mcp-use 2.7.3-canary.2 → 2.7.3

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.
@@ -61,7 +61,7 @@ var __defProp=Object.defineProperty;var __getOwnPropNames=Object.getOwnPropertyN
61
61
 
62
62
  `)}doc.write("payload.value = newResult;"),doc.write("return payload;");let fn=doc.compile();return(payload,ctx)=>fn(shape,payload,ctx)},fastpass,isObject2=isObject,jit=!globalConfig.jitless,fastEnabled=jit&&allowsEval.value,catchall=def.catchall,value;inst._zod.parse=(payload,ctx)=>{value??(value=_normalized.value);let input=payload.value;return isObject2(input)?jit&&fastEnabled&&ctx?.async===!1&&ctx.jitless!==!0?(fastpass||(fastpass=generateFastpass(def.shape)),payload=fastpass(payload,ctx),catchall?handleCatchall([],input,payload,ctx,value,inst):payload):superParse(payload,ctx):(payload.issues.push({expected:"object",code:"invalid_type",input,inst}),payload)}});$ZodUnion=$constructor("$ZodUnion",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"optin",()=>def.options.some(o=>o._zod.optin==="optional")?"optional":void 0),defineLazy(inst._zod,"optout",()=>def.options.some(o=>o._zod.optout==="optional")?"optional":void 0),defineLazy(inst._zod,"values",()=>{if(def.options.every(o=>o._zod.values))return new Set(def.options.flatMap(option=>Array.from(option._zod.values)))}),defineLazy(inst._zod,"pattern",()=>{if(def.options.every(o=>o._zod.pattern)){let patterns=def.options.map(o=>o._zod.pattern);return new RegExp(`^(${patterns.map(p=>cleanRegex(p.source)).join("|")})$`)}});let first=def.options.length===1?def.options[0]._zod.run:null;inst._zod.parse=(payload,ctx)=>{if(first)return first(payload,ctx);let async=!1,results=[];for(let option of def.options){let result=option._zod.run({value:payload.value,issues:[]},ctx);if(result instanceof Promise)results.push(result),async=!0;else{if(result.issues.length===0)return result;results.push(result)}}return async?Promise.all(results).then(results2=>handleUnionResults(results2,payload,inst,ctx)):handleUnionResults(results,payload,inst,ctx)}}),$ZodDiscriminatedUnion=$constructor("$ZodDiscriminatedUnion",(inst,def)=>{def.inclusive=!1,$ZodUnion.init(inst,def);let _super=inst._zod.parse;defineLazy(inst._zod,"propValues",()=>{let propValues={};for(let option of def.options){let pv=option._zod.propValues;if(!pv||Object.keys(pv).length===0)throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);for(let[k,v]of Object.entries(pv)){propValues[k]||(propValues[k]=new Set);for(let val of v)propValues[k].add(val)}}return propValues});let disc=cached(()=>{let opts=def.options,map=new Map;for(let o of opts){let values=o._zod.propValues?.[def.discriminator];if(!values||values.size===0)throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`);for(let v of values){if(map.has(v))throw new Error(`Duplicate discriminator value "${String(v)}"`);map.set(v,o)}}return map});inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!isObject(input))return payload.issues.push({code:"invalid_type",expected:"object",input,inst}),payload;let opt=disc.value.get(input?.[def.discriminator]);return opt?opt._zod.run(payload,ctx):def.unionFallback||ctx.direction==="backward"?_super(payload,ctx):(payload.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:def.discriminator,options:Array.from(disc.value.keys()),input,path:[def.discriminator],inst}),payload)}}),$ZodIntersection=$constructor("$ZodIntersection",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{let input=payload.value,left=def.left._zod.run({value:input,issues:[]},ctx),right=def.right._zod.run({value:input,issues:[]},ctx);return left instanceof Promise||right instanceof Promise?Promise.all([left,right]).then(([left2,right2])=>handleIntersectionResults(payload,left2,right2)):handleIntersectionResults(payload,left,right)}});$ZodRecord=$constructor("$ZodRecord",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!isPlainObject(input))return payload.issues.push({expected:"record",code:"invalid_type",input,inst}),payload;let proms=[],values=def.keyType._zod.values;if(values){payload.value={};let recordKeys=new Set;for(let key of values)if(typeof key=="string"||typeof key=="number"||typeof key=="symbol"){recordKeys.add(typeof key=="number"?key.toString():key);let keyResult=def.keyType._zod.run({value:key,issues:[]},ctx);if(keyResult instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(keyResult.issues.length){payload.issues.push({code:"invalid_key",origin:"record",issues:keyResult.issues.map(iss=>finalizeIssue(iss,ctx,config())),input:key,path:[key],inst});continue}let outKey=keyResult.value,result=def.valueType._zod.run({value:input[key],issues:[]},ctx);result instanceof Promise?proms.push(result.then(result2=>{result2.issues.length&&payload.issues.push(...prefixIssues(key,result2.issues)),payload.value[outKey]=result2.value})):(result.issues.length&&payload.issues.push(...prefixIssues(key,result.issues)),payload.value[outKey]=result.value)}let unrecognized;for(let key in input)recordKeys.has(key)||(unrecognized=unrecognized??[],unrecognized.push(key));unrecognized&&unrecognized.length>0&&payload.issues.push({code:"unrecognized_keys",input,inst,keys:unrecognized})}else{payload.value={};for(let key of Reflect.ownKeys(input)){if(key==="__proto__"||!Object.prototype.propertyIsEnumerable.call(input,key))continue;let keyResult=def.keyType._zod.run({value:key,issues:[]},ctx);if(keyResult instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof key=="string"&&number.test(key)&&keyResult.issues.length){let retryResult=def.keyType._zod.run({value:Number(key),issues:[]},ctx);if(retryResult instanceof Promise)throw new Error("Async schemas not supported in object keys currently");retryResult.issues.length===0&&(keyResult=retryResult)}if(keyResult.issues.length){def.mode==="loose"?payload.value[key]=input[key]:payload.issues.push({code:"invalid_key",origin:"record",issues:keyResult.issues.map(iss=>finalizeIssue(iss,ctx,config())),input:key,path:[key],inst});continue}let result=def.valueType._zod.run({value:input[key],issues:[]},ctx);result instanceof Promise?proms.push(result.then(result2=>{result2.issues.length&&payload.issues.push(...prefixIssues(key,result2.issues)),payload.value[keyResult.value]=result2.value})):(result.issues.length&&payload.issues.push(...prefixIssues(key,result.issues)),payload.value[keyResult.value]=result.value)}}return proms.length?Promise.all(proms).then(()=>payload):payload}}),$ZodEnum=$constructor("$ZodEnum",(inst,def)=>{$ZodType.init(inst,def);let values=getEnumValues(def.entries),valuesSet=new Set(values);inst._zod.values=valuesSet,inst._zod.pattern=new RegExp(`^(${values.filter(k=>propertyKeyTypes.has(typeof k)).map(o=>typeof o=="string"?escapeRegex(o):o.toString()).join("|")})$`),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;return valuesSet.has(input)||payload.issues.push({code:"invalid_value",values,input,inst}),payload}}),$ZodLiteral=$constructor("$ZodLiteral",(inst,def)=>{if($ZodType.init(inst,def),def.values.length===0)throw new Error("Cannot create literal schema with no valid values");let values=new Set(def.values);inst._zod.values=values,inst._zod.pattern=new RegExp(`^(${def.values.map(o=>typeof o=="string"?escapeRegex(o):o?escapeRegex(o.toString()):String(o)).join("|")})$`),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;return values.has(input)||payload.issues.push({code:"invalid_value",values:def.values,input,inst}),payload}}),$ZodTransform=$constructor("$ZodTransform",(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin="optional",inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")throw new $ZodEncodeError(inst.constructor.name);let _out=def.transform(payload.value,payload);if(ctx.async)return(_out instanceof Promise?_out:Promise.resolve(_out)).then(output2=>(payload.value=output2,payload.fallback=!0,payload));if(_out instanceof Promise)throw new $ZodAsyncError;return payload.value=_out,payload.fallback=!0,payload}});$ZodOptional=$constructor("$ZodOptional",(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin="optional",inst._zod.optout="optional",defineLazy(inst._zod,"values",()=>def.innerType._zod.values?new Set([...def.innerType._zod.values,void 0]):void 0),defineLazy(inst._zod,"pattern",()=>{let pattern=def.innerType._zod.pattern;return pattern?new RegExp(`^(${cleanRegex(pattern.source)})?$`):void 0}),inst._zod.parse=(payload,ctx)=>{if(def.innerType._zod.optin==="optional"){let input=payload.value,result=def.innerType._zod.run(payload,ctx);return result instanceof Promise?result.then(r=>handleOptionalResult(r,input)):handleOptionalResult(result,input)}return payload.value===void 0?payload:def.innerType._zod.run(payload,ctx)}}),$ZodExactOptional=$constructor("$ZodExactOptional",(inst,def)=>{$ZodOptional.init(inst,def),defineLazy(inst._zod,"values",()=>def.innerType._zod.values),defineLazy(inst._zod,"pattern",()=>def.innerType._zod.pattern),inst._zod.parse=(payload,ctx)=>def.innerType._zod.run(payload,ctx)}),$ZodNullable=$constructor("$ZodNullable",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"optin",()=>def.innerType._zod.optin),defineLazy(inst._zod,"optout",()=>def.innerType._zod.optout),defineLazy(inst._zod,"pattern",()=>{let pattern=def.innerType._zod.pattern;return pattern?new RegExp(`^(${cleanRegex(pattern.source)}|null)$`):void 0}),defineLazy(inst._zod,"values",()=>def.innerType._zod.values?new Set([...def.innerType._zod.values,null]):void 0),inst._zod.parse=(payload,ctx)=>payload.value===null?payload:def.innerType._zod.run(payload,ctx)}),$ZodDefault=$constructor("$ZodDefault",(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin="optional",defineLazy(inst._zod,"values",()=>def.innerType._zod.values),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")return def.innerType._zod.run(payload,ctx);if(payload.value===void 0)return payload.value=def.defaultValue,payload;let result=def.innerType._zod.run(payload,ctx);return result instanceof Promise?result.then(result2=>handleDefaultResult(result2,def)):handleDefaultResult(result,def)}});$ZodPrefault=$constructor("$ZodPrefault",(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin="optional",defineLazy(inst._zod,"values",()=>def.innerType._zod.values),inst._zod.parse=(payload,ctx)=>(ctx.direction==="backward"||payload.value===void 0&&(payload.value=def.defaultValue),def.innerType._zod.run(payload,ctx))}),$ZodNonOptional=$constructor("$ZodNonOptional",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"values",()=>{let v=def.innerType._zod.values;return v?new Set([...v].filter(x=>x!==void 0)):void 0}),inst._zod.parse=(payload,ctx)=>{let result=def.innerType._zod.run(payload,ctx);return result instanceof Promise?result.then(result2=>handleNonOptionalResult(result2,inst)):handleNonOptionalResult(result,inst)}});$ZodCatch=$constructor("$ZodCatch",(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin="optional",defineLazy(inst._zod,"optout",()=>def.innerType._zod.optout),defineLazy(inst._zod,"values",()=>def.innerType._zod.values),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")return def.innerType._zod.run(payload,ctx);let result=def.innerType._zod.run(payload,ctx);return result instanceof Promise?result.then(result2=>(payload.value=result2.value,result2.issues.length&&(payload.value=def.catchValue({...payload,error:{issues:result2.issues.map(iss=>finalizeIssue(iss,ctx,config()))},input:payload.value}),payload.issues=[],payload.fallback=!0),payload)):(payload.value=result.value,result.issues.length&&(payload.value=def.catchValue({...payload,error:{issues:result.issues.map(iss=>finalizeIssue(iss,ctx,config()))},input:payload.value}),payload.issues=[],payload.fallback=!0),payload)}}),$ZodPipe=$constructor("$ZodPipe",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"values",()=>def.in._zod.values),defineLazy(inst._zod,"optin",()=>def.in._zod.optin),defineLazy(inst._zod,"optout",()=>def.out._zod.optout),defineLazy(inst._zod,"propValues",()=>def.in._zod.propValues),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward"){let right=def.out._zod.run(payload,ctx);return right instanceof Promise?right.then(right2=>handlePipeResult(right2,def.in,ctx)):handlePipeResult(right,def.in,ctx)}let left=def.in._zod.run(payload,ctx);return left instanceof Promise?left.then(left2=>handlePipeResult(left2,def.out,ctx)):handlePipeResult(left,def.out,ctx)}});$ZodPreprocess=$constructor("$ZodPreprocess",(inst,def)=>{$ZodPipe.init(inst,def)}),$ZodReadonly=$constructor("$ZodReadonly",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"propValues",()=>def.innerType._zod.propValues),defineLazy(inst._zod,"values",()=>def.innerType._zod.values),defineLazy(inst._zod,"optin",()=>def.innerType?._zod?.optin),defineLazy(inst._zod,"optout",()=>def.innerType?._zod?.optout),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")return def.innerType._zod.run(payload,ctx);let result=def.innerType._zod.run(payload,ctx);return result instanceof Promise?result.then(handleReadonlyResult):handleReadonlyResult(result)}});$ZodLazy=$constructor("$ZodLazy",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"innerType",()=>{let d=def;return d._cachedInner||(d._cachedInner=def.getter()),d._cachedInner}),defineLazy(inst._zod,"pattern",()=>inst._zod.innerType?._zod?.pattern),defineLazy(inst._zod,"propValues",()=>inst._zod.innerType?._zod?.propValues),defineLazy(inst._zod,"optin",()=>inst._zod.innerType?._zod?.optin??void 0),defineLazy(inst._zod,"optout",()=>inst._zod.innerType?._zod?.optout??void 0),inst._zod.parse=(payload,ctx)=>inst._zod.innerType._zod.run(payload,ctx)}),$ZodCustom=$constructor("$ZodCustom",(inst,def)=>{$ZodCheck.init(inst,def),$ZodType.init(inst,def),inst._zod.parse=(payload,_)=>payload,inst._zod.check=payload=>{let input=payload.value,r=def.fn(input);if(r instanceof Promise)return r.then(r2=>handleRefineResult(r2,payload,input,inst));handleRefineResult(r,payload,input,inst)}})}});function en_default(){return{localeError:error()}}var error,init_en=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/en.js"(){"use strict";init_util();error=()=>{let Sizable={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},TypeDictionary={nan:"NaN"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return`Invalid input: expected ${expected}, received ${received}`}case"invalid_value":return issue2.values.length===1?`Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`:`Invalid option: expected one of ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`Too big: expected ${issue2.origin??"value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit??"elements"}`:`Too big: expected ${issue2.origin??"value"} to be ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`:`Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`Invalid string: must start with "${_issue.prefix}"`:_issue.format==="ends_with"?`Invalid string: must end with "${_issue.suffix}"`:_issue.format==="includes"?`Invalid string: must include "${_issue.includes}"`:_issue.format==="regex"?`Invalid string: must match pattern ${_issue.pattern}`:`Invalid ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${issue2.divisor}`;case"unrecognized_keys":return`Unrecognized key${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Invalid key in ${issue2.origin}`;case"invalid_union":return issue2.options&&Array.isArray(issue2.options)&&issue2.options.length>0?`Invalid discriminator value. Expected ${issue2.options.map(o=>`'${o}'`).join(" | ")}`:"Invalid input";case"invalid_element":return`Invalid value in ${issue2.origin}`;default:return"Invalid input"}}}}});var init_locales=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/index.js"(){"use strict"}});function registry(){return new $ZodRegistry}var _a2,$ZodRegistry,globalRegistry,init_registries=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/registries.js"(){"use strict";$ZodRegistry=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(schema2,..._meta){let meta2=_meta[0];return this._map.set(schema2,meta2),meta2&&typeof meta2=="object"&&"id"in meta2&&this._idmap.set(meta2.id,schema2),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(schema2){let meta2=this._map.get(schema2);return meta2&&typeof meta2=="object"&&"id"in meta2&&this._idmap.delete(meta2.id),this._map.delete(schema2),this}get(schema2){let p=schema2._zod.parent;if(p){let pm={...this.get(p)??{}};delete pm.id;let f={...pm,...this._map.get(schema2)};return Object.keys(f).length?f:void 0}return this._map.get(schema2)}has(schema2){return this._map.has(schema2)}};(_a2=globalThis).__zod_globalRegistry??(_a2.__zod_globalRegistry=registry());globalRegistry=globalThis.__zod_globalRegistry}});function _string(Class2,params){return new Class2({type:"string",...normalizeParams(params)})}function _coercedString(Class2,params){return new Class2({type:"string",coerce:!0,...normalizeParams(params)})}function _email(Class2,params){return new Class2({type:"string",format:"email",check:"string_format",abort:!1,...normalizeParams(params)})}function _guid(Class2,params){return new Class2({type:"string",format:"guid",check:"string_format",abort:!1,...normalizeParams(params)})}function _uuid(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,...normalizeParams(params)})}function _uuidv4(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...normalizeParams(params)})}function _uuidv6(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...normalizeParams(params)})}function _uuidv7(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...normalizeParams(params)})}function _url(Class2,params){return new Class2({type:"string",format:"url",check:"string_format",abort:!1,...normalizeParams(params)})}function _emoji2(Class2,params){return new Class2({type:"string",format:"emoji",check:"string_format",abort:!1,...normalizeParams(params)})}function _nanoid(Class2,params){return new Class2({type:"string",format:"nanoid",check:"string_format",abort:!1,...normalizeParams(params)})}function _cuid(Class2,params){return new Class2({type:"string",format:"cuid",check:"string_format",abort:!1,...normalizeParams(params)})}function _cuid2(Class2,params){return new Class2({type:"string",format:"cuid2",check:"string_format",abort:!1,...normalizeParams(params)})}function _ulid(Class2,params){return new Class2({type:"string",format:"ulid",check:"string_format",abort:!1,...normalizeParams(params)})}function _xid(Class2,params){return new Class2({type:"string",format:"xid",check:"string_format",abort:!1,...normalizeParams(params)})}function _ksuid(Class2,params){return new Class2({type:"string",format:"ksuid",check:"string_format",abort:!1,...normalizeParams(params)})}function _ipv4(Class2,params){return new Class2({type:"string",format:"ipv4",check:"string_format",abort:!1,...normalizeParams(params)})}function _ipv6(Class2,params){return new Class2({type:"string",format:"ipv6",check:"string_format",abort:!1,...normalizeParams(params)})}function _cidrv4(Class2,params){return new Class2({type:"string",format:"cidrv4",check:"string_format",abort:!1,...normalizeParams(params)})}function _cidrv6(Class2,params){return new Class2({type:"string",format:"cidrv6",check:"string_format",abort:!1,...normalizeParams(params)})}function _base64(Class2,params){return new Class2({type:"string",format:"base64",check:"string_format",abort:!1,...normalizeParams(params)})}function _base64url(Class2,params){return new Class2({type:"string",format:"base64url",check:"string_format",abort:!1,...normalizeParams(params)})}function _e164(Class2,params){return new Class2({type:"string",format:"e164",check:"string_format",abort:!1,...normalizeParams(params)})}function _jwt(Class2,params){return new Class2({type:"string",format:"jwt",check:"string_format",abort:!1,...normalizeParams(params)})}function _isoDateTime(Class2,params){return new Class2({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...normalizeParams(params)})}function _isoDate(Class2,params){return new Class2({type:"string",format:"date",check:"string_format",...normalizeParams(params)})}function _isoTime(Class2,params){return new Class2({type:"string",format:"time",check:"string_format",precision:null,...normalizeParams(params)})}function _isoDuration(Class2,params){return new Class2({type:"string",format:"duration",check:"string_format",...normalizeParams(params)})}function _number(Class2,params){return new Class2({type:"number",checks:[],...normalizeParams(params)})}function _coercedNumber(Class2,params){return new Class2({type:"number",coerce:!0,checks:[],...normalizeParams(params)})}function _int(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"safeint",...normalizeParams(params)})}function _boolean(Class2,params){return new Class2({type:"boolean",...normalizeParams(params)})}function _coercedBoolean(Class2,params){return new Class2({type:"boolean",coerce:!0,...normalizeParams(params)})}function _coercedBigint(Class2,params){return new Class2({type:"bigint",coerce:!0,...normalizeParams(params)})}function _null2(Class2,params){return new Class2({type:"null",...normalizeParams(params)})}function _any(Class2){return new Class2({type:"any"})}function _unknown(Class2){return new Class2({type:"unknown"})}function _never(Class2,params){return new Class2({type:"never",...normalizeParams(params)})}function _coercedDate(Class2,params){return new Class2({type:"date",coerce:!0,...normalizeParams(params)})}function _lt(value,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value,inclusive:!1})}function _lte(value,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value,inclusive:!0})}function _gt(value,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value,inclusive:!1})}function _gte(value,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value,inclusive:!0})}function _multipleOf(value,params){return new $ZodCheckMultipleOf({check:"multiple_of",...normalizeParams(params),value})}function _maxLength(maximum,params){return new $ZodCheckMaxLength({check:"max_length",...normalizeParams(params),maximum})}function _minLength(minimum,params){return new $ZodCheckMinLength({check:"min_length",...normalizeParams(params),minimum})}function _length(length,params){return new $ZodCheckLengthEquals({check:"length_equals",...normalizeParams(params),length})}function _regex(pattern,params){return new $ZodCheckRegex({check:"string_format",format:"regex",...normalizeParams(params),pattern})}function _lowercase(params){return new $ZodCheckLowerCase({check:"string_format",format:"lowercase",...normalizeParams(params)})}function _uppercase(params){return new $ZodCheckUpperCase({check:"string_format",format:"uppercase",...normalizeParams(params)})}function _includes(includes,params){return new $ZodCheckIncludes({check:"string_format",format:"includes",...normalizeParams(params),includes})}function _startsWith(prefix,params){return new $ZodCheckStartsWith({check:"string_format",format:"starts_with",...normalizeParams(params),prefix})}function _endsWith(suffix,params){return new $ZodCheckEndsWith({check:"string_format",format:"ends_with",...normalizeParams(params),suffix})}function _overwrite(tx){return new $ZodCheckOverwrite({check:"overwrite",tx})}function _normalize(form){return _overwrite(input=>input.normalize(form))}function _trim(){return _overwrite(input=>input.trim())}function _toLowerCase(){return _overwrite(input=>input.toLowerCase())}function _toUpperCase(){return _overwrite(input=>input.toUpperCase())}function _slugify(){return _overwrite(input=>slugify(input))}function _array(Class2,element,params){return new Class2({type:"array",element,...normalizeParams(params)})}function _refine(Class2,fn,_params){return new Class2({type:"custom",check:"custom",fn,...normalizeParams(_params)})}function _superRefine(fn,params){let ch=_check(payload=>(payload.addIssue=issue2=>{if(typeof issue2=="string")payload.issues.push(issue(issue2,payload.value,ch._zod.def));else{let _issue=issue2;_issue.fatal&&(_issue.continue=!1),_issue.code??(_issue.code="custom"),_issue.input??(_issue.input=payload.value),_issue.inst??(_issue.inst=ch),_issue.continue??(_issue.continue=!ch._zod.def.abort),payload.issues.push(issue(_issue))}},fn(payload.value,payload)),params);return ch}function _check(fn,params){let ch=new $ZodCheck({check:"custom",...normalizeParams(params)});return ch._zod.check=fn,ch}var init_api=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/api.js"(){"use strict";init_checks();init_util()}});function initializeContext(params){let target=params?.target??"draft-2020-12";return target==="draft-4"&&(target="draft-04"),target==="draft-7"&&(target="draft-07"),{processors:params.processors??{},metadataRegistry:params?.metadata??globalRegistry,target,unrepresentable:params?.unrepresentable??"throw",override:params?.override??(()=>{}),io:params?.io??"output",counter:0,seen:new Map,cycles:params?.cycles??"ref",reused:params?.reused??"inline",external:params?.external??void 0}}function process2(schema2,ctx,_params={path:[],schemaPath:[]}){var _a3;let def=schema2._zod.def,seen=ctx.seen.get(schema2);if(seen)return seen.count++,_params.schemaPath.includes(schema2)&&(seen.cycle=_params.path),seen.schema;let result={schema:{},count:1,cycle:void 0,path:_params.path};ctx.seen.set(schema2,result);let overrideSchema=schema2._zod.toJSONSchema?.();if(overrideSchema)result.schema=overrideSchema;else{let params={..._params,schemaPath:[..._params.schemaPath,schema2],path:_params.path};if(schema2._zod.processJSONSchema)schema2._zod.processJSONSchema(ctx,result.schema,params);else{let _json=result.schema,processor=ctx.processors[def.type];if(!processor)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);processor(schema2,ctx,_json,params)}let parent=schema2._zod.parent;parent&&(result.ref||(result.ref=parent),process2(parent,ctx,params),ctx.seen.get(parent).isParent=!0)}let meta2=ctx.metadataRegistry.get(schema2);return meta2&&Object.assign(result.schema,meta2),ctx.io==="input"&&isTransforming(schema2)&&(delete result.schema.examples,delete result.schema.default),ctx.io==="input"&&"_prefault"in result.schema&&((_a3=result.schema).default??(_a3.default=result.schema._prefault)),delete result.schema._prefault,ctx.seen.get(schema2).schema}function extractDefs(ctx,schema2){let root=ctx.seen.get(schema2);if(!root)throw new Error("Unprocessed schema. This is a bug in Zod.");let idToSchema=new Map;for(let entry of ctx.seen.entries()){let id=ctx.metadataRegistry.get(entry[0])?.id;if(id){let existing=idToSchema.get(id);if(existing&&existing!==entry[0])throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);idToSchema.set(id,entry[0])}}let makeURI=entry=>{let defsSegment=ctx.target==="draft-2020-12"?"$defs":"definitions";if(ctx.external){let externalId=ctx.external.registry.get(entry[0])?.id,uriGenerator=ctx.external.uri??(id2=>id2);if(externalId)return{ref:uriGenerator(externalId)};let id=entry[1].defId??entry[1].schema.id??`schema${ctx.counter++}`;return entry[1].defId=id,{defId:id,ref:`${uriGenerator("__shared")}#/${defsSegment}/${id}`}}if(entry[1]===root)return{ref:"#"};let defUriPrefix=`#/${defsSegment}/`,defId=entry[1].schema.id??`__schema${ctx.counter++}`;return{defId,ref:defUriPrefix+defId}},extractToDef=entry=>{if(entry[1].schema.$ref)return;let seen=entry[1],{ref,defId}=makeURI(entry);seen.def={...seen.schema},defId&&(seen.defId=defId);let schema3=seen.schema;for(let key in schema3)delete schema3[key];schema3.$ref=ref};if(ctx.cycles==="throw")for(let entry of ctx.seen.entries()){let seen=entry[1];if(seen.cycle)throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/<root>
63
63
 
64
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let entry of ctx.seen.entries()){let seen=entry[1];if(schema2===entry[0]){extractToDef(entry);continue}if(ctx.external){let ext=ctx.external.registry.get(entry[0])?.id;if(schema2!==entry[0]&&ext){extractToDef(entry);continue}}if(ctx.metadataRegistry.get(entry[0])?.id){extractToDef(entry);continue}if(seen.cycle){extractToDef(entry);continue}if(seen.count>1&&ctx.reused==="ref"){extractToDef(entry);continue}}}function finalize(ctx,schema2){let root=ctx.seen.get(schema2);if(!root)throw new Error("Unprocessed schema. This is a bug in Zod.");let flattenRef=zodSchema=>{let seen=ctx.seen.get(zodSchema);if(seen.ref===null)return;let schema3=seen.def??seen.schema,_cached={...schema3},ref=seen.ref;if(seen.ref=null,ref){flattenRef(ref);let refSeen=ctx.seen.get(ref),refSchema=refSeen.schema;if(refSchema.$ref&&(ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0")?(schema3.allOf=schema3.allOf??[],schema3.allOf.push(refSchema)):Object.assign(schema3,refSchema),Object.assign(schema3,_cached),zodSchema._zod.parent===ref)for(let key in schema3)key==="$ref"||key==="allOf"||key in _cached||delete schema3[key];if(refSchema.$ref&&refSeen.def)for(let key in schema3)key==="$ref"||key==="allOf"||key in refSeen.def&&JSON.stringify(schema3[key])===JSON.stringify(refSeen.def[key])&&delete schema3[key]}let parent=zodSchema._zod.parent;if(parent&&parent!==ref){flattenRef(parent);let parentSeen=ctx.seen.get(parent);if(parentSeen?.schema.$ref&&(schema3.$ref=parentSeen.schema.$ref,parentSeen.def))for(let key in schema3)key==="$ref"||key==="allOf"||key in parentSeen.def&&JSON.stringify(schema3[key])===JSON.stringify(parentSeen.def[key])&&delete schema3[key]}ctx.override({zodSchema,jsonSchema:schema3,path:seen.path??[]})};for(let entry of[...ctx.seen.entries()].reverse())flattenRef(entry[0]);let result={};if(ctx.target==="draft-2020-12"?result.$schema="https://json-schema.org/draft/2020-12/schema":ctx.target==="draft-07"?result.$schema="http://json-schema.org/draft-07/schema#":ctx.target==="draft-04"?result.$schema="http://json-schema.org/draft-04/schema#":ctx.target,ctx.external?.uri){let id=ctx.external.registry.get(schema2)?.id;if(!id)throw new Error("Schema is missing an `id` property");result.$id=ctx.external.uri(id)}Object.assign(result,root.def??root.schema);let rootMetaId=ctx.metadataRegistry.get(schema2)?.id;rootMetaId!==void 0&&result.id===rootMetaId&&delete result.id;let defs=ctx.external?.defs??{};for(let entry of ctx.seen.entries()){let seen=entry[1];seen.def&&seen.defId&&(seen.def.id===seen.defId&&delete seen.def.id,defs[seen.defId]=seen.def)}ctx.external||Object.keys(defs).length>0&&(ctx.target==="draft-2020-12"?result.$defs=defs:result.definitions=defs);try{let finalized=JSON.parse(JSON.stringify(result));return Object.defineProperty(finalized,"~standard",{value:{...schema2["~standard"],jsonSchema:{input:createStandardJSONSchemaMethod(schema2,"input",ctx.processors),output:createStandardJSONSchemaMethod(schema2,"output",ctx.processors)}},enumerable:!1,writable:!1}),finalized}catch{throw new Error("Error converting schema to JSON.")}}function isTransforming(_schema,_ctx){let ctx=_ctx??{seen:new Set};if(ctx.seen.has(_schema))return!1;ctx.seen.add(_schema);let def=_schema._zod.def;if(def.type==="transform")return!0;if(def.type==="array")return isTransforming(def.element,ctx);if(def.type==="set")return isTransforming(def.valueType,ctx);if(def.type==="lazy")return isTransforming(def.getter(),ctx);if(def.type==="promise"||def.type==="optional"||def.type==="nonoptional"||def.type==="nullable"||def.type==="readonly"||def.type==="default"||def.type==="prefault")return isTransforming(def.innerType,ctx);if(def.type==="intersection")return isTransforming(def.left,ctx)||isTransforming(def.right,ctx);if(def.type==="record"||def.type==="map")return isTransforming(def.keyType,ctx)||isTransforming(def.valueType,ctx);if(def.type==="pipe")return _schema._zod.traits.has("$ZodCodec")?!0:isTransforming(def.in,ctx)||isTransforming(def.out,ctx);if(def.type==="object"){for(let key in def.shape)if(isTransforming(def.shape[key],ctx))return!0;return!1}if(def.type==="union"){for(let option of def.options)if(isTransforming(option,ctx))return!0;return!1}if(def.type==="tuple"){for(let item of def.items)if(isTransforming(item,ctx))return!0;return!!(def.rest&&isTransforming(def.rest,ctx))}return!1}var createToJSONSchemaMethod,createStandardJSONSchemaMethod,init_to_json_schema=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/to-json-schema.js"(){"use strict";init_registries();createToJSONSchemaMethod=(schema2,processors={})=>params=>{let ctx=initializeContext({...params,processors});return process2(schema2,ctx),extractDefs(ctx,schema2),finalize(ctx,schema2)},createStandardJSONSchemaMethod=(schema2,io,processors={})=>params=>{let{libraryOptions,target}=params??{},ctx=initializeContext({...libraryOptions??{},target,io,processors});return process2(schema2,ctx),extractDefs(ctx,schema2),finalize(ctx,schema2)}}});function toJSONSchema(input,params){if("_idmap"in input){let registry2=input,ctx2=initializeContext({...params,processors:allProcessors}),defs={};for(let entry of registry2._idmap.entries()){let[_,schema2]=entry;process2(schema2,ctx2)}let schemas={},external={registry:registry2,uri:params?.uri,defs};ctx2.external=external;for(let entry of registry2._idmap.entries()){let[key,schema2]=entry;extractDefs(ctx2,schema2),schemas[key]=finalize(ctx2,schema2)}if(Object.keys(defs).length>0){let defsSegment=ctx2.target==="draft-2020-12"?"$defs":"definitions";schemas.__shared={[defsSegment]:defs}}return{schemas}}let ctx=initializeContext({...params,processors:allProcessors});return process2(input,ctx),extractDefs(ctx,input),finalize(ctx,input)}var formatMap,stringProcessor,numberProcessor,booleanProcessor,bigintProcessor,symbolProcessor,nullProcessor,undefinedProcessor,voidProcessor,neverProcessor,anyProcessor,unknownProcessor,dateProcessor,enumProcessor,literalProcessor,nanProcessor,templateLiteralProcessor,fileProcessor,successProcessor,customProcessor,functionProcessor,transformProcessor,mapProcessor,setProcessor,arrayProcessor,objectProcessor,unionProcessor,intersectionProcessor,tupleProcessor,recordProcessor,nullableProcessor,nonoptionalProcessor,defaultProcessor,prefaultProcessor,catchProcessor,pipeProcessor,readonlyProcessor,promiseProcessor,optionalProcessor,lazyProcessor,allProcessors,init_json_schema_processors=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-processors.js"(){"use strict";init_to_json_schema();init_util();formatMap={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},stringProcessor=(schema2,ctx,_json,_params)=>{let json=_json;json.type="string";let{minimum,maximum,format,patterns,contentEncoding}=schema2._zod.bag;if(typeof minimum=="number"&&(json.minLength=minimum),typeof maximum=="number"&&(json.maxLength=maximum),format&&(json.format=formatMap[format]??format,json.format===""&&delete json.format,format==="time"&&delete json.format),contentEncoding&&(json.contentEncoding=contentEncoding),patterns&&patterns.size>0){let regexes=[...patterns];regexes.length===1?json.pattern=regexes[0].source:regexes.length>1&&(json.allOf=[...regexes.map(regex=>({...ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0"?{type:"string"}:{},pattern:regex.source}))])}},numberProcessor=(schema2,ctx,_json,_params)=>{let json=_json,{minimum,maximum,format,multipleOf,exclusiveMaximum,exclusiveMinimum}=schema2._zod.bag;typeof format=="string"&&format.includes("int")?json.type="integer":json.type="number";let exMin=typeof exclusiveMinimum=="number"&&exclusiveMinimum>=(minimum??Number.NEGATIVE_INFINITY),exMax=typeof exclusiveMaximum=="number"&&exclusiveMaximum<=(maximum??Number.POSITIVE_INFINITY),legacy=ctx.target==="draft-04"||ctx.target==="openapi-3.0";exMin?legacy?(json.minimum=exclusiveMinimum,json.exclusiveMinimum=!0):json.exclusiveMinimum=exclusiveMinimum:typeof minimum=="number"&&(json.minimum=minimum),exMax?legacy?(json.maximum=exclusiveMaximum,json.exclusiveMaximum=!0):json.exclusiveMaximum=exclusiveMaximum:typeof maximum=="number"&&(json.maximum=maximum),typeof multipleOf=="number"&&(json.multipleOf=multipleOf)},booleanProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"},bigintProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},symbolProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},nullProcessor=(_schema,ctx,json,_params)=>{ctx.target==="openapi-3.0"?(json.type="string",json.nullable=!0,json.enum=[null]):json.type="null"},undefinedProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},voidProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},neverProcessor=(_schema,_ctx,json,_params)=>{json.not={}},anyProcessor=(_schema,_ctx,_json,_params)=>{},unknownProcessor=(_schema,_ctx,_json,_params)=>{},dateProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},enumProcessor=(schema2,_ctx,json,_params)=>{let def=schema2._zod.def,values=getEnumValues(def.entries);values.every(v=>typeof v=="number")&&(json.type="number"),values.every(v=>typeof v=="string")&&(json.type="string"),json.enum=values},literalProcessor=(schema2,ctx,json,_params)=>{let def=schema2._zod.def,vals=[];for(let val of def.values)if(val===void 0){if(ctx.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof val=="bigint"){if(ctx.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");vals.push(Number(val))}else vals.push(val);if(vals.length!==0)if(vals.length===1){let val=vals[0];json.type=val===null?"null":typeof val,ctx.target==="draft-04"||ctx.target==="openapi-3.0"?json.enum=[val]:json.const=val}else vals.every(v=>typeof v=="number")&&(json.type="number"),vals.every(v=>typeof v=="string")&&(json.type="string"),vals.every(v=>typeof v=="boolean")&&(json.type="boolean"),vals.every(v=>v===null)&&(json.type="null"),json.enum=vals},nanProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},templateLiteralProcessor=(schema2,_ctx,json,_params)=>{let _json=json,pattern=schema2._zod.pattern;if(!pattern)throw new Error("Pattern not found in template literal");_json.type="string",_json.pattern=pattern.source},fileProcessor=(schema2,_ctx,json,_params)=>{let _json=json,file={type:"string",format:"binary",contentEncoding:"binary"},{minimum,maximum,mime}=schema2._zod.bag;minimum!==void 0&&(file.minLength=minimum),maximum!==void 0&&(file.maxLength=maximum),mime?mime.length===1?(file.contentMediaType=mime[0],Object.assign(_json,file)):(Object.assign(_json,file),_json.anyOf=mime.map(m=>({contentMediaType:m}))):Object.assign(_json,file)},successProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"},customProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},functionProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},transformProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},mapProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},setProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},arrayProcessor=(schema2,ctx,_json,params)=>{let json=_json,def=schema2._zod.def,{minimum,maximum}=schema2._zod.bag;typeof minimum=="number"&&(json.minItems=minimum),typeof maximum=="number"&&(json.maxItems=maximum),json.type="array",json.items=process2(def.element,ctx,{...params,path:[...params.path,"items"]})},objectProcessor=(schema2,ctx,_json,params)=>{let json=_json,def=schema2._zod.def;json.type="object",json.properties={};let shape=def.shape;for(let key in shape)json.properties[key]=process2(shape[key],ctx,{...params,path:[...params.path,"properties",key]});let allKeys=new Set(Object.keys(shape)),requiredKeys=new Set([...allKeys].filter(key=>{let v=def.shape[key]._zod;return ctx.io==="input"?v.optin===void 0:v.optout===void 0}));requiredKeys.size>0&&(json.required=Array.from(requiredKeys)),def.catchall?._zod.def.type==="never"?json.additionalProperties=!1:def.catchall?def.catchall&&(json.additionalProperties=process2(def.catchall,ctx,{...params,path:[...params.path,"additionalProperties"]})):ctx.io==="output"&&(json.additionalProperties=!1)},unionProcessor=(schema2,ctx,json,params)=>{let def=schema2._zod.def,isExclusive=def.inclusive===!1,options=def.options.map((x,i)=>process2(x,ctx,{...params,path:[...params.path,isExclusive?"oneOf":"anyOf",i]}));isExclusive?json.oneOf=options:json.anyOf=options},intersectionProcessor=(schema2,ctx,json,params)=>{let def=schema2._zod.def,a=process2(def.left,ctx,{...params,path:[...params.path,"allOf",0]}),b=process2(def.right,ctx,{...params,path:[...params.path,"allOf",1]}),isSimpleIntersection=val=>"allOf"in val&&Object.keys(val).length===1,allOf=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(b)?b.allOf:[b]];json.allOf=allOf},tupleProcessor=(schema2,ctx,_json,params)=>{let json=_json,def=schema2._zod.def;json.type="array";let prefixPath=ctx.target==="draft-2020-12"?"prefixItems":"items",restPath=ctx.target==="draft-2020-12"||ctx.target==="openapi-3.0"?"items":"additionalItems",prefixItems=def.items.map((x,i)=>process2(x,ctx,{...params,path:[...params.path,prefixPath,i]})),rest=def.rest?process2(def.rest,ctx,{...params,path:[...params.path,restPath,...ctx.target==="openapi-3.0"?[def.items.length]:[]]}):null;ctx.target==="draft-2020-12"?(json.prefixItems=prefixItems,rest&&(json.items=rest)):ctx.target==="openapi-3.0"?(json.items={anyOf:prefixItems},rest&&json.items.anyOf.push(rest),json.minItems=prefixItems.length,rest||(json.maxItems=prefixItems.length)):(json.items=prefixItems,rest&&(json.additionalItems=rest));let{minimum,maximum}=schema2._zod.bag;typeof minimum=="number"&&(json.minItems=minimum),typeof maximum=="number"&&(json.maxItems=maximum)},recordProcessor=(schema2,ctx,_json,params)=>{let json=_json,def=schema2._zod.def;json.type="object";let keyType=def.keyType,patterns=keyType._zod.bag?.patterns;if(def.mode==="loose"&&patterns&&patterns.size>0){let valueSchema=process2(def.valueType,ctx,{...params,path:[...params.path,"patternProperties","*"]});json.patternProperties={};for(let pattern of patterns)json.patternProperties[pattern.source]=valueSchema}else(ctx.target==="draft-07"||ctx.target==="draft-2020-12")&&(json.propertyNames=process2(def.keyType,ctx,{...params,path:[...params.path,"propertyNames"]})),json.additionalProperties=process2(def.valueType,ctx,{...params,path:[...params.path,"additionalProperties"]});let keyValues=keyType._zod.values;if(keyValues){let validKeyValues=[...keyValues].filter(v=>typeof v=="string"||typeof v=="number");validKeyValues.length>0&&(json.required=validKeyValues)}},nullableProcessor=(schema2,ctx,json,params)=>{let def=schema2._zod.def,inner=process2(def.innerType,ctx,params),seen=ctx.seen.get(schema2);ctx.target==="openapi-3.0"?(seen.ref=def.innerType,json.nullable=!0):json.anyOf=[inner,{type:"null"}]},nonoptionalProcessor=(schema2,ctx,_json,params)=>{let def=schema2._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema2);seen.ref=def.innerType},defaultProcessor=(schema2,ctx,json,params)=>{let def=schema2._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema2);seen.ref=def.innerType,json.default=JSON.parse(JSON.stringify(def.defaultValue))},prefaultProcessor=(schema2,ctx,json,params)=>{let def=schema2._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema2);seen.ref=def.innerType,ctx.io==="input"&&(json._prefault=JSON.parse(JSON.stringify(def.defaultValue)))},catchProcessor=(schema2,ctx,json,params)=>{let def=schema2._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema2);seen.ref=def.innerType;let catchValue;try{catchValue=def.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}json.default=catchValue},pipeProcessor=(schema2,ctx,_json,params)=>{let def=schema2._zod.def,inIsTransform=def.in._zod.traits.has("$ZodTransform"),innerType=ctx.io==="input"?inIsTransform?def.out:def.in:def.out;process2(innerType,ctx,params);let seen=ctx.seen.get(schema2);seen.ref=innerType},readonlyProcessor=(schema2,ctx,json,params)=>{let def=schema2._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema2);seen.ref=def.innerType,json.readOnly=!0},promiseProcessor=(schema2,ctx,_json,params)=>{let def=schema2._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema2);seen.ref=def.innerType},optionalProcessor=(schema2,ctx,_json,params)=>{let def=schema2._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema2);seen.ref=def.innerType},lazyProcessor=(schema2,ctx,_json,params)=>{let innerType=schema2._zod.innerType;process2(innerType,ctx,params);let seen=ctx.seen.get(schema2);seen.ref=innerType},allProcessors={string:stringProcessor,number:numberProcessor,boolean:booleanProcessor,bigint:bigintProcessor,symbol:symbolProcessor,null:nullProcessor,undefined:undefinedProcessor,void:voidProcessor,never:neverProcessor,any:anyProcessor,unknown:unknownProcessor,date:dateProcessor,enum:enumProcessor,literal:literalProcessor,nan:nanProcessor,template_literal:templateLiteralProcessor,file:fileProcessor,success:successProcessor,custom:customProcessor,function:functionProcessor,transform:transformProcessor,map:mapProcessor,set:setProcessor,array:arrayProcessor,object:objectProcessor,union:unionProcessor,intersection:intersectionProcessor,tuple:tupleProcessor,record:recordProcessor,nullable:nullableProcessor,nonoptional:nonoptionalProcessor,default:defaultProcessor,prefault:prefaultProcessor,catch:catchProcessor,pipe:pipeProcessor,readonly:readonlyProcessor,promise:promiseProcessor,optional:optionalProcessor,lazy:lazyProcessor}}});var init_json_schema=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema.js"(){"use strict"}});var init_core2=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/index.js"(){"use strict";init_core();init_parse();init_errors();init_schemas();init_checks();init_versions();init_util();init_regexes();init_locales();init_registries();init_doc();init_api();init_to_json_schema();init_json_schema()}});var init_checks2=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/checks.js"(){"use strict";init_core2()}});var iso_exports={};__export(iso_exports,{ZodISODate:()=>ZodISODate,ZodISODateTime:()=>ZodISODateTime,ZodISODuration:()=>ZodISODuration,ZodISOTime:()=>ZodISOTime,date:()=>date2,datetime:()=>datetime2,duration:()=>duration2,time:()=>time2});function datetime2(params){return _isoDateTime(ZodISODateTime,params)}function date2(params){return _isoDate(ZodISODate,params)}function time2(params){return _isoTime(ZodISOTime,params)}function duration2(params){return _isoDuration(ZodISODuration,params)}var ZodISODateTime,ZodISODate,ZodISOTime,ZodISODuration,init_iso=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/iso.js"(){"use strict";init_core2();init_schemas2();ZodISODateTime=$constructor("ZodISODateTime",(inst,def)=>{$ZodISODateTime.init(inst,def),ZodStringFormat.init(inst,def)});ZodISODate=$constructor("ZodISODate",(inst,def)=>{$ZodISODate.init(inst,def),ZodStringFormat.init(inst,def)});ZodISOTime=$constructor("ZodISOTime",(inst,def)=>{$ZodISOTime.init(inst,def),ZodStringFormat.init(inst,def)});ZodISODuration=$constructor("ZodISODuration",(inst,def)=>{$ZodISODuration.init(inst,def),ZodStringFormat.init(inst,def)})}});var initializer2,ZodRealError,init_errors2=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/errors.js"(){"use strict";init_core2();init_core2();init_util();initializer2=(inst,issues)=>{$ZodError.init(inst,issues),inst.name="ZodError",Object.defineProperties(inst,{format:{value:mapper=>formatError(inst,mapper)},flatten:{value:mapper=>flattenError(inst,mapper)},addIssue:{value:issue2=>{inst.issues.push(issue2),inst.message=JSON.stringify(inst.issues,jsonStringifyReplacer,2)}},addIssues:{value:issues2=>{inst.issues.push(...issues2),inst.message=JSON.stringify(inst.issues,jsonStringifyReplacer,2)}},isEmpty:{get(){return inst.issues.length===0}}})},ZodRealError=$constructor("ZodError",initializer2,{Parent:Error})}});var parse2,parseAsync2,safeParse2,safeParseAsync2,encode,decode,encodeAsync,decodeAsync,safeEncode,safeDecode,safeEncodeAsync,safeDecodeAsync,init_parse2=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/parse.js"(){"use strict";init_core2();init_errors2();parse2=_parse(ZodRealError),parseAsync2=_parseAsync(ZodRealError),safeParse2=_safeParse(ZodRealError),safeParseAsync2=_safeParseAsync(ZodRealError),encode=_encode(ZodRealError),decode=_decode(ZodRealError),encodeAsync=_encodeAsync(ZodRealError),decodeAsync=_decodeAsync(ZodRealError),safeEncode=_safeEncode(ZodRealError),safeDecode=_safeDecode(ZodRealError),safeEncodeAsync=_safeEncodeAsync(ZodRealError),safeDecodeAsync=_safeDecodeAsync(ZodRealError)}});function _installLazyMethods(inst,group,methods){let proto=Object.getPrototypeOf(inst),installed=_installedGroups.get(proto);if(installed||(installed=new Set,_installedGroups.set(proto,installed)),!installed.has(group)){installed.add(group);for(let key in methods){let fn=methods[key];Object.defineProperty(proto,key,{configurable:!0,enumerable:!1,get(){let bound=fn.bind(this);return Object.defineProperty(this,key,{configurable:!0,writable:!0,enumerable:!0,value:bound}),bound},set(v){Object.defineProperty(this,key,{configurable:!0,writable:!0,enumerable:!0,value:v})}})}}}function string2(params){return _string(ZodString,params)}function email2(params){return _email(ZodEmail,params)}function url(params){return _url(ZodURL,params)}function number2(params){return _number(ZodNumber,params)}function int(params){return _int(ZodNumberFormat,params)}function boolean2(params){return _boolean(ZodBoolean,params)}function _null3(params){return _null2(ZodNull,params)}function any(){return _any(ZodAny)}function unknown(){return _unknown(ZodUnknown)}function never(params){return _never(ZodNever,params)}function array(element,params){return _array(ZodArray,element,params)}function object(shape,params){let def={type:"object",shape:shape??{},...util_exports.normalizeParams(params)};return new ZodObject(def)}function looseObject(shape,params){return new ZodObject({type:"object",shape,catchall:unknown(),...util_exports.normalizeParams(params)})}function union(options,params){return new ZodUnion({type:"union",options,...util_exports.normalizeParams(params)})}function discriminatedUnion(discriminator,options,params){return new ZodDiscriminatedUnion({type:"union",options,discriminator,...util_exports.normalizeParams(params)})}function intersection(left,right){return new ZodIntersection({type:"intersection",left,right})}function record(keyType,valueType,params){return!valueType||!valueType._zod?new ZodRecord({type:"record",keyType:string2(),valueType:keyType,...util_exports.normalizeParams(valueType)}):new ZodRecord({type:"record",keyType,valueType,...util_exports.normalizeParams(params)})}function _enum(values,params){let entries=Array.isArray(values)?Object.fromEntries(values.map(v=>[v,v])):values;return new ZodEnum({type:"enum",entries,...util_exports.normalizeParams(params)})}function literal(value,params){return new ZodLiteral({type:"literal",values:Array.isArray(value)?value:[value],...util_exports.normalizeParams(params)})}function transform(fn){return new ZodTransform({type:"transform",transform:fn})}function optional(innerType){return new ZodOptional({type:"optional",innerType})}function exactOptional(innerType){return new ZodExactOptional({type:"optional",innerType})}function nullable(innerType){return new ZodNullable({type:"nullable",innerType})}function _default(innerType,defaultValue){return new ZodDefault({type:"default",innerType,get defaultValue(){return typeof defaultValue=="function"?defaultValue():util_exports.shallowClone(defaultValue)}})}function prefault(innerType,defaultValue){return new ZodPrefault({type:"prefault",innerType,get defaultValue(){return typeof defaultValue=="function"?defaultValue():util_exports.shallowClone(defaultValue)}})}function nonoptional(innerType,params){return new ZodNonOptional({type:"nonoptional",innerType,...util_exports.normalizeParams(params)})}function _catch(innerType,catchValue){return new ZodCatch({type:"catch",innerType,catchValue:typeof catchValue=="function"?catchValue:()=>catchValue})}function pipe(in_,out){return new ZodPipe({type:"pipe",in:in_,out})}function readonly(innerType){return new ZodReadonly({type:"readonly",innerType})}function lazy(getter){return new ZodLazy({type:"lazy",getter})}function refine(fn,_params={}){return _refine(ZodCustom,fn,_params)}function superRefine(fn,params){return _superRefine(fn,params)}function preprocess(fn,schema2){return new ZodPreprocess({type:"pipe",in:transform(fn),out:schema2})}var _installedGroups,ZodType,_ZodString,ZodString,ZodStringFormat,ZodEmail,ZodGUID,ZodUUID,ZodURL,ZodEmoji,ZodNanoID,ZodCUID,ZodCUID2,ZodULID,ZodXID,ZodKSUID,ZodIPv4,ZodIPv6,ZodCIDRv4,ZodCIDRv6,ZodBase64,ZodBase64URL,ZodE164,ZodJWT,ZodNumber,ZodNumberFormat,ZodBoolean,ZodBigInt,ZodNull,ZodAny,ZodUnknown,ZodNever,ZodDate,ZodArray,ZodObject,ZodUnion,ZodDiscriminatedUnion,ZodIntersection,ZodRecord,ZodEnum,ZodLiteral,ZodTransform,ZodOptional,ZodExactOptional,ZodNullable,ZodDefault,ZodPrefault,ZodNonOptional,ZodCatch,ZodPipe,ZodPreprocess,ZodReadonly,ZodLazy,ZodCustom,init_schemas2=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js"(){"use strict";init_core2();init_core2();init_json_schema_processors();init_to_json_schema();init_checks2();init_iso();init_parse2();_installedGroups=new WeakMap;ZodType=$constructor("ZodType",(inst,def)=>($ZodType.init(inst,def),Object.assign(inst["~standard"],{jsonSchema:{input:createStandardJSONSchemaMethod(inst,"input"),output:createStandardJSONSchemaMethod(inst,"output")}}),inst.toJSONSchema=createToJSONSchemaMethod(inst,{}),inst.def=def,inst.type=def.type,Object.defineProperty(inst,"_def",{value:def}),inst.parse=(data,params)=>parse2(inst,data,params,{callee:inst.parse}),inst.safeParse=(data,params)=>safeParse2(inst,data,params),inst.parseAsync=async(data,params)=>parseAsync2(inst,data,params,{callee:inst.parseAsync}),inst.safeParseAsync=async(data,params)=>safeParseAsync2(inst,data,params),inst.spa=inst.safeParseAsync,inst.encode=(data,params)=>encode(inst,data,params),inst.decode=(data,params)=>decode(inst,data,params),inst.encodeAsync=async(data,params)=>encodeAsync(inst,data,params),inst.decodeAsync=async(data,params)=>decodeAsync(inst,data,params),inst.safeEncode=(data,params)=>safeEncode(inst,data,params),inst.safeDecode=(data,params)=>safeDecode(inst,data,params),inst.safeEncodeAsync=async(data,params)=>safeEncodeAsync(inst,data,params),inst.safeDecodeAsync=async(data,params)=>safeDecodeAsync(inst,data,params),_installLazyMethods(inst,"ZodType",{check(...chks){let def2=this.def;return this.clone(util_exports.mergeDefs(def2,{checks:[...def2.checks??[],...chks.map(ch=>typeof ch=="function"?{_zod:{check:ch,def:{check:"custom"},onattach:[]}}:ch)]}),{parent:!0})},with(...chks){return this.check(...chks)},clone(def2,params){return clone(this,def2,params)},brand(){return this},register(reg,meta2){return reg.add(this,meta2),this},refine(check,params){return this.check(refine(check,params))},superRefine(refinement,params){return this.check(superRefine(refinement,params))},overwrite(fn){return this.check(_overwrite(fn))},optional(){return optional(this)},exactOptional(){return exactOptional(this)},nullable(){return nullable(this)},nullish(){return optional(nullable(this))},nonoptional(params){return nonoptional(this,params)},array(){return array(this)},or(arg){return union([this,arg])},and(arg){return intersection(this,arg)},transform(tx){return pipe(this,transform(tx))},default(d){return _default(this,d)},prefault(d){return prefault(this,d)},catch(params){return _catch(this,params)},pipe(target){return pipe(this,target)},readonly(){return readonly(this)},describe(description){let cl=this.clone();return globalRegistry.add(cl,{description}),cl},meta(...args){if(args.length===0)return globalRegistry.get(this);let cl=this.clone();return globalRegistry.add(cl,args[0]),cl},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(fn){return fn(this)}}),Object.defineProperty(inst,"description",{get(){return globalRegistry.get(inst)?.description},configurable:!0}),inst)),_ZodString=$constructor("_ZodString",(inst,def)=>{$ZodString.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>stringProcessor(inst,ctx,json,params);let bag=inst._zod.bag;inst.format=bag.format??null,inst.minLength=bag.minimum??null,inst.maxLength=bag.maximum??null,_installLazyMethods(inst,"_ZodString",{regex(...args){return this.check(_regex(...args))},includes(...args){return this.check(_includes(...args))},startsWith(...args){return this.check(_startsWith(...args))},endsWith(...args){return this.check(_endsWith(...args))},min(...args){return this.check(_minLength(...args))},max(...args){return this.check(_maxLength(...args))},length(...args){return this.check(_length(...args))},nonempty(...args){return this.check(_minLength(1,...args))},lowercase(params){return this.check(_lowercase(params))},uppercase(params){return this.check(_uppercase(params))},trim(){return this.check(_trim())},normalize(...args){return this.check(_normalize(...args))},toLowerCase(){return this.check(_toLowerCase())},toUpperCase(){return this.check(_toUpperCase())},slugify(){return this.check(_slugify())}})}),ZodString=$constructor("ZodString",(inst,def)=>{$ZodString.init(inst,def),_ZodString.init(inst,def),inst.email=params=>inst.check(_email(ZodEmail,params)),inst.url=params=>inst.check(_url(ZodURL,params)),inst.jwt=params=>inst.check(_jwt(ZodJWT,params)),inst.emoji=params=>inst.check(_emoji2(ZodEmoji,params)),inst.guid=params=>inst.check(_guid(ZodGUID,params)),inst.uuid=params=>inst.check(_uuid(ZodUUID,params)),inst.uuidv4=params=>inst.check(_uuidv4(ZodUUID,params)),inst.uuidv6=params=>inst.check(_uuidv6(ZodUUID,params)),inst.uuidv7=params=>inst.check(_uuidv7(ZodUUID,params)),inst.nanoid=params=>inst.check(_nanoid(ZodNanoID,params)),inst.guid=params=>inst.check(_guid(ZodGUID,params)),inst.cuid=params=>inst.check(_cuid(ZodCUID,params)),inst.cuid2=params=>inst.check(_cuid2(ZodCUID2,params)),inst.ulid=params=>inst.check(_ulid(ZodULID,params)),inst.base64=params=>inst.check(_base64(ZodBase64,params)),inst.base64url=params=>inst.check(_base64url(ZodBase64URL,params)),inst.xid=params=>inst.check(_xid(ZodXID,params)),inst.ksuid=params=>inst.check(_ksuid(ZodKSUID,params)),inst.ipv4=params=>inst.check(_ipv4(ZodIPv4,params)),inst.ipv6=params=>inst.check(_ipv6(ZodIPv6,params)),inst.cidrv4=params=>inst.check(_cidrv4(ZodCIDRv4,params)),inst.cidrv6=params=>inst.check(_cidrv6(ZodCIDRv6,params)),inst.e164=params=>inst.check(_e164(ZodE164,params)),inst.datetime=params=>inst.check(datetime2(params)),inst.date=params=>inst.check(date2(params)),inst.time=params=>inst.check(time2(params)),inst.duration=params=>inst.check(duration2(params))});ZodStringFormat=$constructor("ZodStringFormat",(inst,def)=>{$ZodStringFormat.init(inst,def),_ZodString.init(inst,def)}),ZodEmail=$constructor("ZodEmail",(inst,def)=>{$ZodEmail.init(inst,def),ZodStringFormat.init(inst,def)});ZodGUID=$constructor("ZodGUID",(inst,def)=>{$ZodGUID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodUUID=$constructor("ZodUUID",(inst,def)=>{$ZodUUID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodURL=$constructor("ZodURL",(inst,def)=>{$ZodURL.init(inst,def),ZodStringFormat.init(inst,def)});ZodEmoji=$constructor("ZodEmoji",(inst,def)=>{$ZodEmoji.init(inst,def),ZodStringFormat.init(inst,def)}),ZodNanoID=$constructor("ZodNanoID",(inst,def)=>{$ZodNanoID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodCUID=$constructor("ZodCUID",(inst,def)=>{$ZodCUID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodCUID2=$constructor("ZodCUID2",(inst,def)=>{$ZodCUID2.init(inst,def),ZodStringFormat.init(inst,def)}),ZodULID=$constructor("ZodULID",(inst,def)=>{$ZodULID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodXID=$constructor("ZodXID",(inst,def)=>{$ZodXID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodKSUID=$constructor("ZodKSUID",(inst,def)=>{$ZodKSUID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodIPv4=$constructor("ZodIPv4",(inst,def)=>{$ZodIPv4.init(inst,def),ZodStringFormat.init(inst,def)}),ZodIPv6=$constructor("ZodIPv6",(inst,def)=>{$ZodIPv6.init(inst,def),ZodStringFormat.init(inst,def)}),ZodCIDRv4=$constructor("ZodCIDRv4",(inst,def)=>{$ZodCIDRv4.init(inst,def),ZodStringFormat.init(inst,def)}),ZodCIDRv6=$constructor("ZodCIDRv6",(inst,def)=>{$ZodCIDRv6.init(inst,def),ZodStringFormat.init(inst,def)}),ZodBase64=$constructor("ZodBase64",(inst,def)=>{$ZodBase64.init(inst,def),ZodStringFormat.init(inst,def)}),ZodBase64URL=$constructor("ZodBase64URL",(inst,def)=>{$ZodBase64URL.init(inst,def),ZodStringFormat.init(inst,def)}),ZodE164=$constructor("ZodE164",(inst,def)=>{$ZodE164.init(inst,def),ZodStringFormat.init(inst,def)}),ZodJWT=$constructor("ZodJWT",(inst,def)=>{$ZodJWT.init(inst,def),ZodStringFormat.init(inst,def)}),ZodNumber=$constructor("ZodNumber",(inst,def)=>{$ZodNumber.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>numberProcessor(inst,ctx,json,params),_installLazyMethods(inst,"ZodNumber",{gt(value,params){return this.check(_gt(value,params))},gte(value,params){return this.check(_gte(value,params))},min(value,params){return this.check(_gte(value,params))},lt(value,params){return this.check(_lt(value,params))},lte(value,params){return this.check(_lte(value,params))},max(value,params){return this.check(_lte(value,params))},int(params){return this.check(int(params))},safe(params){return this.check(int(params))},positive(params){return this.check(_gt(0,params))},nonnegative(params){return this.check(_gte(0,params))},negative(params){return this.check(_lt(0,params))},nonpositive(params){return this.check(_lte(0,params))},multipleOf(value,params){return this.check(_multipleOf(value,params))},step(value,params){return this.check(_multipleOf(value,params))},finite(){return this}});let bag=inst._zod.bag;inst.minValue=Math.max(bag.minimum??Number.NEGATIVE_INFINITY,bag.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,inst.maxValue=Math.min(bag.maximum??Number.POSITIVE_INFINITY,bag.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,inst.isInt=(bag.format??"").includes("int")||Number.isSafeInteger(bag.multipleOf??.5),inst.isFinite=!0,inst.format=bag.format??null});ZodNumberFormat=$constructor("ZodNumberFormat",(inst,def)=>{$ZodNumberFormat.init(inst,def),ZodNumber.init(inst,def)});ZodBoolean=$constructor("ZodBoolean",(inst,def)=>{$ZodBoolean.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>booleanProcessor(inst,ctx,json,params)});ZodBigInt=$constructor("ZodBigInt",(inst,def)=>{$ZodBigInt.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>bigintProcessor(inst,ctx,json,params),inst.gte=(value,params)=>inst.check(_gte(value,params)),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.gt=(value,params)=>inst.check(_gt(value,params)),inst.gte=(value,params)=>inst.check(_gte(value,params)),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.lt=(value,params)=>inst.check(_lt(value,params)),inst.lte=(value,params)=>inst.check(_lte(value,params)),inst.max=(value,params)=>inst.check(_lte(value,params)),inst.positive=params=>inst.check(_gt(BigInt(0),params)),inst.negative=params=>inst.check(_lt(BigInt(0),params)),inst.nonpositive=params=>inst.check(_lte(BigInt(0),params)),inst.nonnegative=params=>inst.check(_gte(BigInt(0),params)),inst.multipleOf=(value,params)=>inst.check(_multipleOf(value,params));let bag=inst._zod.bag;inst.minValue=bag.minimum??null,inst.maxValue=bag.maximum??null,inst.format=bag.format??null}),ZodNull=$constructor("ZodNull",(inst,def)=>{$ZodNull.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nullProcessor(inst,ctx,json,params)});ZodAny=$constructor("ZodAny",(inst,def)=>{$ZodAny.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>anyProcessor(inst,ctx,json,params)});ZodUnknown=$constructor("ZodUnknown",(inst,def)=>{$ZodUnknown.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>unknownProcessor(inst,ctx,json,params)});ZodNever=$constructor("ZodNever",(inst,def)=>{$ZodNever.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>neverProcessor(inst,ctx,json,params)});ZodDate=$constructor("ZodDate",(inst,def)=>{$ZodDate.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>dateProcessor(inst,ctx,json,params),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.max=(value,params)=>inst.check(_lte(value,params));let c=inst._zod.bag;inst.minDate=c.minimum?new Date(c.minimum):null,inst.maxDate=c.maximum?new Date(c.maximum):null}),ZodArray=$constructor("ZodArray",(inst,def)=>{$ZodArray.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>arrayProcessor(inst,ctx,json,params),inst.element=def.element,_installLazyMethods(inst,"ZodArray",{min(n,params){return this.check(_minLength(n,params))},nonempty(params){return this.check(_minLength(1,params))},max(n,params){return this.check(_maxLength(n,params))},length(n,params){return this.check(_length(n,params))},unwrap(){return this.element}})});ZodObject=$constructor("ZodObject",(inst,def)=>{$ZodObjectJIT.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>objectProcessor(inst,ctx,json,params),util_exports.defineLazy(inst,"shape",()=>def.shape),_installLazyMethods(inst,"ZodObject",{keyof(){return _enum(Object.keys(this._zod.def.shape))},catchall(catchall){return this.clone({...this._zod.def,catchall})},passthrough(){return this.clone({...this._zod.def,catchall:unknown()})},loose(){return this.clone({...this._zod.def,catchall:unknown()})},strict(){return this.clone({...this._zod.def,catchall:never()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(incoming){return util_exports.extend(this,incoming)},safeExtend(incoming){return util_exports.safeExtend(this,incoming)},merge(other){return util_exports.merge(this,other)},pick(mask){return util_exports.pick(this,mask)},omit(mask){return util_exports.omit(this,mask)},partial(...args){return util_exports.partial(ZodOptional,this,args[0])},required(...args){return util_exports.required(ZodNonOptional,this,args[0])}})});ZodUnion=$constructor("ZodUnion",(inst,def)=>{$ZodUnion.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>unionProcessor(inst,ctx,json,params),inst.options=def.options});ZodDiscriminatedUnion=$constructor("ZodDiscriminatedUnion",(inst,def)=>{ZodUnion.init(inst,def),$ZodDiscriminatedUnion.init(inst,def)});ZodIntersection=$constructor("ZodIntersection",(inst,def)=>{$ZodIntersection.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>intersectionProcessor(inst,ctx,json,params)});ZodRecord=$constructor("ZodRecord",(inst,def)=>{$ZodRecord.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>recordProcessor(inst,ctx,json,params),inst.keyType=def.keyType,inst.valueType=def.valueType});ZodEnum=$constructor("ZodEnum",(inst,def)=>{$ZodEnum.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>enumProcessor(inst,ctx,json,params),inst.enum=def.entries,inst.options=Object.values(def.entries);let keys=new Set(Object.keys(def.entries));inst.extract=(values,params)=>{let newEntries={};for(let value of values)if(keys.has(value))newEntries[value]=def.entries[value];else throw new Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...util_exports.normalizeParams(params),entries:newEntries})},inst.exclude=(values,params)=>{let newEntries={...def.entries};for(let value of values)if(keys.has(value))delete newEntries[value];else throw new Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...util_exports.normalizeParams(params),entries:newEntries})}});ZodLiteral=$constructor("ZodLiteral",(inst,def)=>{$ZodLiteral.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>literalProcessor(inst,ctx,json,params),inst.values=new Set(def.values),Object.defineProperty(inst,"value",{get(){if(def.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return def.values[0]}})});ZodTransform=$constructor("ZodTransform",(inst,def)=>{$ZodTransform.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>transformProcessor(inst,ctx,json,params),inst._zod.parse=(payload,_ctx)=>{if(_ctx.direction==="backward")throw new $ZodEncodeError(inst.constructor.name);payload.addIssue=issue2=>{if(typeof issue2=="string")payload.issues.push(util_exports.issue(issue2,payload.value,def));else{let _issue=issue2;_issue.fatal&&(_issue.continue=!1),_issue.code??(_issue.code="custom"),_issue.input??(_issue.input=payload.value),_issue.inst??(_issue.inst=inst),payload.issues.push(util_exports.issue(_issue))}};let output=def.transform(payload.value,payload);return output instanceof Promise?output.then(output2=>(payload.value=output2,payload.fallback=!0,payload)):(payload.value=output,payload.fallback=!0,payload)}});ZodOptional=$constructor("ZodOptional",(inst,def)=>{$ZodOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>optionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodExactOptional=$constructor("ZodExactOptional",(inst,def)=>{$ZodExactOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>optionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodNullable=$constructor("ZodNullable",(inst,def)=>{$ZodNullable.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nullableProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodDefault=$constructor("ZodDefault",(inst,def)=>{$ZodDefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>defaultProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeDefault=inst.unwrap});ZodPrefault=$constructor("ZodPrefault",(inst,def)=>{$ZodPrefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>prefaultProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodNonOptional=$constructor("ZodNonOptional",(inst,def)=>{$ZodNonOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nonoptionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodCatch=$constructor("ZodCatch",(inst,def)=>{$ZodCatch.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>catchProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeCatch=inst.unwrap});ZodPipe=$constructor("ZodPipe",(inst,def)=>{$ZodPipe.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>pipeProcessor(inst,ctx,json,params),inst.in=def.in,inst.out=def.out});ZodPreprocess=$constructor("ZodPreprocess",(inst,def)=>{ZodPipe.init(inst,def),$ZodPreprocess.init(inst,def)}),ZodReadonly=$constructor("ZodReadonly",(inst,def)=>{$ZodReadonly.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>readonlyProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodLazy=$constructor("ZodLazy",(inst,def)=>{$ZodLazy.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>lazyProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.getter()});ZodCustom=$constructor("ZodCustom",(inst,def)=>{$ZodCustom.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>customProcessor(inst,ctx,json,params)})}});var ZodIssueCode,ZodFirstPartyTypeKind,init_compat=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/compat.js"(){"use strict";ZodIssueCode={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={})}});var coerce_exports={};__export(coerce_exports,{bigint:()=>bigint2,boolean:()=>boolean3,date:()=>date3,number:()=>number3,string:()=>string3});function string3(params){return _coercedString(ZodString,params)}function number3(params){return _coercedNumber(ZodNumber,params)}function boolean3(params){return _coercedBoolean(ZodBoolean,params)}function bigint2(params){return _coercedBigint(ZodBigInt,params)}function date3(params){return _coercedDate(ZodDate,params)}var init_coerce=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/coerce.js"(){"use strict";init_core2();init_schemas2()}});var init_external=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js"(){"use strict";init_core2();init_schemas2();init_checks2();init_errors2();init_parse2();init_compat();init_core2();init_en();init_core2();init_json_schema_processors();init_locales();init_iso();init_coerce();config(en_default())}});var init_classic=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/index.js"(){"use strict";init_external()}});var init_v4=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/index.js"(){"use strict";init_classic()}});var LATEST_PROTOCOL_VERSION,DEFAULT_NEGOTIATED_PROTOCOL_VERSION,SUPPORTED_PROTOCOL_VERSIONS,RELATED_TASK_META_KEY,PROTOCOL_VERSION_META_KEY,CLIENT_INFO_META_KEY,SERVER_INFO_META_KEY,CLIENT_CAPABILITIES_META_KEY,SUBSCRIPTION_ID_META_KEY,LOG_LEVEL_META_KEY,JSONRPC_VERSION,INVALID_PARAMS,JSONValueSchema,JSONObjectSchema,JSONArraySchema,ProgressTokenSchema,CursorSchema,TaskMetadataSchema,RelatedTaskMetadataSchema,RequestMetaSchema,BaseRequestParamsSchema,TaskAugmentedRequestParamsSchema,RequestSchema,NotificationsParamsSchema,NotificationSchema,ResultMetaObjectSchema,ResultSchema,RequestIdSchema,JSONRPCRequestSchema,JSONRPCNotificationSchema,JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema,JSONRPCMessageSchema,JSONRPCResponseSchema,EmptyResultSchema,CancelledNotificationParamsSchema,CancelledNotificationSchema,IconSchema,IconsSchema,BaseMetadataSchema,ImplementationSchema,FormElicitationCapabilitySchema,ElicitationCapabilitySchema,ClientTasksCapabilitySchema,ServerTasksCapabilitySchema,ClientCapabilitiesSchema,InitializeRequestParamsSchema,InitializeRequestSchema,ServerCapabilitiesSchema,InitializeResultSchema,InitializedNotificationSchema,DiscoverRequestSchema,DiscoverResultSchema,PingRequestSchema,ProgressSchema,ProgressNotificationParamsSchema,ProgressNotificationSchema,PaginatedRequestParamsSchema,PaginatedRequestSchema,PaginatedResultSchema,ResourceContentsSchema,TextResourceContentsSchema,Base64Schema,BlobResourceContentsSchema,RoleSchema,AnnotationsSchema,ResourceSchema,ResourceTemplateSchema,ListResourcesRequestSchema,ListResourcesResultSchema,ListResourceTemplatesRequestSchema,ListResourceTemplatesResultSchema,ResourceRequestParamsSchema,ReadResourceRequestParamsSchema,ReadResourceRequestSchema,ReadResourceResultSchema,ResourceListChangedNotificationSchema,SubscribeRequestParamsSchema,SubscribeRequestSchema,UnsubscribeRequestParamsSchema,UnsubscribeRequestSchema,SubscriptionFilterSchema,SubscriptionsListenRequestParamsSchema,SubscriptionsListenRequestSchema,SubscriptionsAcknowledgedNotificationParamsSchema,SubscriptionsAcknowledgedNotificationSchema,SubscriptionsListenResultMetaSchema,SubscriptionsListenResultSchema,ResourceUpdatedNotificationParamsSchema,ResourceUpdatedNotificationSchema,PromptArgumentSchema,PromptSchema,ListPromptsRequestSchema,ListPromptsResultSchema,GetPromptRequestParamsSchema,GetPromptRequestSchema,TextContentSchema,ImageContentSchema,AudioContentSchema,ToolUseContentSchema,EmbeddedResourceSchema,ResourceLinkSchema,ContentBlockSchema,PromptMessageSchema,GetPromptResultSchema,PromptListChangedNotificationSchema,ToolAnnotationsSchema,ToolExecutionSchema,ToolSchema,ListToolsRequestSchema,ListToolsResultSchema,CallToolResultSchema,CompatibilityCallToolResultSchema,CallToolRequestParamsSchema,CallToolRequestSchema,ToolListChangedNotificationSchema,ListChangedOptionsBaseSchema,LoggingLevelSchema,SetLevelRequestParamsSchema,SetLevelRequestSchema,LoggingMessageNotificationParamsSchema,LoggingMessageNotificationSchema,ModelHintSchema,ModelPreferencesSchema,ToolChoiceSchema,ToolResultContentSchema,SamplingContentSchema,SamplingMessageContentBlockSchema,SamplingMessageSchema,CreateMessageRequestParamsSchema,CreateMessageRequestSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,BooleanSchemaSchema,StringSchemaSchema,NumberSchemaSchema,UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema,LegacyTitledEnumSchemaSchema,SingleSelectEnumSchemaSchema,UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema,MultiSelectEnumSchemaSchema,EnumSchemaSchema,PrimitiveSchemaDefinitionSchema,ElicitRequestFormParamsSchema,ElicitRequestURLParamsSchema,ElicitRequestParamsSchema,ElicitRequestSchema,ElicitationCompleteNotificationParamsSchema,ElicitationCompleteNotificationSchema,ElicitResultSchema,ResourceTemplateReferenceSchema,PromptReferenceSchema,CompleteRequestParamsSchema,CompleteRequestSchema,CompleteResultSchema,RootSchema,ListRootsRequestSchema,ListRootsResultSchema,RootsListChangedNotificationSchema,TaskCreationParamsSchema,TaskStatusSchema,TaskSchema,CreateTaskResultSchema,TaskStatusNotificationParamsSchema,TaskStatusNotificationSchema,GetTaskRequestSchema,GetTaskResultSchema,GetTaskPayloadRequestSchema,GetTaskPayloadResultSchema,ListTasksRequestSchema,ListTasksResultSchema,CancelTaskRequestSchema,CancelTaskResultSchema,ClientRequestSchema,ClientNotificationSchema,ClientResultSchema,ServerRequestSchema,ServerNotificationSchema,ServerResultSchema,SafeUrlSchema,OAuthProtectedResourceMetadataSchema,OAuthMetadataSchema,OpenIdProviderMetadataSchema,OpenIdProviderDiscoveryMetadataSchema,OAuthTokensSchema,IdJagTokenExchangeResponseSchema,OAuthErrorResponseSchema,OptionalSafeUrlSchema,OAuthClientMetadataSchema,OAuthClientInformationSchema,OAuthClientInformationFullSchema,OAuthClientRegistrationErrorSchema,OAuthTokenRevocationRequestSchema,init_auth_CUe6YdwF=__esm({"../../node_modules/.pnpm/@modelcontextprotocol+core@2.0.0/node_modules/@modelcontextprotocol/core/dist/auth-CUe6YdwF.mjs"(){"use strict";init_v4();LATEST_PROTOCOL_VERSION="2025-11-25",DEFAULT_NEGOTIATED_PROTOCOL_VERSION="2025-03-26",SUPPORTED_PROTOCOL_VERSIONS=[LATEST_PROTOCOL_VERSION,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],RELATED_TASK_META_KEY="io.modelcontextprotocol/related-task",PROTOCOL_VERSION_META_KEY="io.modelcontextprotocol/protocolVersion",CLIENT_INFO_META_KEY="io.modelcontextprotocol/clientInfo",SERVER_INFO_META_KEY="io.modelcontextprotocol/serverInfo",CLIENT_CAPABILITIES_META_KEY="io.modelcontextprotocol/clientCapabilities",SUBSCRIPTION_ID_META_KEY="io.modelcontextprotocol/subscriptionId",LOG_LEVEL_META_KEY="io.modelcontextprotocol/logLevel",JSONRPC_VERSION="2.0",INVALID_PARAMS=-32602,JSONValueSchema=lazy(()=>union([string2(),number2(),boolean2(),_null3(),record(string2(),JSONValueSchema),array(JSONValueSchema)])),JSONObjectSchema=record(string2(),JSONValueSchema),JSONArraySchema=array(JSONValueSchema),ProgressTokenSchema=union([string2(),number2().int()]),CursorSchema=string2(),TaskMetadataSchema=object({ttl:number2().optional()}),RelatedTaskMetadataSchema=object({taskId:string2()}),RequestMetaSchema=looseObject({progressToken:ProgressTokenSchema.optional(),[RELATED_TASK_META_KEY]:RelatedTaskMetadataSchema.optional()}),BaseRequestParamsSchema=object({_meta:RequestMetaSchema.optional()}),TaskAugmentedRequestParamsSchema=BaseRequestParamsSchema.extend({task:TaskMetadataSchema.optional()}),RequestSchema=object({method:string2(),params:BaseRequestParamsSchema.loose().optional()}),NotificationsParamsSchema=object({_meta:RequestMetaSchema.optional()}),NotificationSchema=object({method:string2(),params:NotificationsParamsSchema.loose().optional()}),ResultMetaObjectSchema=looseObject({get[SERVER_INFO_META_KEY](){return ImplementationSchema.optional().catch(void 0)}}),ResultSchema=looseObject({_meta:ResultMetaObjectSchema.optional()}),RequestIdSchema=union([string2(),number2().int()]),JSONRPCRequestSchema=object({jsonrpc:literal(JSONRPC_VERSION),id:RequestIdSchema,...RequestSchema.shape}).strict(),JSONRPCNotificationSchema=object({jsonrpc:literal(JSONRPC_VERSION),...NotificationSchema.shape}).strict(),JSONRPCResultResponseSchema=object({jsonrpc:literal(JSONRPC_VERSION),id:RequestIdSchema,result:ResultSchema}).strict(),JSONRPCErrorResponseSchema=object({jsonrpc:literal(JSONRPC_VERSION),id:RequestIdSchema.optional(),error:object({code:number2().int(),message:string2(),data:unknown().optional()})}).strict(),JSONRPCMessageSchema=union([JSONRPCRequestSchema,JSONRPCNotificationSchema,JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),JSONRPCResponseSchema=union([JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),EmptyResultSchema=ResultSchema.strict(),CancelledNotificationParamsSchema=NotificationsParamsSchema.extend({requestId:RequestIdSchema.optional(),reason:string2().optional()}),CancelledNotificationSchema=NotificationSchema.extend({method:literal("notifications/cancelled"),params:CancelledNotificationParamsSchema}),IconSchema=object({src:string2(),mimeType:string2().optional(),sizes:array(string2()).optional(),theme:_enum(["light","dark"]).optional()}),IconsSchema=object({icons:array(IconSchema).optional()}),BaseMetadataSchema=object({name:string2(),title:string2().optional()}),ImplementationSchema=BaseMetadataSchema.extend({...BaseMetadataSchema.shape,...IconsSchema.shape,version:string2(),websiteUrl:string2().optional(),description:string2().optional()}),FormElicitationCapabilitySchema=intersection(object({applyDefaults:boolean2().optional()}),JSONObjectSchema),ElicitationCapabilitySchema=preprocess(value=>value&&typeof value=="object"&&!Array.isArray(value)&&Object.keys(value).length===0?{form:{}}:value,intersection(object({form:FormElicitationCapabilitySchema.optional(),url:JSONObjectSchema.optional()}),JSONObjectSchema.optional())),ClientTasksCapabilitySchema=looseObject({list:JSONObjectSchema.optional(),cancel:JSONObjectSchema.optional(),requests:looseObject({sampling:looseObject({createMessage:JSONObjectSchema.optional()}).optional(),elicitation:looseObject({create:JSONObjectSchema.optional()}).optional()}).optional()}),ServerTasksCapabilitySchema=looseObject({list:JSONObjectSchema.optional(),cancel:JSONObjectSchema.optional(),requests:looseObject({tools:looseObject({call:JSONObjectSchema.optional()}).optional()}).optional()}),ClientCapabilitiesSchema=object({experimental:record(string2(),JSONObjectSchema).optional(),sampling:object({context:JSONObjectSchema.optional(),tools:JSONObjectSchema.optional()}).optional(),elicitation:ElicitationCapabilitySchema.optional(),roots:object({listChanged:boolean2().optional()}).optional(),tasks:ClientTasksCapabilitySchema.optional(),extensions:record(string2(),JSONObjectSchema).optional()}),InitializeRequestParamsSchema=BaseRequestParamsSchema.extend({protocolVersion:string2(),capabilities:ClientCapabilitiesSchema,clientInfo:ImplementationSchema}),InitializeRequestSchema=RequestSchema.extend({method:literal("initialize"),params:InitializeRequestParamsSchema}),ServerCapabilitiesSchema=object({experimental:record(string2(),JSONObjectSchema).optional(),logging:JSONObjectSchema.optional(),completions:JSONObjectSchema.optional(),prompts:object({listChanged:boolean2().optional()}).optional(),resources:object({subscribe:boolean2().optional(),listChanged:boolean2().optional()}).optional(),tools:object({listChanged:boolean2().optional()}).optional(),tasks:ServerTasksCapabilitySchema.optional(),extensions:record(string2(),JSONObjectSchema).optional()}),InitializeResultSchema=ResultSchema.extend({protocolVersion:string2(),capabilities:ServerCapabilitiesSchema,serverInfo:ImplementationSchema,instructions:string2().optional()}),InitializedNotificationSchema=NotificationSchema.extend({method:literal("notifications/initialized"),params:NotificationsParamsSchema.optional()}),DiscoverRequestSchema=RequestSchema.extend({method:literal("server/discover"),params:BaseRequestParamsSchema.optional()}),DiscoverResultSchema=ResultSchema.extend({supportedVersions:array(string2()),capabilities:ServerCapabilitiesSchema,instructions:string2().optional()}),PingRequestSchema=RequestSchema.extend({method:literal("ping"),params:BaseRequestParamsSchema.optional()}),ProgressSchema=object({progress:number2(),total:optional(number2()),message:optional(string2())}),ProgressNotificationParamsSchema=object({...NotificationsParamsSchema.shape,...ProgressSchema.shape,progressToken:ProgressTokenSchema}),ProgressNotificationSchema=NotificationSchema.extend({method:literal("notifications/progress"),params:ProgressNotificationParamsSchema}),PaginatedRequestParamsSchema=BaseRequestParamsSchema.extend({cursor:CursorSchema.optional()}),PaginatedRequestSchema=RequestSchema.extend({params:PaginatedRequestParamsSchema.optional()}),PaginatedResultSchema=ResultSchema.extend({nextCursor:CursorSchema.optional()}),ResourceContentsSchema=object({uri:string2(),mimeType:optional(string2()),_meta:record(string2(),unknown()).optional()}),TextResourceContentsSchema=ResourceContentsSchema.extend({text:string2()}),Base64Schema=string2().refine(val=>{try{return atob(val),!0}catch{return!1}},{message:"Invalid Base64 string"}),BlobResourceContentsSchema=ResourceContentsSchema.extend({blob:Base64Schema}),RoleSchema=_enum(["user","assistant"]),AnnotationsSchema=object({audience:array(RoleSchema).optional(),priority:number2().min(0).max(1).optional(),lastModified:iso_exports.datetime({offset:!0}).optional()}),ResourceSchema=object({...BaseMetadataSchema.shape,...IconsSchema.shape,uri:string2(),description:optional(string2()),mimeType:optional(string2()),size:optional(number2()),annotations:AnnotationsSchema.optional(),_meta:optional(looseObject({}))}),ResourceTemplateSchema=object({...BaseMetadataSchema.shape,...IconsSchema.shape,uriTemplate:string2(),description:optional(string2()),mimeType:optional(string2()),annotations:AnnotationsSchema.optional(),_meta:optional(looseObject({}))}),ListResourcesRequestSchema=PaginatedRequestSchema.extend({method:literal("resources/list")}),ListResourcesResultSchema=PaginatedResultSchema.extend({resources:array(ResourceSchema)}),ListResourceTemplatesRequestSchema=PaginatedRequestSchema.extend({method:literal("resources/templates/list")}),ListResourceTemplatesResultSchema=PaginatedResultSchema.extend({resourceTemplates:array(ResourceTemplateSchema)}),ResourceRequestParamsSchema=BaseRequestParamsSchema.extend({uri:string2()}),ReadResourceRequestParamsSchema=ResourceRequestParamsSchema,ReadResourceRequestSchema=RequestSchema.extend({method:literal("resources/read"),params:ReadResourceRequestParamsSchema}),ReadResourceResultSchema=ResultSchema.extend({contents:array(union([TextResourceContentsSchema,BlobResourceContentsSchema]))}),ResourceListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/resources/list_changed"),params:NotificationsParamsSchema.optional()}),SubscribeRequestParamsSchema=ResourceRequestParamsSchema,SubscribeRequestSchema=RequestSchema.extend({method:literal("resources/subscribe"),params:SubscribeRequestParamsSchema}),UnsubscribeRequestParamsSchema=ResourceRequestParamsSchema,UnsubscribeRequestSchema=RequestSchema.extend({method:literal("resources/unsubscribe"),params:UnsubscribeRequestParamsSchema}),SubscriptionFilterSchema=object({toolsListChanged:boolean2().optional(),promptsListChanged:boolean2().optional(),resourcesListChanged:boolean2().optional(),resourceSubscriptions:array(string2()).optional()}),SubscriptionsListenRequestParamsSchema=BaseRequestParamsSchema.extend({notifications:SubscriptionFilterSchema}),SubscriptionsListenRequestSchema=RequestSchema.extend({method:literal("subscriptions/listen"),params:SubscriptionsListenRequestParamsSchema}),SubscriptionsAcknowledgedNotificationParamsSchema=NotificationsParamsSchema.extend({notifications:SubscriptionFilterSchema}),SubscriptionsAcknowledgedNotificationSchema=NotificationSchema.extend({method:literal("notifications/subscriptions/acknowledged"),params:SubscriptionsAcknowledgedNotificationParamsSchema}),SubscriptionsListenResultMetaSchema=ResultMetaObjectSchema.extend({[SUBSCRIPTION_ID_META_KEY]:RequestIdSchema}),SubscriptionsListenResultSchema=ResultSchema.extend({_meta:SubscriptionsListenResultMetaSchema}),ResourceUpdatedNotificationParamsSchema=NotificationsParamsSchema.extend({uri:string2()}),ResourceUpdatedNotificationSchema=NotificationSchema.extend({method:literal("notifications/resources/updated"),params:ResourceUpdatedNotificationParamsSchema}),PromptArgumentSchema=object({name:string2(),description:optional(string2()),required:optional(boolean2())}),PromptSchema=object({...BaseMetadataSchema.shape,...IconsSchema.shape,description:optional(string2()),arguments:optional(array(PromptArgumentSchema)),_meta:optional(looseObject({}))}),ListPromptsRequestSchema=PaginatedRequestSchema.extend({method:literal("prompts/list")}),ListPromptsResultSchema=PaginatedResultSchema.extend({prompts:array(PromptSchema)}),GetPromptRequestParamsSchema=BaseRequestParamsSchema.extend({name:string2(),arguments:record(string2(),string2()).optional()}),GetPromptRequestSchema=RequestSchema.extend({method:literal("prompts/get"),params:GetPromptRequestParamsSchema}),TextContentSchema=object({type:literal("text"),text:string2(),annotations:AnnotationsSchema.optional(),_meta:record(string2(),unknown()).optional()}),ImageContentSchema=object({type:literal("image"),data:Base64Schema,mimeType:string2(),annotations:AnnotationsSchema.optional(),_meta:record(string2(),unknown()).optional()}),AudioContentSchema=object({type:literal("audio"),data:Base64Schema,mimeType:string2(),annotations:AnnotationsSchema.optional(),_meta:record(string2(),unknown()).optional()}),ToolUseContentSchema=object({type:literal("tool_use"),name:string2(),id:string2(),input:record(string2(),unknown()),_meta:record(string2(),unknown()).optional()}),EmbeddedResourceSchema=object({type:literal("resource"),resource:union([TextResourceContentsSchema,BlobResourceContentsSchema]),annotations:AnnotationsSchema.optional(),_meta:record(string2(),unknown()).optional()}),ResourceLinkSchema=ResourceSchema.extend({type:literal("resource_link")}),ContentBlockSchema=union([TextContentSchema,ImageContentSchema,AudioContentSchema,ResourceLinkSchema,EmbeddedResourceSchema]),PromptMessageSchema=object({role:RoleSchema,content:ContentBlockSchema}),GetPromptResultSchema=ResultSchema.extend({description:string2().optional(),messages:array(PromptMessageSchema)}),PromptListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/prompts/list_changed"),params:NotificationsParamsSchema.optional()}),ToolAnnotationsSchema=object({title:string2().optional(),readOnlyHint:boolean2().optional(),destructiveHint:boolean2().optional(),idempotentHint:boolean2().optional(),openWorldHint:boolean2().optional()}),ToolExecutionSchema=object({taskSupport:_enum(["required","optional","forbidden"]).optional()}),ToolSchema=object({...BaseMetadataSchema.shape,...IconsSchema.shape,description:string2().optional(),inputSchema:object({type:literal("object"),properties:record(string2(),JSONValueSchema).optional(),required:array(string2()).optional()}).catchall(unknown()),outputSchema:looseObject({$schema:string2().optional()}).optional(),annotations:ToolAnnotationsSchema.optional(),execution:ToolExecutionSchema.optional(),_meta:record(string2(),unknown()).optional()}),ListToolsRequestSchema=PaginatedRequestSchema.extend({method:literal("tools/list")}),ListToolsResultSchema=PaginatedResultSchema.extend({tools:array(ToolSchema)}),CallToolResultSchema=ResultSchema.extend({content:array(ContentBlockSchema).default([]),structuredContent:unknown().optional(),isError:boolean2().optional()}),CompatibilityCallToolResultSchema=CallToolResultSchema.or(ResultSchema.extend({toolResult:unknown()})),CallToolRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({name:string2(),arguments:record(string2(),unknown()).optional()}),CallToolRequestSchema=RequestSchema.extend({method:literal("tools/call"),params:CallToolRequestParamsSchema}),ToolListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/tools/list_changed"),params:NotificationsParamsSchema.optional()}),ListChangedOptionsBaseSchema=object({autoRefresh:boolean2().default(!0),debounceMs:number2().int().nonnegative().default(300)}),LoggingLevelSchema=_enum(["debug","info","notice","warning","error","critical","alert","emergency"]),SetLevelRequestParamsSchema=BaseRequestParamsSchema.extend({level:LoggingLevelSchema}),SetLevelRequestSchema=RequestSchema.extend({method:literal("logging/setLevel"),params:SetLevelRequestParamsSchema}),LoggingMessageNotificationParamsSchema=NotificationsParamsSchema.extend({level:LoggingLevelSchema,logger:string2().optional(),data:unknown()}),LoggingMessageNotificationSchema=NotificationSchema.extend({method:literal("notifications/message"),params:LoggingMessageNotificationParamsSchema}),ModelHintSchema=object({name:string2().optional()}),ModelPreferencesSchema=object({hints:array(ModelHintSchema).optional(),costPriority:number2().min(0).max(1).optional(),speedPriority:number2().min(0).max(1).optional(),intelligencePriority:number2().min(0).max(1).optional()}),ToolChoiceSchema=object({mode:_enum(["auto","required","none"]).optional()}),ToolResultContentSchema=object({type:literal("tool_result"),toolUseId:string2().describe("The unique identifier for the corresponding tool call."),content:array(ContentBlockSchema),structuredContent:unknown().optional(),isError:boolean2().optional(),_meta:record(string2(),unknown()).optional()}),SamplingContentSchema=discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema]),SamplingMessageContentBlockSchema=discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema,ToolUseContentSchema,ToolResultContentSchema]),SamplingMessageSchema=object({role:RoleSchema,content:union([SamplingMessageContentBlockSchema,array(SamplingMessageContentBlockSchema)]),_meta:record(string2(),unknown()).optional()}),CreateMessageRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({messages:array(SamplingMessageSchema),modelPreferences:ModelPreferencesSchema.optional(),systemPrompt:string2().optional(),includeContext:_enum(["none","thisServer","allServers"]).optional(),temperature:number2().optional(),maxTokens:number2().int(),stopSequences:array(string2()).optional(),metadata:JSONObjectSchema.optional(),tools:array(ToolSchema).optional(),toolChoice:ToolChoiceSchema.optional()}),CreateMessageRequestSchema=RequestSchema.extend({method:literal("sampling/createMessage"),params:CreateMessageRequestParamsSchema}),CreateMessageResultSchema=ResultSchema.extend({model:string2(),stopReason:optional(_enum(["endTurn","stopSequence","maxTokens"]).or(string2())),role:RoleSchema,content:SamplingContentSchema}),CreateMessageResultWithToolsSchema=ResultSchema.extend({model:string2(),stopReason:optional(_enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(string2())),role:RoleSchema,content:union([SamplingMessageContentBlockSchema,array(SamplingMessageContentBlockSchema)])}),BooleanSchemaSchema=object({type:literal("boolean"),title:string2().optional(),description:string2().optional(),default:boolean2().optional()}),StringSchemaSchema=object({type:literal("string"),title:string2().optional(),description:string2().optional(),minLength:number2().optional(),maxLength:number2().optional(),format:_enum(["email","uri","date","date-time"]).optional(),default:string2().optional()}),NumberSchemaSchema=object({type:_enum(["number","integer"]),title:string2().optional(),description:string2().optional(),minimum:number2().optional(),maximum:number2().optional(),default:number2().optional()}),UntitledSingleSelectEnumSchemaSchema=object({type:literal("string"),title:string2().optional(),description:string2().optional(),enum:array(string2()),default:string2().optional()}),TitledSingleSelectEnumSchemaSchema=object({type:literal("string"),title:string2().optional(),description:string2().optional(),oneOf:array(object({const:string2(),title:string2()})),default:string2().optional()}),LegacyTitledEnumSchemaSchema=object({type:literal("string"),title:string2().optional(),description:string2().optional(),enum:array(string2()),enumNames:array(string2()).optional(),default:string2().optional()}),SingleSelectEnumSchemaSchema=union([UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema]),UntitledMultiSelectEnumSchemaSchema=object({type:literal("array"),title:string2().optional(),description:string2().optional(),minItems:number2().optional(),maxItems:number2().optional(),items:object({type:literal("string"),enum:array(string2())}),default:array(string2()).optional()}),TitledMultiSelectEnumSchemaSchema=object({type:literal("array"),title:string2().optional(),description:string2().optional(),minItems:number2().optional(),maxItems:number2().optional(),items:object({anyOf:array(object({const:string2(),title:string2()}))}),default:array(string2()).optional()}),MultiSelectEnumSchemaSchema=union([UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema]),EnumSchemaSchema=union([LegacyTitledEnumSchemaSchema,SingleSelectEnumSchemaSchema,MultiSelectEnumSchemaSchema]),PrimitiveSchemaDefinitionSchema=union([EnumSchemaSchema,BooleanSchemaSchema,StringSchemaSchema,NumberSchemaSchema]),ElicitRequestFormParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal("form").optional(),message:string2(),requestedSchema:object({type:literal("object"),properties:record(string2(),PrimitiveSchemaDefinitionSchema),required:array(string2()).optional()}).catchall(unknown())}),ElicitRequestURLParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal("url"),message:string2(),elicitationId:string2(),url:string2().url()}),ElicitRequestParamsSchema=union([ElicitRequestFormParamsSchema,ElicitRequestURLParamsSchema]),ElicitRequestSchema=RequestSchema.extend({method:literal("elicitation/create"),params:ElicitRequestParamsSchema}),ElicitationCompleteNotificationParamsSchema=NotificationsParamsSchema.extend({elicitationId:string2()}),ElicitationCompleteNotificationSchema=NotificationSchema.extend({method:literal("notifications/elicitation/complete"),params:ElicitationCompleteNotificationParamsSchema}),ElicitResultSchema=ResultSchema.extend({action:_enum(["accept","decline","cancel"]),content:preprocess(val=>val===null?void 0:val,record(string2(),union([string2(),number2(),boolean2(),array(string2())])).optional())}),ResourceTemplateReferenceSchema=object({type:literal("ref/resource"),uri:string2()}),PromptReferenceSchema=object({type:literal("ref/prompt"),name:string2()}),CompleteRequestParamsSchema=BaseRequestParamsSchema.extend({ref:union([PromptReferenceSchema,ResourceTemplateReferenceSchema]),argument:object({name:string2(),value:string2()}),context:object({arguments:record(string2(),string2()).optional()}).optional()}),CompleteRequestSchema=RequestSchema.extend({method:literal("completion/complete"),params:CompleteRequestParamsSchema}),CompleteResultSchema=ResultSchema.extend({completion:looseObject({values:array(string2()).max(100),total:optional(number2().int()),hasMore:optional(boolean2())})}),RootSchema=object({uri:string2().startsWith("file://"),name:string2().optional(),_meta:record(string2(),unknown()).optional()}),ListRootsRequestSchema=RequestSchema.extend({method:literal("roots/list"),params:BaseRequestParamsSchema.optional()}),ListRootsResultSchema=ResultSchema.extend({roots:array(RootSchema)}),RootsListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/roots/list_changed"),params:NotificationsParamsSchema.optional()}),TaskCreationParamsSchema=looseObject({ttl:number2().optional(),pollInterval:number2().optional()}),TaskStatusSchema=_enum(["working","input_required","completed","failed","cancelled"]),TaskSchema=object({taskId:string2(),status:TaskStatusSchema,ttl:union([number2(),_null3()]),createdAt:string2(),lastUpdatedAt:string2(),pollInterval:optional(number2()),statusMessage:optional(string2())}),CreateTaskResultSchema=ResultSchema.extend({task:TaskSchema}),TaskStatusNotificationParamsSchema=NotificationsParamsSchema.merge(TaskSchema),TaskStatusNotificationSchema=NotificationSchema.extend({method:literal("notifications/tasks/status"),params:TaskStatusNotificationParamsSchema}),GetTaskRequestSchema=RequestSchema.extend({method:literal("tasks/get"),params:BaseRequestParamsSchema.extend({taskId:string2()})}),GetTaskResultSchema=ResultSchema.merge(TaskSchema),GetTaskPayloadRequestSchema=RequestSchema.extend({method:literal("tasks/result"),params:BaseRequestParamsSchema.extend({taskId:string2()})}),GetTaskPayloadResultSchema=ResultSchema.loose(),ListTasksRequestSchema=PaginatedRequestSchema.extend({method:literal("tasks/list")}),ListTasksResultSchema=PaginatedResultSchema.extend({tasks:array(TaskSchema)}),CancelTaskRequestSchema=RequestSchema.extend({method:literal("tasks/cancel"),params:BaseRequestParamsSchema.extend({taskId:string2()})}),CancelTaskResultSchema=ResultSchema.merge(TaskSchema),ClientRequestSchema=union([PingRequestSchema,InitializeRequestSchema,DiscoverRequestSchema,CompleteRequestSchema,SetLevelRequestSchema,GetPromptRequestSchema,ListPromptsRequestSchema,ListResourcesRequestSchema,ListResourceTemplatesRequestSchema,ReadResourceRequestSchema,SubscribeRequestSchema,UnsubscribeRequestSchema,SubscriptionsListenRequestSchema,CallToolRequestSchema,ListToolsRequestSchema]),ClientNotificationSchema=union([CancelledNotificationSchema,ProgressNotificationSchema,InitializedNotificationSchema,RootsListChangedNotificationSchema]),ClientResultSchema=union([EmptyResultSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,ElicitResultSchema,ListRootsResultSchema]),ServerRequestSchema=union([PingRequestSchema,CreateMessageRequestSchema,ElicitRequestSchema,ListRootsRequestSchema]),ServerNotificationSchema=union([CancelledNotificationSchema,ProgressNotificationSchema,LoggingMessageNotificationSchema,ResourceUpdatedNotificationSchema,ResourceListChangedNotificationSchema,ToolListChangedNotificationSchema,PromptListChangedNotificationSchema,SubscriptionsAcknowledgedNotificationSchema,ElicitationCompleteNotificationSchema]),ServerResultSchema=union([EmptyResultSchema,InitializeResultSchema,DiscoverResultSchema,CompleteResultSchema,GetPromptResultSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListResourceTemplatesResultSchema,ReadResourceResultSchema,CallToolResultSchema,ListToolsResultSchema,SubscriptionsListenResultSchema]),SafeUrlSchema=url().superRefine((val,ctx)=>{if(!URL.canParse(val))return ctx.addIssue({code:ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),NEVER}).refine(url2=>{let u=new URL(url2);return u.protocol!=="javascript:"&&u.protocol!=="data:"&&u.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),OAuthProtectedResourceMetadataSchema=looseObject({resource:string2().url(),authorization_servers:array(SafeUrlSchema).optional(),jwks_uri:string2().url().optional(),scopes_supported:array(string2()).optional(),bearer_methods_supported:array(string2()).optional(),resource_signing_alg_values_supported:array(string2()).optional(),resource_name:string2().optional(),resource_documentation:string2().optional(),resource_policy_uri:string2().url().optional(),resource_tos_uri:string2().url().optional(),tls_client_certificate_bound_access_tokens:boolean2().optional(),authorization_details_types_supported:array(string2()).optional(),dpop_signing_alg_values_supported:array(string2()).optional(),dpop_bound_access_tokens_required:boolean2().optional()}),OAuthMetadataSchema=looseObject({issuer:string2(),authorization_endpoint:SafeUrlSchema,token_endpoint:SafeUrlSchema,registration_endpoint:SafeUrlSchema.optional(),scopes_supported:array(string2()).optional(),response_types_supported:array(string2()),response_modes_supported:array(string2()).optional(),grant_types_supported:array(string2()).optional(),token_endpoint_auth_methods_supported:array(string2()).optional(),token_endpoint_auth_signing_alg_values_supported:array(string2()).optional(),service_documentation:SafeUrlSchema.optional(),revocation_endpoint:SafeUrlSchema.optional(),revocation_endpoint_auth_methods_supported:array(string2()).optional(),revocation_endpoint_auth_signing_alg_values_supported:array(string2()).optional(),introspection_endpoint:string2().optional(),introspection_endpoint_auth_methods_supported:array(string2()).optional(),introspection_endpoint_auth_signing_alg_values_supported:array(string2()).optional(),code_challenge_methods_supported:array(string2()).optional(),client_id_metadata_document_supported:boolean2().optional(),authorization_response_iss_parameter_supported:boolean2().optional().catch(void 0)}),OpenIdProviderMetadataSchema=looseObject({issuer:string2(),authorization_endpoint:SafeUrlSchema,token_endpoint:SafeUrlSchema,userinfo_endpoint:SafeUrlSchema.optional(),jwks_uri:SafeUrlSchema,registration_endpoint:SafeUrlSchema.optional(),scopes_supported:array(string2()).optional(),response_types_supported:array(string2()),response_modes_supported:array(string2()).optional(),grant_types_supported:array(string2()).optional(),acr_values_supported:array(string2()).optional(),subject_types_supported:array(string2()),id_token_signing_alg_values_supported:array(string2()),id_token_encryption_alg_values_supported:array(string2()).optional(),id_token_encryption_enc_values_supported:array(string2()).optional(),userinfo_signing_alg_values_supported:array(string2()).optional(),userinfo_encryption_alg_values_supported:array(string2()).optional(),userinfo_encryption_enc_values_supported:array(string2()).optional(),request_object_signing_alg_values_supported:array(string2()).optional(),request_object_encryption_alg_values_supported:array(string2()).optional(),request_object_encryption_enc_values_supported:array(string2()).optional(),token_endpoint_auth_methods_supported:array(string2()).optional(),token_endpoint_auth_signing_alg_values_supported:array(string2()).optional(),display_values_supported:array(string2()).optional(),claim_types_supported:array(string2()).optional(),claims_supported:array(string2()).optional(),service_documentation:string2().optional(),claims_locales_supported:array(string2()).optional(),ui_locales_supported:array(string2()).optional(),claims_parameter_supported:boolean2().optional(),request_parameter_supported:boolean2().optional(),request_uri_parameter_supported:boolean2().optional(),require_request_uri_registration:boolean2().optional(),op_policy_uri:SafeUrlSchema.optional(),op_tos_uri:SafeUrlSchema.optional(),client_id_metadata_document_supported:boolean2().optional(),authorization_response_iss_parameter_supported:boolean2().optional().catch(void 0)}),OpenIdProviderDiscoveryMetadataSchema=object({...OpenIdProviderMetadataSchema.shape,...OAuthMetadataSchema.pick({code_challenge_methods_supported:!0}).shape}),OAuthTokensSchema=object({access_token:string2(),id_token:string2().optional(),token_type:string2(),expires_in:coerce_exports.number().optional(),scope:string2().optional(),refresh_token:string2().optional()}).strip(),IdJagTokenExchangeResponseSchema=object({issued_token_type:literal("urn:ietf:params:oauth:token-type:id-jag"),access_token:string2(),token_type:string2().optional(),expires_in:number2().optional(),scope:string2().optional()}).strip(),OAuthErrorResponseSchema=object({error:string2(),error_description:string2().optional(),error_uri:string2().optional()}),OptionalSafeUrlSchema=SafeUrlSchema.optional().or(literal("").transform(()=>{})),OAuthClientMetadataSchema=object({redirect_uris:array(SafeUrlSchema),token_endpoint_auth_method:string2().optional(),grant_types:array(string2()).optional(),response_types:array(string2()).optional(),application_type:string2().optional(),client_name:string2().optional(),client_uri:SafeUrlSchema.optional(),logo_uri:OptionalSafeUrlSchema,scope:string2().optional(),contacts:array(string2()).optional(),tos_uri:OptionalSafeUrlSchema,policy_uri:string2().optional(),jwks_uri:SafeUrlSchema.optional(),jwks:any().optional(),software_id:string2().optional(),software_version:string2().optional(),software_statement:string2().optional()}).strip(),OAuthClientInformationSchema=object({client_id:string2(),client_secret:string2().optional(),client_id_issued_at:number2().optional(),client_secret_expires_at:number2().optional()}).strip(),OAuthClientInformationFullSchema=OAuthClientMetadataSchema.merge(OAuthClientInformationSchema),OAuthClientRegistrationErrorSchema=object({error:string2(),error_description:string2().optional()}).strip(),OAuthTokenRevocationRequestSchema=object({token:string2(),token_type_hint:string2().optional()}).strip()}});var init_internal=__esm({"../../node_modules/.pnpm/@modelcontextprotocol+core@2.0.0/node_modules/@modelcontextprotocol/core/dist/internal.mjs"(){"use strict";init_auth_CUe6YdwF()}});function stampErrorBrands(instance,ctor){let brands=new Set,current=ctor;for(;typeof current=="function";){let brand=current.mcpBrand;Object.prototype.hasOwnProperty.call(current,"mcpBrand")&&typeof brand=="string"&&brands.add(brand),current=Object.getPrototypeOf(current)}brands.size!==0&&Object.defineProperty(instance,BRANDS,{value:brands,enumerable:!1,configurable:!0})}function brandedHasInstance(cls,value){try{if(typeof value=="object"&&value!==null&&Object.prototype.hasOwnProperty.call(cls,"mcpBrand")&&typeof cls.mcpBrand=="string"&&Object.prototype.hasOwnProperty.call(value,BRANDS)){let carried=value[BRANDS];if(carried&&typeof carried.has=="function"&&carried.has(cls.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(cls,value)}function requiredClientCapabilitiesForRequest(method){return Object.hasOwn(REQUIRED_CLIENT_CAPABILITIES_BY_METHOD,method)?REQUIRED_CLIENT_CAPABILITIES_BY_METHOD[method]:void 0}function isPlainObject$7(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function isImpliedCapabilityMember(capability,member,declaredValue){return capability==="elicitation"&&member==="form"&&declaredValue.form===void 0&&declaredValue.url===void 0}function requiredClientCapabilitiesForInputRequest(entry){switch(entry.method){case"elicitation/create":return entry.params?.mode==="url"?{elicitation:{url:{}}}:{elicitation:{form:{}}};case"sampling/createMessage":{let params=entry.params;return params!==void 0&&(params.tools!==void 0||params.toolChoice!==void 0)?{sampling:{tools:{}}}:{sampling:{}}}case"roots/list":return{roots:{}};default:return}}function missingClientCapabilities(required2,declared){let missing={};for(let[capability,requirement]of Object.entries(required2)){if(requirement===void 0)continue;let declaredValue=declared===void 0?void 0:declared[capability];if(declaredValue===void 0){missing[capability]=requirement;continue}if(isPlainObject$7(requirement)&&isPlainObject$7(declaredValue)){let missingMembers={};for(let[member,memberRequirement]of Object.entries(requirement))memberRequirement!==void 0&&declaredValue[member]===void 0&&!isImpliedCapabilityMember(capability,member,declaredValue)&&(missingMembers[member]=memberRequirement);Object.keys(missingMembers).length>0&&(missing[capability]=missingMembers)}}return Object.keys(missing).length>0?missing:void 0}function isModernProtocolVersion(version2){return version2>=FIRST_MODERN_PROTOCOL_VERSION}function legacyProtocolVersions(versions){return versions.filter(version2=>!isModernProtocolVersion(version2))}function modernProtocolVersions(versions){return versions.filter(version2=>isModernProtocolVersion(version2))}function appendTextFallbackForNonObject(result){let sc=result.structuredContent;return sc===void 0||!(typeof sc!="object"||sc===null||Array.isArray(sc))||(result.content?.some(c=>c.type==="text")??!1)?result:{...result,content:[...result.content??[],{type:"text",text:JSON.stringify(sc)}]}}function normalizeContentlessToolResult(value){return value===null||typeof value!="object"||Array.isArray(value)||value.content!==void 0||TOOL_RESULT_FOREIGN_FAMILY_KEYS.some(key=>key in value)?value:{...value,content:[]}}function build$1(){let JSONValueSchema$1=lazy(()=>union([string2(),number2(),boolean2(),_null3(),record(string2(),JSONValueSchema$1),array(JSONValueSchema$1)])),JSONObjectSchema$1=record(string2(),JSONValueSchema$1),ProgressTokenSchema$1=union([string2(),number2().int()]),CursorSchema$1=string2(),TaskMetadataSchema$1=object({ttl:number2().optional()}),RelatedTaskMetadataSchema$1=object({taskId:string2()}),RequestMetaSchema$1=looseObject({progressToken:ProgressTokenSchema$1.optional(),"io.modelcontextprotocol/related-task":RelatedTaskMetadataSchema$1.optional()}),BaseRequestParamsSchema$1=object({_meta:RequestMetaSchema$1.optional()}),TaskAugmentedRequestParamsSchema$1=BaseRequestParamsSchema$1.extend({task:TaskMetadataSchema$1.optional()}),RequestSchema$1=object({method:string2(),params:BaseRequestParamsSchema$1.loose().optional()}),NotificationsParamsSchema$1=object({_meta:RequestMetaSchema$1.optional()}),NotificationSchema$1=object({method:string2(),params:NotificationsParamsSchema$1.loose().optional()}),ResultSchema$1=looseObject({_meta:RequestMetaSchema$1.optional()}),RequestIdSchema$1=union([string2(),number2().int()]),EmptyResultSchema$1=ResultSchema$1.strict(),CancelledNotificationParamsSchema$1=NotificationsParamsSchema$1.extend({requestId:RequestIdSchema$1.optional(),reason:string2().optional()}),CancelledNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/cancelled"),params:CancelledNotificationParamsSchema$1}),IconSchema$1=object({src:string2(),mimeType:string2().optional(),sizes:array(string2()).optional(),theme:_enum(["light","dark"]).optional()}),IconsSchema$1=object({icons:array(IconSchema$1).optional()}),BaseMetadataSchema$1=object({name:string2(),title:string2().optional()}),ImplementationSchema$1=BaseMetadataSchema$1.extend({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,version:string2(),websiteUrl:string2().optional(),description:string2().optional()}),FormElicitationCapabilitySchema2=intersection(object({applyDefaults:boolean2().optional()}),JSONObjectSchema$1),ElicitationCapabilitySchema2=preprocess(value=>value&&typeof value=="object"&&!Array.isArray(value)&&Object.keys(value).length===0?{form:{}}:value,intersection(object({form:FormElicitationCapabilitySchema2.optional(),url:JSONObjectSchema$1.optional()}),JSONObjectSchema$1.optional())),ClientTasksCapabilitySchema$1=looseObject({list:JSONObjectSchema$1.optional(),cancel:JSONObjectSchema$1.optional(),requests:looseObject({sampling:looseObject({createMessage:JSONObjectSchema$1.optional()}).optional(),elicitation:looseObject({create:JSONObjectSchema$1.optional()}).optional()}).optional()}),ServerTasksCapabilitySchema$1=looseObject({list:JSONObjectSchema$1.optional(),cancel:JSONObjectSchema$1.optional(),requests:looseObject({tools:looseObject({call:JSONObjectSchema$1.optional()}).optional()}).optional()}),ClientCapabilitiesSchema$1=object({experimental:record(string2(),JSONObjectSchema$1).optional(),sampling:object({context:JSONObjectSchema$1.optional(),tools:JSONObjectSchema$1.optional()}).optional(),elicitation:ElicitationCapabilitySchema2.optional(),roots:object({listChanged:boolean2().optional()}).optional(),tasks:ClientTasksCapabilitySchema$1.optional(),extensions:record(string2(),JSONObjectSchema$1).optional()}),InitializeRequestParamsSchema$1=BaseRequestParamsSchema$1.extend({protocolVersion:string2(),capabilities:ClientCapabilitiesSchema$1,clientInfo:ImplementationSchema$1}),InitializeRequestSchema$1=RequestSchema$1.extend({method:literal("initialize"),params:InitializeRequestParamsSchema$1}),ServerCapabilitiesSchema$1=object({experimental:record(string2(),JSONObjectSchema$1).optional(),logging:JSONObjectSchema$1.optional(),completions:JSONObjectSchema$1.optional(),prompts:object({listChanged:boolean2().optional()}).optional(),resources:object({subscribe:boolean2().optional(),listChanged:boolean2().optional()}).optional(),tools:object({listChanged:boolean2().optional()}).optional(),tasks:ServerTasksCapabilitySchema$1.optional(),extensions:record(string2(),JSONObjectSchema$1).optional()}),InitializeResultSchema$1=ResultSchema$1.extend({protocolVersion:string2(),capabilities:ServerCapabilitiesSchema$1,serverInfo:ImplementationSchema$1,instructions:string2().optional()}),InitializedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/initialized"),params:NotificationsParamsSchema$1.optional()}),PingRequestSchema$1=RequestSchema$1.extend({method:literal("ping"),params:BaseRequestParamsSchema$1.optional()}),ProgressSchema$1=object({progress:number2(),total:optional(number2()),message:optional(string2())}),ProgressNotificationParamsSchema$1=object({...NotificationsParamsSchema$1.shape,...ProgressSchema$1.shape,progressToken:ProgressTokenSchema$1}),ProgressNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/progress"),params:ProgressNotificationParamsSchema$1}),PaginatedRequestParamsSchema$1=BaseRequestParamsSchema$1.extend({cursor:CursorSchema$1.optional()}),PaginatedRequestSchema$1=RequestSchema$1.extend({params:PaginatedRequestParamsSchema$1.optional()}),PaginatedResultSchema$1=ResultSchema$1.extend({nextCursor:CursorSchema$1.optional()}),ResourceContentsSchema$1=object({uri:string2(),mimeType:optional(string2()),_meta:record(string2(),unknown()).optional()}),TextResourceContentsSchema$1=ResourceContentsSchema$1.extend({text:string2()}),Base64Schema2=string2().refine(val=>{try{return atob(val),!0}catch{return!1}},{message:"Invalid Base64 string"}),BlobResourceContentsSchema$1=ResourceContentsSchema$1.extend({blob:Base64Schema2}),RoleSchema$1=_enum(["user","assistant"]),AnnotationsSchema$1=object({audience:array(RoleSchema$1).optional(),priority:number2().min(0).max(1).optional(),lastModified:iso_exports.datetime({offset:!0}).optional()}),ResourceSchema$1=object({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,uri:string2(),description:optional(string2()),mimeType:optional(string2()),size:optional(number2()),annotations:AnnotationsSchema$1.optional(),_meta:optional(looseObject({}))}),ResourceTemplateSchema$1=object({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,uriTemplate:string2(),description:optional(string2()),mimeType:optional(string2()),annotations:AnnotationsSchema$1.optional(),_meta:optional(looseObject({}))}),ListResourcesRequestSchema$1=PaginatedRequestSchema$1.extend({method:literal("resources/list")}),ListResourcesResultSchema$1=PaginatedResultSchema$1.extend({resources:array(ResourceSchema$1)}),ListResourceTemplatesRequestSchema$1=PaginatedRequestSchema$1.extend({method:literal("resources/templates/list")}),ListResourceTemplatesResultSchema$1=PaginatedResultSchema$1.extend({resourceTemplates:array(ResourceTemplateSchema$1)}),ResourceRequestParamsSchema$1=BaseRequestParamsSchema$1.extend({uri:string2()}),ReadResourceRequestParamsSchema$1=ResourceRequestParamsSchema$1,ReadResourceRequestSchema$1=RequestSchema$1.extend({method:literal("resources/read"),params:ReadResourceRequestParamsSchema$1}),ReadResourceResultSchema$1=ResultSchema$1.extend({contents:array(union([TextResourceContentsSchema$1,BlobResourceContentsSchema$1]))}),ResourceListChangedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/resources/list_changed"),params:NotificationsParamsSchema$1.optional()}),SubscribeRequestParamsSchema$1=ResourceRequestParamsSchema$1,SubscribeRequestSchema$1=RequestSchema$1.extend({method:literal("resources/subscribe"),params:SubscribeRequestParamsSchema$1}),UnsubscribeRequestParamsSchema$1=ResourceRequestParamsSchema$1,UnsubscribeRequestSchema$1=RequestSchema$1.extend({method:literal("resources/unsubscribe"),params:UnsubscribeRequestParamsSchema$1}),ResourceUpdatedNotificationParamsSchema$1=NotificationsParamsSchema$1.extend({uri:string2()}),ResourceUpdatedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/resources/updated"),params:ResourceUpdatedNotificationParamsSchema$1}),PromptArgumentSchema$1=object({name:string2(),description:optional(string2()),required:optional(boolean2())}),PromptSchema$1=object({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,description:optional(string2()),arguments:optional(array(PromptArgumentSchema$1)),_meta:optional(looseObject({}))}),ListPromptsRequestSchema$1=PaginatedRequestSchema$1.extend({method:literal("prompts/list")}),ListPromptsResultSchema$1=PaginatedResultSchema$1.extend({prompts:array(PromptSchema$1)}),GetPromptRequestParamsSchema$1=BaseRequestParamsSchema$1.extend({name:string2(),arguments:record(string2(),string2()).optional()}),GetPromptRequestSchema$1=RequestSchema$1.extend({method:literal("prompts/get"),params:GetPromptRequestParamsSchema$1}),TextContentSchema$1=object({type:literal("text"),text:string2(),annotations:AnnotationsSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),ImageContentSchema$1=object({type:literal("image"),data:Base64Schema2,mimeType:string2(),annotations:AnnotationsSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),AudioContentSchema$1=object({type:literal("audio"),data:Base64Schema2,mimeType:string2(),annotations:AnnotationsSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),ToolUseContentSchema$1=object({type:literal("tool_use"),name:string2(),id:string2(),input:record(string2(),unknown()),_meta:record(string2(),unknown()).optional()}),EmbeddedResourceSchema$1=object({type:literal("resource"),resource:union([TextResourceContentsSchema$1,BlobResourceContentsSchema$1]),annotations:AnnotationsSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),ResourceLinkSchema$1=ResourceSchema$1.extend({type:literal("resource_link")}),ContentBlockSchema$1=union([TextContentSchema$1,ImageContentSchema$1,AudioContentSchema$1,ResourceLinkSchema$1,EmbeddedResourceSchema$1]),PromptMessageSchema$1=object({role:RoleSchema$1,content:ContentBlockSchema$1}),GetPromptResultSchema$1=ResultSchema$1.extend({description:string2().optional(),messages:array(PromptMessageSchema$1)}),PromptListChangedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/prompts/list_changed"),params:NotificationsParamsSchema$1.optional()}),ToolAnnotationsSchema$1=object({title:string2().optional(),readOnlyHint:boolean2().optional(),destructiveHint:boolean2().optional(),idempotentHint:boolean2().optional(),openWorldHint:boolean2().optional()}),ToolExecutionSchema$1=object({taskSupport:_enum(["required","optional","forbidden"]).optional()}),ToolSchema$1=object({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,description:string2().optional(),inputSchema:object({type:literal("object"),properties:record(string2(),JSONValueSchema$1).optional(),required:array(string2()).optional()}).catchall(unknown()),outputSchema:object({type:literal("object"),properties:record(string2(),JSONValueSchema$1).optional(),required:array(string2()).optional()}).catchall(unknown()).optional(),annotations:ToolAnnotationsSchema$1.optional(),execution:ToolExecutionSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),ListToolsRequestSchema$1=PaginatedRequestSchema$1.extend({method:literal("tools/list")}),ListToolsResultSchema$1=PaginatedResultSchema$1.extend({tools:array(ToolSchema$1)}),CallToolResultSchema$1=ResultSchema$1.extend({content:array(ContentBlockSchema$1),structuredContent:record(string2(),unknown()).optional(),isError:boolean2().optional()}),CallToolRequestParamsSchema$1=TaskAugmentedRequestParamsSchema$1.extend({name:string2(),arguments:record(string2(),unknown()).optional()}),CallToolRequestSchema$1=RequestSchema$1.extend({method:literal("tools/call"),params:CallToolRequestParamsSchema$1}),ToolListChangedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/tools/list_changed"),params:NotificationsParamsSchema$1.optional()}),LoggingLevelSchema$1=_enum(["debug","info","notice","warning","error","critical","alert","emergency"]),SetLevelRequestParamsSchema$1=BaseRequestParamsSchema$1.extend({level:LoggingLevelSchema$1}),SetLevelRequestSchema$1=RequestSchema$1.extend({method:literal("logging/setLevel"),params:SetLevelRequestParamsSchema$1}),LoggingMessageNotificationParamsSchema$1=NotificationsParamsSchema$1.extend({level:LoggingLevelSchema$1,logger:string2().optional(),data:unknown()}),LoggingMessageNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/message"),params:LoggingMessageNotificationParamsSchema$1}),ModelHintSchema$1=object({name:string2().optional()}),ModelPreferencesSchema$1=object({hints:array(ModelHintSchema$1).optional(),costPriority:number2().min(0).max(1).optional(),speedPriority:number2().min(0).max(1).optional(),intelligencePriority:number2().min(0).max(1).optional()}),ToolChoiceSchema$1=object({mode:_enum(["auto","required","none"]).optional()}),ToolResultContentSchema$1=object({type:literal("tool_result"),toolUseId:string2().describe("The unique identifier for the corresponding tool call."),content:array(ContentBlockSchema$1),structuredContent:object({}).loose().optional(),isError:boolean2().optional(),_meta:record(string2(),unknown()).optional()}),SamplingContentSchema$1=discriminatedUnion("type",[TextContentSchema$1,ImageContentSchema$1,AudioContentSchema$1]),SamplingMessageContentBlockSchema$1=discriminatedUnion("type",[TextContentSchema$1,ImageContentSchema$1,AudioContentSchema$1,ToolUseContentSchema$1,ToolResultContentSchema$1]),SamplingMessageSchema$1=object({role:RoleSchema$1,content:union([SamplingMessageContentBlockSchema$1,array(SamplingMessageContentBlockSchema$1)]),_meta:record(string2(),unknown()).optional()}),CreateMessageRequestParamsSchema$1=TaskAugmentedRequestParamsSchema$1.extend({messages:array(SamplingMessageSchema$1),modelPreferences:ModelPreferencesSchema$1.optional(),systemPrompt:string2().optional(),includeContext:_enum(["none","thisServer","allServers"]).optional(),temperature:number2().optional(),maxTokens:number2().int(),stopSequences:array(string2()).optional(),metadata:JSONObjectSchema$1.optional(),tools:array(ToolSchema$1).optional(),toolChoice:ToolChoiceSchema$1.optional()}),CreateMessageRequestSchema$1=RequestSchema$1.extend({method:literal("sampling/createMessage"),params:CreateMessageRequestParamsSchema$1}),CreateMessageResultSchema$1=ResultSchema$1.extend({model:string2(),stopReason:optional(_enum(["endTurn","stopSequence","maxTokens"]).or(string2())),role:RoleSchema$1,content:SamplingContentSchema$1}),CreateMessageResultWithToolsSchema$1=ResultSchema$1.extend({model:string2(),stopReason:optional(_enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(string2())),role:RoleSchema$1,content:union([SamplingMessageContentBlockSchema$1,array(SamplingMessageContentBlockSchema$1)])}),BooleanSchemaSchema$1=object({type:literal("boolean"),title:string2().optional(),description:string2().optional(),default:boolean2().optional()}),StringSchemaSchema$1=object({type:literal("string"),title:string2().optional(),description:string2().optional(),minLength:number2().optional(),maxLength:number2().optional(),format:_enum(["email","uri","date","date-time"]).optional(),default:string2().optional()}),NumberSchemaSchema$1=object({type:_enum(["number","integer"]),title:string2().optional(),description:string2().optional(),minimum:number2().optional(),maximum:number2().optional(),default:number2().optional()}),UntitledSingleSelectEnumSchemaSchema$1=object({type:literal("string"),title:string2().optional(),description:string2().optional(),enum:array(string2()),default:string2().optional()}),TitledSingleSelectEnumSchemaSchema$1=object({type:literal("string"),title:string2().optional(),description:string2().optional(),oneOf:array(object({const:string2(),title:string2()})),default:string2().optional()}),LegacyTitledEnumSchemaSchema$1=object({type:literal("string"),title:string2().optional(),description:string2().optional(),enum:array(string2()),enumNames:array(string2()).optional(),default:string2().optional()}),SingleSelectEnumSchemaSchema$1=union([UntitledSingleSelectEnumSchemaSchema$1,TitledSingleSelectEnumSchemaSchema$1]),UntitledMultiSelectEnumSchemaSchema$1=object({type:literal("array"),title:string2().optional(),description:string2().optional(),minItems:number2().optional(),maxItems:number2().optional(),items:object({type:literal("string"),enum:array(string2())}),default:array(string2()).optional()}),TitledMultiSelectEnumSchemaSchema$1=object({type:literal("array"),title:string2().optional(),description:string2().optional(),minItems:number2().optional(),maxItems:number2().optional(),items:object({anyOf:array(object({const:string2(),title:string2()}))}),default:array(string2()).optional()}),MultiSelectEnumSchemaSchema$1=union([UntitledMultiSelectEnumSchemaSchema$1,TitledMultiSelectEnumSchemaSchema$1]),EnumSchemaSchema$1=union([LegacyTitledEnumSchemaSchema$1,SingleSelectEnumSchemaSchema$1,MultiSelectEnumSchemaSchema$1]),PrimitiveSchemaDefinitionSchema$1=union([EnumSchemaSchema$1,BooleanSchemaSchema$1,StringSchemaSchema$1,NumberSchemaSchema$1]),ElicitRequestFormParamsSchema$1=TaskAugmentedRequestParamsSchema$1.extend({mode:literal("form").optional(),message:string2(),requestedSchema:object({type:literal("object"),properties:record(string2(),PrimitiveSchemaDefinitionSchema$1),required:array(string2()).optional()}).catchall(unknown())}),ElicitRequestURLParamsSchema$1=TaskAugmentedRequestParamsSchema$1.extend({mode:literal("url"),message:string2(),elicitationId:string2(),url:string2().url()}),ElicitRequestParamsSchema$1=union([ElicitRequestFormParamsSchema$1,ElicitRequestURLParamsSchema$1]),ElicitRequestSchema$1=RequestSchema$1.extend({method:literal("elicitation/create"),params:ElicitRequestParamsSchema$1}),ElicitationCompleteNotificationParamsSchema$1=NotificationsParamsSchema$1.extend({elicitationId:string2()}),ElicitationCompleteNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/elicitation/complete"),params:ElicitationCompleteNotificationParamsSchema$1}),ElicitResultSchema$1=ResultSchema$1.extend({action:_enum(["accept","decline","cancel"]),content:preprocess(val=>val===null?void 0:val,record(string2(),union([string2(),number2(),boolean2(),array(string2())])).optional())}),ResourceTemplateReferenceSchema$1=object({type:literal("ref/resource"),uri:string2()}),PromptReferenceSchema$1=object({type:literal("ref/prompt"),name:string2()}),CompleteRequestParamsSchema$1=BaseRequestParamsSchema$1.extend({ref:union([PromptReferenceSchema$1,ResourceTemplateReferenceSchema$1]),argument:object({name:string2(),value:string2()}),context:object({arguments:record(string2(),string2()).optional()}).optional()}),CompleteRequestSchema$1=RequestSchema$1.extend({method:literal("completion/complete"),params:CompleteRequestParamsSchema$1}),CompleteResultSchema$1=ResultSchema$1.extend({completion:looseObject({values:array(string2()).max(100),total:optional(number2().int()),hasMore:optional(boolean2())})}),RootSchema$1=object({uri:string2().startsWith("file://"),name:string2().optional(),_meta:record(string2(),unknown()).optional()}),ListRootsRequestSchema$1=RequestSchema$1.extend({method:literal("roots/list"),params:BaseRequestParamsSchema$1.optional()}),ListRootsResultSchema$1=ResultSchema$1.extend({roots:array(RootSchema$1)}),RootsListChangedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/roots/list_changed"),params:NotificationsParamsSchema$1.optional()}),TaskCreationParamsSchema$1=looseObject({ttl:number2().optional(),pollInterval:number2().optional()}),TaskStatusSchema$1=_enum(["working","input_required","completed","failed","cancelled"]),TaskSchema$1=object({taskId:string2(),status:TaskStatusSchema$1,ttl:union([number2(),_null3()]),createdAt:string2(),lastUpdatedAt:string2(),pollInterval:optional(number2()),statusMessage:optional(string2())}),CreateTaskResultSchema$1=ResultSchema$1.extend({task:TaskSchema$1}),TaskStatusNotificationParamsSchema$1=NotificationsParamsSchema$1.merge(TaskSchema$1),TaskStatusNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/tasks/status"),params:TaskStatusNotificationParamsSchema$1}),GetTaskRequestSchema$1=RequestSchema$1.extend({method:literal("tasks/get"),params:BaseRequestParamsSchema$1.extend({taskId:string2()})}),GetTaskResultSchema$1=ResultSchema$1.merge(TaskSchema$1),GetTaskPayloadRequestSchema$1=RequestSchema$1.extend({method:literal("tasks/result"),params:BaseRequestParamsSchema$1.extend({taskId:string2()})}),GetTaskPayloadResultSchema$1=ResultSchema$1.loose(),ListTasksRequestSchema$1=PaginatedRequestSchema$1.extend({method:literal("tasks/list")}),ListTasksResultSchema$1=PaginatedResultSchema$1.extend({tasks:array(TaskSchema$1)}),CancelTaskRequestSchema$1=RequestSchema$1.extend({method:literal("tasks/cancel"),params:BaseRequestParamsSchema$1.extend({taskId:string2()})});return{JSONValueSchema:JSONValueSchema$1,JSONObjectSchema:JSONObjectSchema$1,ProgressTokenSchema:ProgressTokenSchema$1,CursorSchema:CursorSchema$1,TaskMetadataSchema:TaskMetadataSchema$1,RelatedTaskMetadataSchema:RelatedTaskMetadataSchema$1,RequestMetaSchema:RequestMetaSchema$1,BaseRequestParamsSchema:BaseRequestParamsSchema$1,TaskAugmentedRequestParamsSchema:TaskAugmentedRequestParamsSchema$1,RequestSchema:RequestSchema$1,NotificationsParamsSchema:NotificationsParamsSchema$1,NotificationSchema:NotificationSchema$1,ResultSchema:ResultSchema$1,RequestIdSchema:RequestIdSchema$1,EmptyResultSchema:EmptyResultSchema$1,CancelledNotificationParamsSchema:CancelledNotificationParamsSchema$1,CancelledNotificationSchema:CancelledNotificationSchema$1,IconSchema:IconSchema$1,IconsSchema:IconsSchema$1,BaseMetadataSchema:BaseMetadataSchema$1,ImplementationSchema:ImplementationSchema$1,ClientTasksCapabilitySchema:ClientTasksCapabilitySchema$1,ServerTasksCapabilitySchema:ServerTasksCapabilitySchema$1,ClientCapabilitiesSchema:ClientCapabilitiesSchema$1,InitializeRequestParamsSchema:InitializeRequestParamsSchema$1,InitializeRequestSchema:InitializeRequestSchema$1,ServerCapabilitiesSchema:ServerCapabilitiesSchema$1,InitializeResultSchema:InitializeResultSchema$1,InitializedNotificationSchema:InitializedNotificationSchema$1,PingRequestSchema:PingRequestSchema$1,ProgressSchema:ProgressSchema$1,ProgressNotificationParamsSchema:ProgressNotificationParamsSchema$1,ProgressNotificationSchema:ProgressNotificationSchema$1,PaginatedRequestParamsSchema:PaginatedRequestParamsSchema$1,PaginatedRequestSchema:PaginatedRequestSchema$1,PaginatedResultSchema:PaginatedResultSchema$1,ResourceContentsSchema:ResourceContentsSchema$1,TextResourceContentsSchema:TextResourceContentsSchema$1,BlobResourceContentsSchema:BlobResourceContentsSchema$1,RoleSchema:RoleSchema$1,AnnotationsSchema:AnnotationsSchema$1,ResourceSchema:ResourceSchema$1,ResourceTemplateSchema:ResourceTemplateSchema$1,ListResourcesRequestSchema:ListResourcesRequestSchema$1,ListResourcesResultSchema:ListResourcesResultSchema$1,ListResourceTemplatesRequestSchema:ListResourceTemplatesRequestSchema$1,ListResourceTemplatesResultSchema:ListResourceTemplatesResultSchema$1,ResourceRequestParamsSchema:ResourceRequestParamsSchema$1,ReadResourceRequestParamsSchema:ReadResourceRequestParamsSchema$1,ReadResourceRequestSchema:ReadResourceRequestSchema$1,ReadResourceResultSchema:ReadResourceResultSchema$1,ResourceListChangedNotificationSchema:ResourceListChangedNotificationSchema$1,SubscribeRequestParamsSchema:SubscribeRequestParamsSchema$1,SubscribeRequestSchema:SubscribeRequestSchema$1,UnsubscribeRequestParamsSchema:UnsubscribeRequestParamsSchema$1,UnsubscribeRequestSchema:UnsubscribeRequestSchema$1,ResourceUpdatedNotificationParamsSchema:ResourceUpdatedNotificationParamsSchema$1,ResourceUpdatedNotificationSchema:ResourceUpdatedNotificationSchema$1,PromptArgumentSchema:PromptArgumentSchema$1,PromptSchema:PromptSchema$1,ListPromptsRequestSchema:ListPromptsRequestSchema$1,ListPromptsResultSchema:ListPromptsResultSchema$1,GetPromptRequestParamsSchema:GetPromptRequestParamsSchema$1,GetPromptRequestSchema:GetPromptRequestSchema$1,TextContentSchema:TextContentSchema$1,ImageContentSchema:ImageContentSchema$1,AudioContentSchema:AudioContentSchema$1,ToolUseContentSchema:ToolUseContentSchema$1,EmbeddedResourceSchema:EmbeddedResourceSchema$1,ResourceLinkSchema:ResourceLinkSchema$1,ContentBlockSchema:ContentBlockSchema$1,PromptMessageSchema:PromptMessageSchema$1,GetPromptResultSchema:GetPromptResultSchema$1,PromptListChangedNotificationSchema:PromptListChangedNotificationSchema$1,ToolAnnotationsSchema:ToolAnnotationsSchema$1,ToolExecutionSchema:ToolExecutionSchema$1,ToolSchema:ToolSchema$1,ListToolsRequestSchema:ListToolsRequestSchema$1,ListToolsResultSchema:ListToolsResultSchema$1,CallToolResultSchema:CallToolResultSchema$1,CallToolRequestParamsSchema:CallToolRequestParamsSchema$1,CallToolRequestSchema:CallToolRequestSchema$1,ToolListChangedNotificationSchema:ToolListChangedNotificationSchema$1,LoggingLevelSchema:LoggingLevelSchema$1,SetLevelRequestParamsSchema:SetLevelRequestParamsSchema$1,SetLevelRequestSchema:SetLevelRequestSchema$1,LoggingMessageNotificationParamsSchema:LoggingMessageNotificationParamsSchema$1,LoggingMessageNotificationSchema:LoggingMessageNotificationSchema$1,ModelHintSchema:ModelHintSchema$1,ModelPreferencesSchema:ModelPreferencesSchema$1,ToolChoiceSchema:ToolChoiceSchema$1,ToolResultContentSchema:ToolResultContentSchema$1,SamplingContentSchema:SamplingContentSchema$1,SamplingMessageContentBlockSchema:SamplingMessageContentBlockSchema$1,SamplingMessageSchema:SamplingMessageSchema$1,CreateMessageRequestParamsSchema:CreateMessageRequestParamsSchema$1,CreateMessageRequestSchema:CreateMessageRequestSchema$1,CreateMessageResultSchema:CreateMessageResultSchema$1,CreateMessageResultWithToolsSchema:CreateMessageResultWithToolsSchema$1,BooleanSchemaSchema:BooleanSchemaSchema$1,StringSchemaSchema:StringSchemaSchema$1,NumberSchemaSchema:NumberSchemaSchema$1,UntitledSingleSelectEnumSchemaSchema:UntitledSingleSelectEnumSchemaSchema$1,TitledSingleSelectEnumSchemaSchema:TitledSingleSelectEnumSchemaSchema$1,LegacyTitledEnumSchemaSchema:LegacyTitledEnumSchemaSchema$1,SingleSelectEnumSchemaSchema:SingleSelectEnumSchemaSchema$1,UntitledMultiSelectEnumSchemaSchema:UntitledMultiSelectEnumSchemaSchema$1,TitledMultiSelectEnumSchemaSchema:TitledMultiSelectEnumSchemaSchema$1,MultiSelectEnumSchemaSchema:MultiSelectEnumSchemaSchema$1,EnumSchemaSchema:EnumSchemaSchema$1,PrimitiveSchemaDefinitionSchema:PrimitiveSchemaDefinitionSchema$1,ElicitRequestFormParamsSchema:ElicitRequestFormParamsSchema$1,ElicitRequestURLParamsSchema:ElicitRequestURLParamsSchema$1,ElicitRequestParamsSchema:ElicitRequestParamsSchema$1,ElicitRequestSchema:ElicitRequestSchema$1,ElicitationCompleteNotificationParamsSchema:ElicitationCompleteNotificationParamsSchema$1,ElicitationCompleteNotificationSchema:ElicitationCompleteNotificationSchema$1,ElicitResultSchema:ElicitResultSchema$1,ResourceTemplateReferenceSchema:ResourceTemplateReferenceSchema$1,PromptReferenceSchema:PromptReferenceSchema$1,CompleteRequestParamsSchema:CompleteRequestParamsSchema$1,CompleteRequestSchema:CompleteRequestSchema$1,CompleteResultSchema:CompleteResultSchema$1,RootSchema:RootSchema$1,ListRootsRequestSchema:ListRootsRequestSchema$1,ListRootsResultSchema:ListRootsResultSchema$1,RootsListChangedNotificationSchema:RootsListChangedNotificationSchema$1,TaskCreationParamsSchema:TaskCreationParamsSchema$1,TaskStatusSchema:TaskStatusSchema$1,TaskSchema:TaskSchema$1,CreateTaskResultSchema:CreateTaskResultSchema$1,TaskStatusNotificationParamsSchema:TaskStatusNotificationParamsSchema$1,TaskStatusNotificationSchema:TaskStatusNotificationSchema$1,GetTaskRequestSchema:GetTaskRequestSchema$1,GetTaskResultSchema:GetTaskResultSchema$1,GetTaskPayloadRequestSchema:GetTaskPayloadRequestSchema$1,GetTaskPayloadResultSchema:GetTaskPayloadResultSchema$1,ListTasksRequestSchema:ListTasksRequestSchema$1,ListTasksResultSchema:ListTasksResultSchema$1,CancelTaskRequestSchema:CancelTaskRequestSchema$1,CancelTaskResultSchema:ResultSchema$1.merge(TaskSchema$1),ClientRequestSchema:union([PingRequestSchema$1,InitializeRequestSchema$1,CompleteRequestSchema$1,SetLevelRequestSchema$1,GetPromptRequestSchema$1,ListPromptsRequestSchema$1,ListResourcesRequestSchema$1,ListResourceTemplatesRequestSchema$1,ReadResourceRequestSchema$1,SubscribeRequestSchema$1,UnsubscribeRequestSchema$1,CallToolRequestSchema$1,ListToolsRequestSchema$1,GetTaskRequestSchema$1,GetTaskPayloadRequestSchema$1,ListTasksRequestSchema$1,CancelTaskRequestSchema$1]),ClientNotificationSchema:union([CancelledNotificationSchema$1,ProgressNotificationSchema$1,InitializedNotificationSchema$1,RootsListChangedNotificationSchema$1,TaskStatusNotificationSchema$1]),ClientResultSchema:union([EmptyResultSchema$1,CreateMessageResultSchema$1,CreateMessageResultWithToolsSchema$1,ElicitResultSchema$1,ListRootsResultSchema$1,GetTaskResultSchema$1,ListTasksResultSchema$1,CreateTaskResultSchema$1]),ServerRequestSchema:union([PingRequestSchema$1,CreateMessageRequestSchema$1,ElicitRequestSchema$1,ListRootsRequestSchema$1,GetTaskRequestSchema$1,GetTaskPayloadRequestSchema$1,ListTasksRequestSchema$1,CancelTaskRequestSchema$1]),ServerNotificationSchema:union([CancelledNotificationSchema$1,ProgressNotificationSchema$1,LoggingMessageNotificationSchema$1,ResourceUpdatedNotificationSchema$1,ResourceListChangedNotificationSchema$1,ToolListChangedNotificationSchema$1,PromptListChangedNotificationSchema$1,TaskStatusNotificationSchema$1,ElicitationCompleteNotificationSchema$1]),ServerResultSchema:union([EmptyResultSchema$1,InitializeResultSchema$1,CompleteResultSchema$1,GetPromptResultSchema$1,ListPromptsResultSchema$1,ListResourcesResultSchema$1,ListResourceTemplatesResultSchema$1,ReadResourceResultSchema$1,CallToolResultSchema$1,ListToolsResultSchema$1,GetTaskResultSchema$1,ListTasksResultSchema$1,CreateTaskResultSchema$1]),CallToolResultWireSchema:unknown().superRefine((value,ctx)=>{if(!(typeof value!="object"||value===null||Array.isArray(value)||value.content!==void 0)){for(let key of TOOL_RESULT_FOREIGN_FAMILY_KEYS)if(key in value){ctx.addIssue({code:"custom",message:`content is required when the body carries '${key}' \u2014 another result family cannot default into an empty tools/call success`});return}}}).transform(normalizeContentlessToolResult).pipe(CallToolResultSchema$1)}}function buildSchemas2025(){return memo$1??=build$1()}function isNonObjectJsonSchemaRoot(json){return json.type!=="object"}function establishesNewBase(id){return id!==void 0&&!(typeof id=="string"&&id.startsWith("#"))}function wrapOutputSchemaForLegacy(natural){let $schema=typeof natural.$schema=="string"?natural.$schema:void 0;if(establishesNewBase(natural.$id))return{...$schema!==void 0&&{$schema},type:"object",properties:{result:natural},required:["result"]};let convertRecursiveRefs=declares2019Dialect(natural.$schema)&&natural.$recursiveAnchor!==!0,rewriteRefs=(node,parentIsNameMap)=>{if(Array.isArray(node))return node.map(item=>rewriteRefs(item,!1));if(node===null||typeof node!="object"||!parentIsNameMap&&establishesNewBase(node.$id))return node;let out={},convertedRecursion=!1;for(let[k,v]of Object.entries(node))parentIsNameMap?out[k]=rewriteRefs(v,!1):(k==="$ref"||k==="$dynamicRef")&&typeof v=="string"?out[k]=v==="#"?"#/properties/result":v.startsWith("#/")?`#/properties/result${v.slice(1)}`:v:k==="$recursiveRef"&&v==="#"&&convertRecursiveRefs?convertedRecursion=!0:REF_REWRITE_DATA_POSITION_KEYS.has(k)?out[k]=v:REF_REWRITE_NAME_MAP_KEYS.has(k)?out[k]=rewriteRefs(v,!0):out[k]=rewriteRefs(v,!1);return convertedRecursion&&("$ref"in out?out.allOf=[...Array.isArray(out.allOf)?out.allOf:[],{$ref:"#/properties/result"}]:out.$ref="#/properties/result"),out};return{...$schema!==void 0&&{$schema},type:"object",properties:{result:rewriteRefs(natural,!1)},required:["result"]}}function registryMaps(){if(maps$1)return maps$1;let s=buildSchemas2025();return maps$1={requestSchemas:{ping:s.PingRequestSchema,initialize:s.InitializeRequestSchema,"completion/complete":s.CompleteRequestSchema,"logging/setLevel":s.SetLevelRequestSchema,"prompts/get":s.GetPromptRequestSchema,"prompts/list":s.ListPromptsRequestSchema,"resources/list":s.ListResourcesRequestSchema,"resources/templates/list":s.ListResourceTemplatesRequestSchema,"resources/read":s.ReadResourceRequestSchema,"resources/subscribe":s.SubscribeRequestSchema,"resources/unsubscribe":s.UnsubscribeRequestSchema,"tools/call":s.CallToolRequestSchema,"tools/list":s.ListToolsRequestSchema,"tasks/get":s.GetTaskRequestSchema,"tasks/result":s.GetTaskPayloadRequestSchema,"tasks/list":s.ListTasksRequestSchema,"tasks/cancel":s.CancelTaskRequestSchema,"sampling/createMessage":s.CreateMessageRequestSchema,"elicitation/create":s.ElicitRequestSchema,"roots/list":s.ListRootsRequestSchema},notificationSchemas:{"notifications/cancelled":s.CancelledNotificationSchema,"notifications/progress":s.ProgressNotificationSchema,"notifications/initialized":s.InitializedNotificationSchema,"notifications/roots/list_changed":s.RootsListChangedNotificationSchema,"notifications/tasks/status":s.TaskStatusNotificationSchema,"notifications/message":s.LoggingMessageNotificationSchema,"notifications/resources/updated":s.ResourceUpdatedNotificationSchema,"notifications/resources/list_changed":s.ResourceListChangedNotificationSchema,"notifications/tools/list_changed":s.ToolListChangedNotificationSchema,"notifications/prompts/list_changed":s.PromptListChangedNotificationSchema,"notifications/elicitation/complete":s.ElicitationCompleteNotificationSchema},resultSchemas:{ping:s.EmptyResultSchema,initialize:s.InitializeResultSchema,"completion/complete":s.CompleteResultSchema,"logging/setLevel":s.EmptyResultSchema,"prompts/get":s.GetPromptResultSchema,"prompts/list":s.ListPromptsResultSchema,"resources/list":s.ListResourcesResultSchema,"resources/templates/list":s.ListResourceTemplatesResultSchema,"resources/read":s.ReadResourceResultSchema,"resources/subscribe":s.EmptyResultSchema,"resources/unsubscribe":s.EmptyResultSchema,"tools/call":s.CallToolResultWireSchema,"tools/list":s.ListToolsResultSchema,"sampling/createMessage":s.CreateMessageResultWithToolsSchema,"elicitation/create":s.ElicitResultSchema,"roots/list":s.ListRootsResultSchema}},maps$1}function hasRequestMethod2025(method){return Object.prototype.hasOwnProperty.call(requestMethodKeys$1,method)}function hasNotificationMethod2025(method){return Object.prototype.hasOwnProperty.call(notificationMethodKeys$1,method)}function hasResultMethod(method){return Object.prototype.hasOwnProperty.call(resultMethodKeys,method)}function getResultSchema(method){return hasResultMethod(method)?registryMaps().resultSchemas[method]:void 0}function getRequestSchema(method){return hasRequestMethod2025(method)?registryMaps().requestSchemas[method]:void 0}function getNotificationSchema(method){return hasNotificationMethod2025(method)?registryMaps().notificationSchemas[method]:void 0}function isPlainObject$6(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function triState$1(schema2,raw2){if(schema2===void 0)return{ok:!1,reason:"not-in-era"};let parsed=schema2.safeParse(raw2);return parsed.success?{ok:!0,value:parsed.data}:{ok:!1,reason:"invalid",message:String(parsed.error)}}function toolNeedsLegacyWrap(t){return isPlainObject$6(t)&&isPlainObject$6(t.outputSchema)&&isNonObjectJsonSchemaRoot(t.outputSchema)}function build(){let JSONValueSchema$1=lazy(()=>union([string2(),number2(),boolean2(),_null3(),record(string2(),JSONValueSchema$1),array(JSONValueSchema$1)])),JSONObjectSchema$1=record(string2(),JSONValueSchema$1),ProgressTokenSchema$1=union([string2(),number2().int()]),CursorSchema$1=string2(),RequestIdSchema$1=union([string2(),number2().int()]),RoleSchema$1=_enum(["user","assistant"]),LoggingLevelSchema$1=_enum(["debug","info","notice","warning","error","critical","alert","emergency"]),Base64Schema2=string2().refine(val=>{try{return atob(val),!0}catch{return!1}},{message:"Invalid Base64 string"}),TaskMetadataSchema$1=object({ttl:number2().optional()}),RelatedTaskMetadataSchema$1=object({taskId:string2()}),RequestMetaSchema$1=looseObject({progressToken:ProgressTokenSchema$1.optional(),"io.modelcontextprotocol/related-task":RelatedTaskMetadataSchema$1.optional()}),BaseRequestParamsSchema$1=object({_meta:RequestMetaSchema$1.optional()}),TaskAugmentedRequestParamsSchema$1=BaseRequestParamsSchema$1.extend({task:TaskMetadataSchema$1.optional()}),NotificationsParamsSchema$1=object({_meta:RequestMetaSchema$1.optional()}),NotificationSchema$1=object({method:string2(),params:NotificationsParamsSchema$1.loose().optional()}),IconSchema$1=object({src:string2(),mimeType:string2().optional(),sizes:array(string2()).optional(),theme:_enum(["light","dark"]).optional()}),IconsSchema$1=object({icons:array(IconSchema$1).optional()}),BaseMetadataSchema$1=object({name:string2(),title:string2().optional()}),ImplementationSchema$1=BaseMetadataSchema$1.extend({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,version:string2(),websiteUrl:string2().optional(),description:string2().optional()}),FormElicitationCapabilitySchema2=intersection(object({applyDefaults:boolean2().optional()}),JSONObjectSchema$1),ElicitationCapabilitySchema2=preprocess(value=>value&&typeof value=="object"&&!Array.isArray(value)&&Object.keys(value).length===0?{form:{}}:value,intersection(object({form:FormElicitationCapabilitySchema2.optional(),url:JSONObjectSchema$1.optional()}),JSONObjectSchema$1.optional())),ClientTasksCapabilitySchema$1=looseObject({list:JSONObjectSchema$1.optional(),cancel:JSONObjectSchema$1.optional(),requests:looseObject({sampling:looseObject({createMessage:JSONObjectSchema$1.optional()}).optional(),elicitation:looseObject({create:JSONObjectSchema$1.optional()}).optional()}).optional()}),ServerTasksCapabilitySchema$1=looseObject({list:JSONObjectSchema$1.optional(),cancel:JSONObjectSchema$1.optional(),requests:looseObject({tools:looseObject({call:JSONObjectSchema$1.optional()}).optional()}).optional()}),ClientCapabilitiesSchema$1=object({experimental:record(string2(),JSONObjectSchema$1).optional(),sampling:object({context:JSONObjectSchema$1.optional(),tools:JSONObjectSchema$1.optional()}).optional(),elicitation:ElicitationCapabilitySchema2.optional(),roots:object({listChanged:boolean2().optional()}).optional(),tasks:ClientTasksCapabilitySchema$1.optional(),extensions:record(string2(),JSONObjectSchema$1).optional()}),ServerCapabilitiesSchema$1=object({experimental:record(string2(),JSONObjectSchema$1).optional(),logging:JSONObjectSchema$1.optional(),completions:JSONObjectSchema$1.optional(),prompts:object({listChanged:boolean2().optional()}).optional(),resources:object({subscribe:boolean2().optional(),listChanged:boolean2().optional()}).optional(),tools:object({listChanged:boolean2().optional()}).optional(),tasks:ServerTasksCapabilitySchema$1.optional(),extensions:record(string2(),JSONObjectSchema$1).optional()}),ProgressSchema$1=object({progress:number2(),total:optional(number2()),message:optional(string2())}),ProgressNotificationParamsSchema$1=object({...NotificationsParamsSchema$1.shape,...ProgressSchema$1.shape,progressToken:ProgressTokenSchema$1}),ProgressNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/progress"),params:ProgressNotificationParamsSchema$1}),LoggingMessageNotificationParamsSchema$1=NotificationsParamsSchema$1.extend({level:LoggingLevelSchema$1,logger:string2().optional(),data:unknown()}),LoggingMessageNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/message"),params:LoggingMessageNotificationParamsSchema$1}),ResourceContentsSchema$1=object({uri:string2(),mimeType:optional(string2()),_meta:record(string2(),unknown()).optional()}),TextResourceContentsSchema$1=ResourceContentsSchema$1.extend({text:string2()}),BlobResourceContentsSchema$1=ResourceContentsSchema$1.extend({blob:Base64Schema2}),AnnotationsSchema$1=object({audience:array(RoleSchema$1).optional(),priority:number2().min(0).max(1).optional(),lastModified:iso_exports.datetime({offset:!0}).optional()}),ResourceSchema$1=object({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,uri:string2(),description:optional(string2()),mimeType:optional(string2()),size:optional(number2()),annotations:AnnotationsSchema$1.optional(),_meta:optional(looseObject({}))}),ResourceTemplateSchema$1=object({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,uriTemplate:string2(),description:optional(string2()),mimeType:optional(string2()),annotations:AnnotationsSchema$1.optional(),_meta:optional(looseObject({}))}),ResourceListChangedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/resources/list_changed"),params:NotificationsParamsSchema$1.optional()}),ResourceUpdatedNotificationParamsSchema$1=NotificationsParamsSchema$1.extend({uri:string2()}),ResourceUpdatedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/resources/updated"),params:ResourceUpdatedNotificationParamsSchema$1}),PromptArgumentSchema$1=object({name:string2(),description:optional(string2()),required:optional(boolean2())}),PromptSchema$1=object({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,description:optional(string2()),arguments:optional(array(PromptArgumentSchema$1)),_meta:optional(looseObject({}))}),PromptListChangedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/prompts/list_changed"),params:NotificationsParamsSchema$1.optional()}),TextContentSchema$1=object({type:literal("text"),text:string2(),annotations:AnnotationsSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),ImageContentSchema$1=object({type:literal("image"),data:Base64Schema2,mimeType:string2(),annotations:AnnotationsSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),AudioContentSchema$1=object({type:literal("audio"),data:Base64Schema2,mimeType:string2(),annotations:AnnotationsSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),ToolUseContentSchema$1=object({type:literal("tool_use"),name:string2(),id:string2(),input:record(string2(),unknown()),_meta:record(string2(),unknown()).optional()}),EmbeddedResourceSchema$1=object({type:literal("resource"),resource:union([TextResourceContentsSchema$1,BlobResourceContentsSchema$1]),annotations:AnnotationsSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),ResourceLinkSchema$1=ResourceSchema$1.extend({type:literal("resource_link")}),ContentBlockSchema$1=union([TextContentSchema$1,ImageContentSchema$1,AudioContentSchema$1,ResourceLinkSchema$1,EmbeddedResourceSchema$1]),PromptMessageSchema$1=object({role:RoleSchema$1,content:ContentBlockSchema$1}),ToolAnnotationsSchema$1=object({title:string2().optional(),readOnlyHint:boolean2().optional(),destructiveHint:boolean2().optional(),idempotentHint:boolean2().optional(),openWorldHint:boolean2().optional()}),ToolListChangedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/tools/list_changed"),params:NotificationsParamsSchema$1.optional()}),ModelHintSchema$1=object({name:string2().optional()}),ModelPreferencesSchema$1=object({hints:array(ModelHintSchema$1).optional(),costPriority:number2().min(0).max(1).optional(),speedPriority:number2().min(0).max(1).optional(),intelligencePriority:number2().min(0).max(1).optional()}),ToolChoiceSchema$1=object({mode:_enum(["auto","required","none"]).optional()}),BooleanSchemaSchema$1=object({type:literal("boolean"),title:string2().optional(),description:string2().optional(),default:boolean2().optional()}),StringSchemaSchema$1=object({type:literal("string"),title:string2().optional(),description:string2().optional(),minLength:number2().optional(),maxLength:number2().optional(),format:_enum(["email","uri","date","date-time"]).optional(),default:string2().optional()}),NumberSchemaSchema$1=object({type:_enum(["number","integer"]),title:string2().optional(),description:string2().optional(),minimum:number2().optional(),maximum:number2().optional(),default:number2().optional()}),UntitledSingleSelectEnumSchemaSchema$1=object({type:literal("string"),title:string2().optional(),description:string2().optional(),enum:array(string2()),default:string2().optional()}),TitledSingleSelectEnumSchemaSchema$1=object({type:literal("string"),title:string2().optional(),description:string2().optional(),oneOf:array(object({const:string2(),title:string2()})),default:string2().optional()}),LegacyTitledEnumSchemaSchema$1=object({type:literal("string"),title:string2().optional(),description:string2().optional(),enum:array(string2()),enumNames:array(string2()).optional(),default:string2().optional()}),SingleSelectEnumSchemaSchema$1=union([UntitledSingleSelectEnumSchemaSchema$1,TitledSingleSelectEnumSchemaSchema$1]),UntitledMultiSelectEnumSchemaSchema$1=object({type:literal("array"),title:string2().optional(),description:string2().optional(),minItems:number2().optional(),maxItems:number2().optional(),items:object({type:literal("string"),enum:array(string2())}),default:array(string2()).optional()}),TitledMultiSelectEnumSchemaSchema$1=object({type:literal("array"),title:string2().optional(),description:string2().optional(),minItems:number2().optional(),maxItems:number2().optional(),items:object({anyOf:array(object({const:string2(),title:string2()}))}),default:array(string2()).optional()}),MultiSelectEnumSchemaSchema$1=union([UntitledMultiSelectEnumSchemaSchema$1,TitledMultiSelectEnumSchemaSchema$1]),EnumSchemaSchema$1=union([LegacyTitledEnumSchemaSchema$1,SingleSelectEnumSchemaSchema$1,MultiSelectEnumSchemaSchema$1]),PrimitiveSchemaDefinitionSchema$1=union([EnumSchemaSchema$1,BooleanSchemaSchema$1,StringSchemaSchema$1,NumberSchemaSchema$1]),ElicitRequestFormParamsSchema$1=TaskAugmentedRequestParamsSchema$1.extend({mode:literal("form").optional(),message:string2(),requestedSchema:object({type:literal("object"),properties:record(string2(),PrimitiveSchemaDefinitionSchema$1),required:array(string2()).optional()}).catchall(unknown())}),ResourceTemplateReferenceSchema$1=object({type:literal("ref/resource"),uri:string2()}),PromptReferenceSchema$1=object({type:literal("ref/prompt"),name:string2()}),RootSchema$1=object({uri:string2().startsWith("file://"),name:string2().optional(),_meta:record(string2(),unknown()).optional()}),sharedClientCapabilityShape=ClientCapabilitiesSchema$1.shape,ClientCapabilities2026Schema=object({experimental:sharedClientCapabilityShape.experimental,sampling:sharedClientCapabilityShape.sampling,elicitation:sharedClientCapabilityShape.elicitation,roots:sharedClientCapabilityShape.roots,extensions:sharedClientCapabilityShape.extensions}),sharedServerCapabilityShape=ServerCapabilitiesSchema$1.shape,ServerCapabilities2026Schema=object({experimental:sharedServerCapabilityShape.experimental,logging:sharedServerCapabilityShape.logging,completions:sharedServerCapabilityShape.completions,prompts:sharedServerCapabilityShape.prompts,resources:sharedServerCapabilityShape.resources,tools:sharedServerCapabilityShape.tools,extensions:sharedServerCapabilityShape.extensions}),RequestMetaEnvelopeSchema=looseObject({progressToken:ProgressTokenSchema$1.optional(),[PROTOCOL_VERSION_META_KEY]:string2(),[CLIENT_INFO_META_KEY]:ImplementationSchema$1.optional(),[CLIENT_CAPABILITIES_META_KEY]:ClientCapabilities2026Schema,[LOG_LEVEL_META_KEY]:LoggingLevelSchema$1.optional()}),ToolSchema$1=object({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,description:string2().optional(),inputSchema:looseObject({$schema:string2().optional(),type:literal("object")}),outputSchema:looseObject({$schema:string2().optional()}).optional(),annotations:ToolAnnotationsSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),ToolResultContentSchema$1=object({type:literal("tool_result"),toolUseId:string2(),content:array(ContentBlockSchema$1),structuredContent:unknown().optional(),isError:boolean2().optional(),_meta:record(string2(),unknown()).optional()}),SamplingMessageContentBlockSchema$1=union([TextContentSchema$1,ImageContentSchema$1,AudioContentSchema$1,ToolUseContentSchema$1,ToolResultContentSchema$1]),SamplingMessageSchema$1=object({role:RoleSchema$1,content:union([SamplingMessageContentBlockSchema$1,array(SamplingMessageContentBlockSchema$1)]),_meta:record(string2(),unknown()).optional()}),ResultTypeSchema=string2(),ResultMetaSchema=looseObject({[SERVER_INFO_META_KEY]:ImplementationSchema$1.optional().catch(void 0)}),wireMeta=ResultMetaSchema.optional();function wireResult(shape){return looseObject({_meta:wireMeta,resultType:ResultTypeSchema.default("complete"),...shape})}let ResultSchema$1=wireResult({}),PaginatedResultSchema$1=wireResult({nextCursor:CursorSchema$1.optional()}),CallToolResultSchema$1=wireResult({content:array(ContentBlockSchema$1),structuredContent:unknown().optional(),isError:boolean2().optional()}),ListToolsResultSchema$1=wireResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),tools:array(ToolSchema$1),nextCursor:CursorSchema$1.optional()}),ListPromptsResultSchema$1=wireResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),prompts:array(PromptSchema$1),nextCursor:CursorSchema$1.optional()}),GetPromptResultSchema$1=wireResult({description:string2().optional(),messages:array(PromptMessageSchema$1)}),ListResourcesResultSchema$1=wireResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),resources:array(ResourceSchema$1),nextCursor:CursorSchema$1.optional()}),ListResourceTemplatesResultSchema$1=wireResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),resourceTemplates:array(ResourceTemplateSchema$1),nextCursor:CursorSchema$1.optional()}),ReadResourceResultSchema$1=wireResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),contents:array(union([TextResourceContentsSchema$1,BlobResourceContentsSchema$1]))}),CompleteResultSchema$1=wireResult({completion:object({values:array(string2()).max(100),total:number2().int().optional(),hasMore:boolean2().optional()}).loose()}),CacheableResultSchema=wireResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"])}),DiscoverResultSchema$1=wireResult({ttlMs:number2().int().min(0).catch(0),cacheScope:_enum(["public","private"]).catch("private"),supportedVersions:array(string2()),capabilities:ServerCapabilities2026Schema,instructions:string2().optional()}),CreateMessageRequestParamsSchema$1=object({messages:array(SamplingMessageSchema$1),modelPreferences:ModelPreferencesSchema$1.optional(),systemPrompt:string2().optional(),includeContext:_enum(["none","thisServer","allServers"]).optional(),temperature:number2().optional(),maxTokens:number2().int(),stopSequences:array(string2()).optional(),metadata:JSONObjectSchema$1.optional(),tools:array(ToolSchema$1).optional(),toolChoice:ToolChoiceSchema$1.optional()}),CreateMessageRequestSchema$1=object({method:literal("sampling/createMessage"),params:CreateMessageRequestParamsSchema$1}),ListRootsRequestSchema$1=object({method:literal("roots/list"),params:object({_meta:record(string2(),unknown()).optional()}).optional()}),CreateMessageResultSchema$1=object({...SamplingMessageSchema$1.shape,model:string2(),stopReason:string2().optional()}),ListRootsResultSchema$1=object({roots:array(RootSchema$1)}),ElicitResultSchema$1=object({action:_enum(["accept","decline","cancel"]),content:record(string2(),union([string2(),number2(),boolean2(),array(string2())])).optional()}),ElicitRequestURLParamsSchema$1=object({mode:literal("url"),message:string2(),url:string2().url()}),ElicitRequestParamsSchema$1=union([ElicitRequestFormParamsSchema$1,ElicitRequestURLParamsSchema$1]),ElicitRequestSchema$1=object({method:literal("elicitation/create"),params:ElicitRequestParamsSchema$1}),InputRequestSchema=union([CreateMessageRequestSchema$1,ListRootsRequestSchema$1,ElicitRequestSchema$1]),InputResponseSchema=union([CreateMessageResultSchema$1,ListRootsResultSchema$1,ElicitResultSchema$1]),InputRequestsSchema=record(string2(),InputRequestSchema),InputResponsesSchema=record(string2(),InputResponseSchema),InputRequiredResultSchema=wireResult({inputRequests:InputRequestsSchema.optional(),requestState:string2().optional()}),retryParamsShape={inputResponses:InputResponsesSchema.optional(),requestState:string2().optional()},InputResponseRequestParamsSchema=object({_meta:RequestMetaEnvelopeSchema,...retryParamsShape}),DispatchRequestMetaSchema=looseObject({progressToken:ProgressTokenSchema$1.optional()});function wireRequest(method,paramsShape){return object({method:literal(method),params:object({_meta:RequestMetaEnvelopeSchema,...paramsShape})})}function dispatchRequest(method,paramsShape){return object({method:literal(method),params:object({_meta:DispatchRequestMetaSchema.optional(),...paramsShape}).optional()})}let callToolParamsShape={name:string2(),arguments:record(string2(),unknown()).optional(),...retryParamsShape},paginatedParamsShape={cursor:CursorSchema$1.optional()},CallToolRequestSchema$1=wireRequest("tools/call",callToolParamsShape),ListToolsRequestSchema$1=wireRequest("tools/list",paginatedParamsShape),ListPromptsRequestSchema$1=wireRequest("prompts/list",paginatedParamsShape),GetPromptRequestSchema$1=wireRequest("prompts/get",{name:string2(),arguments:record(string2(),string2()).optional(),...retryParamsShape}),ListResourcesRequestSchema$1=wireRequest("resources/list",paginatedParamsShape),ListResourceTemplatesRequestSchema$1=wireRequest("resources/templates/list",paginatedParamsShape),ReadResourceRequestSchema$1=wireRequest("resources/read",{uri:string2(),...retryParamsShape}),completeParamsShape={ref:union([PromptReferenceSchema$1,ResourceTemplateReferenceSchema$1]),argument:object({name:string2(),value:string2()}),context:object({arguments:record(string2(),string2()).optional()}).optional()},CompleteRequestSchema$1=wireRequest("completion/complete",completeParamsShape),DiscoverRequestSchema$1=wireRequest("server/discover",{}),SubscriptionFilterSchema$1=object({toolsListChanged:boolean2().optional(),promptsListChanged:boolean2().optional(),resourcesListChanged:boolean2().optional(),resourceSubscriptions:array(string2()).optional()}),subscriptionsListenParamsShape={notifications:SubscriptionFilterSchema$1},SubscriptionsListenRequestSchema$1=wireRequest("subscriptions/listen",subscriptionsListenParamsShape),SubscriptionsListenResultMetaSchema$1=ResultMetaSchema.extend({"io.modelcontextprotocol/subscriptionId":RequestIdSchema$1}),SubscriptionsListenResultSchema$1=looseObject({_meta:SubscriptionsListenResultMetaSchema$1,resultType:ResultTypeSchema.default("complete")}),dispatchRequestSchemas={"tools/call":dispatchRequest("tools/call",callToolParamsShape),"tools/list":dispatchRequest("tools/list",paginatedParamsShape),"prompts/get":dispatchRequest("prompts/get",{name:string2(),arguments:record(string2(),string2()).optional()}),"prompts/list":dispatchRequest("prompts/list",paginatedParamsShape),"resources/list":dispatchRequest("resources/list",paginatedParamsShape),"resources/templates/list":dispatchRequest("resources/templates/list",paginatedParamsShape),"resources/read":dispatchRequest("resources/read",{uri:string2()}),"completion/complete":dispatchRequest("completion/complete",completeParamsShape),"server/discover":dispatchRequest("server/discover",{}),"subscriptions/listen":dispatchRequest("subscriptions/listen",subscriptionsListenParamsShape)};function liftedResult(shape){return looseObject({_meta:wireMeta,...shape})}let dispatchResultSchemas={"tools/call":liftedResult({content:array(ContentBlockSchema$1),structuredContent:unknown().optional(),isError:boolean2().optional()}),"tools/list":liftedResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),tools:array(ToolSchema$1),nextCursor:CursorSchema$1.optional()}),"prompts/get":liftedResult({description:string2().optional(),messages:array(PromptMessageSchema$1)}),"prompts/list":liftedResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),prompts:array(PromptSchema$1),nextCursor:CursorSchema$1.optional()}),"resources/list":liftedResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),resources:array(ResourceSchema$1),nextCursor:CursorSchema$1.optional()}),"resources/templates/list":liftedResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),resourceTemplates:array(ResourceTemplateSchema$1),nextCursor:CursorSchema$1.optional()}),"resources/read":liftedResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),contents:array(union([TextResourceContentsSchema$1,BlobResourceContentsSchema$1]))}),"completion/complete":liftedResult({completion:object({values:array(string2()).max(100),total:number2().int().optional(),hasMore:boolean2().optional()}).loose()}),"server/discover":liftedResult({ttlMs:number2().int().min(0).catch(0),cacheScope:_enum(["public","private"]).catch("private"),supportedVersions:array(string2()),capabilities:ServerCapabilities2026Schema,instructions:string2().optional()}),"subscriptions/listen":liftedResult({})},NotificationMetaSchema=looseObject({"io.modelcontextprotocol/subscriptionId":RequestIdSchema$1.optional()}),SubscriptionsAcknowledgedNotificationSchema$1=object({method:literal("notifications/subscriptions/acknowledged"),params:object({_meta:NotificationMetaSchema.optional(),notifications:SubscriptionFilterSchema$1})}),CancelledNotificationParamsSchema$1=object({_meta:NotificationMetaSchema.optional(),requestId:RequestIdSchema$1,reason:string2().optional()}),CancelledNotificationSchema$1=object({method:literal("notifications/cancelled"),params:CancelledNotificationParamsSchema$1}),notificationSchemas2026={"notifications/cancelled":CancelledNotificationSchema$1,"notifications/progress":ProgressNotificationSchema$1,"notifications/message":LoggingMessageNotificationSchema$1,"notifications/resources/updated":ResourceUpdatedNotificationSchema$1,"notifications/resources/list_changed":ResourceListChangedNotificationSchema$1,"notifications/tools/list_changed":ToolListChangedNotificationSchema$1,"notifications/prompts/list_changed":PromptListChangedNotificationSchema$1,"notifications/subscriptions/acknowledged":SubscriptionsAcknowledgedNotificationSchema$1},wireResultResponse=result=>object({jsonrpc:literal("2.0"),id:union([string2(),number2().int()]),result}).strict();return{JSONValueSchema:JSONValueSchema$1,JSONObjectSchema:JSONObjectSchema$1,ProgressTokenSchema:ProgressTokenSchema$1,CursorSchema:CursorSchema$1,RequestIdSchema:RequestIdSchema$1,RoleSchema:RoleSchema$1,LoggingLevelSchema:LoggingLevelSchema$1,TaskMetadataSchema:TaskMetadataSchema$1,RelatedTaskMetadataSchema:RelatedTaskMetadataSchema$1,RequestMetaSchema:RequestMetaSchema$1,BaseRequestParamsSchema:BaseRequestParamsSchema$1,TaskAugmentedRequestParamsSchema:TaskAugmentedRequestParamsSchema$1,NotificationsParamsSchema:NotificationsParamsSchema$1,NotificationSchema:NotificationSchema$1,IconSchema:IconSchema$1,IconsSchema:IconsSchema$1,BaseMetadataSchema:BaseMetadataSchema$1,ImplementationSchema:ImplementationSchema$1,ClientTasksCapabilitySchema:ClientTasksCapabilitySchema$1,ServerTasksCapabilitySchema:ServerTasksCapabilitySchema$1,ClientCapabilitiesSchema:ClientCapabilitiesSchema$1,ServerCapabilitiesSchema:ServerCapabilitiesSchema$1,ProgressSchema:ProgressSchema$1,ProgressNotificationParamsSchema:ProgressNotificationParamsSchema$1,ProgressNotificationSchema:ProgressNotificationSchema$1,LoggingMessageNotificationParamsSchema:LoggingMessageNotificationParamsSchema$1,LoggingMessageNotificationSchema:LoggingMessageNotificationSchema$1,ResourceContentsSchema:ResourceContentsSchema$1,TextResourceContentsSchema:TextResourceContentsSchema$1,BlobResourceContentsSchema:BlobResourceContentsSchema$1,AnnotationsSchema:AnnotationsSchema$1,ResourceSchema:ResourceSchema$1,ResourceTemplateSchema:ResourceTemplateSchema$1,ResourceListChangedNotificationSchema:ResourceListChangedNotificationSchema$1,ResourceUpdatedNotificationParamsSchema:ResourceUpdatedNotificationParamsSchema$1,ResourceUpdatedNotificationSchema:ResourceUpdatedNotificationSchema$1,PromptArgumentSchema:PromptArgumentSchema$1,PromptSchema:PromptSchema$1,PromptListChangedNotificationSchema:PromptListChangedNotificationSchema$1,TextContentSchema:TextContentSchema$1,ImageContentSchema:ImageContentSchema$1,AudioContentSchema:AudioContentSchema$1,ToolUseContentSchema:ToolUseContentSchema$1,EmbeddedResourceSchema:EmbeddedResourceSchema$1,ResourceLinkSchema:ResourceLinkSchema$1,ContentBlockSchema:ContentBlockSchema$1,PromptMessageSchema:PromptMessageSchema$1,ToolAnnotationsSchema:ToolAnnotationsSchema$1,ToolListChangedNotificationSchema:ToolListChangedNotificationSchema$1,ModelHintSchema:ModelHintSchema$1,ModelPreferencesSchema:ModelPreferencesSchema$1,ToolChoiceSchema:ToolChoiceSchema$1,BooleanSchemaSchema:BooleanSchemaSchema$1,StringSchemaSchema:StringSchemaSchema$1,NumberSchemaSchema:NumberSchemaSchema$1,UntitledSingleSelectEnumSchemaSchema:UntitledSingleSelectEnumSchemaSchema$1,TitledSingleSelectEnumSchemaSchema:TitledSingleSelectEnumSchemaSchema$1,LegacyTitledEnumSchemaSchema:LegacyTitledEnumSchemaSchema$1,SingleSelectEnumSchemaSchema:SingleSelectEnumSchemaSchema$1,UntitledMultiSelectEnumSchemaSchema:UntitledMultiSelectEnumSchemaSchema$1,TitledMultiSelectEnumSchemaSchema:TitledMultiSelectEnumSchemaSchema$1,MultiSelectEnumSchemaSchema:MultiSelectEnumSchemaSchema$1,EnumSchemaSchema:EnumSchemaSchema$1,PrimitiveSchemaDefinitionSchema:PrimitiveSchemaDefinitionSchema$1,ElicitRequestFormParamsSchema:ElicitRequestFormParamsSchema$1,ResourceTemplateReferenceSchema:ResourceTemplateReferenceSchema$1,PromptReferenceSchema:PromptReferenceSchema$1,RootSchema:RootSchema$1,ClientCapabilities2026Schema,ServerCapabilities2026Schema,RequestMetaEnvelopeSchema,ToolSchema:ToolSchema$1,ToolResultContentSchema:ToolResultContentSchema$1,SamplingMessageContentBlockSchema:SamplingMessageContentBlockSchema$1,SamplingMessageSchema:SamplingMessageSchema$1,ResultTypeSchema,ResultMetaSchema,ResultSchema:ResultSchema$1,PaginatedResultSchema:PaginatedResultSchema$1,CallToolResultSchema:CallToolResultSchema$1,ListToolsResultSchema:ListToolsResultSchema$1,ListPromptsResultSchema:ListPromptsResultSchema$1,GetPromptResultSchema:GetPromptResultSchema$1,ListResourcesResultSchema:ListResourcesResultSchema$1,ListResourceTemplatesResultSchema:ListResourceTemplatesResultSchema$1,ReadResourceResultSchema:ReadResourceResultSchema$1,CompleteResultSchema:CompleteResultSchema$1,CacheableResultSchema,DiscoverResultSchema:DiscoverResultSchema$1,CreateMessageRequestParamsSchema:CreateMessageRequestParamsSchema$1,CreateMessageRequestSchema:CreateMessageRequestSchema$1,ListRootsRequestSchema:ListRootsRequestSchema$1,CreateMessageResultSchema:CreateMessageResultSchema$1,ListRootsResultSchema:ListRootsResultSchema$1,ElicitResultSchema:ElicitResultSchema$1,ElicitRequestURLParamsSchema:ElicitRequestURLParamsSchema$1,ElicitRequestParamsSchema:ElicitRequestParamsSchema$1,ElicitRequestSchema:ElicitRequestSchema$1,InputRequestSchema,InputResponseSchema,InputRequestsSchema,InputResponsesSchema,InputRequiredResultSchema,InputResponseRequestParamsSchema,CallToolRequestSchema:CallToolRequestSchema$1,ListToolsRequestSchema:ListToolsRequestSchema$1,ListPromptsRequestSchema:ListPromptsRequestSchema$1,GetPromptRequestSchema:GetPromptRequestSchema$1,ListResourcesRequestSchema:ListResourcesRequestSchema$1,ListResourceTemplatesRequestSchema:ListResourceTemplatesRequestSchema$1,ReadResourceRequestSchema:ReadResourceRequestSchema$1,CompleteRequestSchema:CompleteRequestSchema$1,DiscoverRequestSchema:DiscoverRequestSchema$1,SubscriptionFilterSchema:SubscriptionFilterSchema$1,SubscriptionsListenRequestSchema:SubscriptionsListenRequestSchema$1,SubscriptionsListenResultMetaSchema:SubscriptionsListenResultMetaSchema$1,SubscriptionsListenResultSchema:SubscriptionsListenResultSchema$1,dispatchRequestSchemas,dispatchResultSchemas,NotificationMetaSchema,SubscriptionsAcknowledgedNotificationSchema:SubscriptionsAcknowledgedNotificationSchema$1,CancelledNotificationParamsSchema:CancelledNotificationParamsSchema$1,CancelledNotificationSchema:CancelledNotificationSchema$1,notificationSchemas2026,JSONRPCResultResponseSchema:wireResultResponse(ResultSchema$1),CallToolResultResponseSchema:wireResultResponse(union([CallToolResultSchema$1,InputRequiredResultSchema])),ListToolsResultResponseSchema:wireResultResponse(ListToolsResultSchema$1),ListPromptsResultResponseSchema:wireResultResponse(ListPromptsResultSchema$1),GetPromptResultResponseSchema:wireResultResponse(union([GetPromptResultSchema$1,InputRequiredResultSchema])),ListResourcesResultResponseSchema:wireResultResponse(ListResourcesResultSchema$1),ListResourceTemplatesResultResponseSchema:wireResultResponse(ListResourceTemplatesResultSchema$1),ReadResourceResultResponseSchema:wireResultResponse(union([ReadResourceResultSchema$1,InputRequiredResultSchema])),CompleteResultResponseSchema:wireResultResponse(CompleteResultSchema$1),DiscoverResultResponseSchema:wireResultResponse(DiscoverResultSchema$1)}}function buildSchemas2026(){return memo??=build()}function isCacheableResultMethod(method){return CACHEABLE_RESULT_METHODS.includes(method)}function attachCacheHintFallback(result,hint){if(hint===void 0)return result;let attached=result[RESULT_CACHE_HINT_FALLBACK];if(attached===void 0)return{...result,[RESULT_CACHE_HINT_FALLBACK]:hint};let merged={},ttlMs=attached.ttlMs??hint.ttlMs;ttlMs!==void 0&&(merged.ttlMs=ttlMs);let cacheScope=attached.cacheScope??hint.cacheScope;return cacheScope!==void 0&&(merged.cacheScope=cacheScope),{...result,[RESULT_CACHE_HINT_FALLBACK]:merged}}function cacheHintFallbackOf(result){return result[RESULT_CACHE_HINT_FALLBACK]}function isValidCacheTtlMs(value){return typeof value=="number"&&Number.isSafeInteger(value)&&value>=0}function isValidCacheScope(value){return value==="public"||value==="private"}function assertValidCacheHint(hint,context){if(hint.ttlMs!==void 0&&!isValidCacheTtlMs(hint.ttlMs))throw new RangeError(`Invalid cache hint for ${context}: ttlMs must be a non-negative safe integer (got ${String(hint.ttlMs)})`);if(hint.cacheScope!==void 0&&!isValidCacheScope(hint.cacheScope))throw new RangeError(`Invalid cache hint for ${context}: cacheScope must be 'public' or 'private' (got ${String(hint.cacheScope)})`)}function stampResultType(method,result){let provided=result.resultType;if(provided===void 0)return{...result,resultType:"complete"};if(provided==="complete"||EXTENDED_RESULT_TYPE_METHODS.includes(method))return result;throw new ProtocolError(ProtocolErrorCode.InternalError,`Handler for ${method} returned resultType '${String(provided)}', but results of ${method} only support 'complete' on protocol revision 2026-07-28`)}function fillCacheFields(method,result){let fallback=cacheHintFallbackOf(result);if(result.resultType!=="complete"||!isCacheableResultMethod(method))return fallback===void 0?result:stripCacheHintFallback(result);let provided=result,ttlMs=isValidCacheTtlMs(provided.ttlMs)?provided.ttlMs:resolveTtlMs(fallback),cacheScope=isValidCacheScope(provided.cacheScope)?provided.cacheScope:resolveCacheScope(fallback),filled={...provided,ttlMs,cacheScope};return delete filled[RESULT_CACHE_HINT_FALLBACK],filled}function isPlainObject$5(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function stampServerInfoMeta(result,serverInfo){if(serverInfo===void 0)return result;let meta2=result._meta;return meta2===void 0?{...result,_meta:{[SERVER_INFO_META_KEY]:serverInfo}}:!isPlainObject$5(meta2)||meta2[SERVER_INFO_META_KEY]!==void 0?result:{...result,_meta:{...meta2,[SERVER_INFO_META_KEY]:serverInfo}}}function resolveTtlMs(fallback){return fallback!==void 0&&isValidCacheTtlMs(fallback.ttlMs)?fallback.ttlMs:DEFAULT_CACHE_TTL_MS}function resolveCacheScope(fallback){return fallback!==void 0&&isValidCacheScope(fallback.cacheScope)?fallback.cacheScope:DEFAULT_CACHE_SCOPE}function stripCacheHintFallback(result){let copy={...result};return delete copy[RESULT_CACHE_HINT_FALLBACK],copy}function inputSchemaMaps(){if(maps)return maps;let s=buildSchemas2026();return maps={request:{"elicitation/create":object({method:literal("elicitation/create"),params:s.ElicitRequestParamsSchema}),"sampling/createMessage":object({method:literal("sampling/createMessage"),params:s.CreateMessageRequestParamsSchema}),"roots/list":object({method:literal("roots/list"),params:looseObject({}).optional()})},response:{"elicitation/create":s.ElicitResultSchema,"sampling/createMessage":s.CreateMessageResultSchema,"roots/list":s.ListRootsResultSchema}},maps}function isInputRequestMethod2026(method){return INPUT_REQUEST_METHODS_2026.includes(method)}function getInputRequestSchema2026(method){return isInputRequestMethod2026(method)?inputSchemaMaps().request[method]:void 0}function getInputResponseSchema2026(method){return isInputRequestMethod2026(method)?inputSchemaMaps().response[method]:void 0}function hasRequestMethod2026(method){return Object.prototype.hasOwnProperty.call(requestMethodKeys,method)}function hasNotificationMethod2026(method){return Object.prototype.hasOwnProperty.call(notificationMethodKeys,method)}function hasResultMethod2026(method){return Object.prototype.hasOwnProperty.call(requestMethodKeys,method)}function getRequestSchema2026(method){return hasRequestMethod2026(method)?buildSchemas2026().dispatchRequestSchemas[method]:void 0}function getResultSchema2026(method){return hasResultMethod2026(method)?buildSchemas2026().dispatchResultSchemas[method]:void 0}function getNotificationSchema2026(method){return hasNotificationMethod2026(method)?buildSchemas2026().notificationSchemas2026[method]:void 0}function isPlainObject$4(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function triState(schema2,raw2){if(schema2===void 0)return{ok:!1,reason:"not-in-era"};let parsed=schema2.safeParse(raw2);return parsed.success?{ok:!0,value:parsed.data}:{ok:!1,reason:"invalid",message:String(parsed.error)}}function enforceDeletedFields(method,result){let next=result,copied=!1,copy=()=>(copied||(next={...next},copied=!0),next),tools=result.tools;method==="tools/list"&&Array.isArray(tools)&&tools.some(tool=>isPlainObject$4(tool)&&"execution"in tool)&&(copy().tools=tools.map(tool=>{if(!isPlainObject$4(tool)||!("execution"in tool))return tool;let rest={...tool};return delete rest.execution,rest}));let capabilities=result.capabilities;if(isPlainObject$4(capabilities)&&"tasks"in capabilities){let rest={...capabilities};delete rest.tasks,copy().capabilities=rest}return next}function getWireResultSchemas(){if(wireResultSchemasMemo)return wireResultSchemasMemo;let s=buildSchemas2026();return wireResultSchemasMemo={"tools/call":s.CallToolResultSchema,"tools/list":s.ListToolsResultSchema,"prompts/get":s.GetPromptResultSchema,"prompts/list":s.ListPromptsResultSchema,"resources/list":s.ListResourcesResultSchema,"resources/templates/list":s.ListResourceTemplatesResultSchema,"resources/read":s.ReadResourceResultSchema,"completion/complete":s.CompleteResultSchema,"server/discover":s.DiscoverResultSchema},wireResultSchemasMemo}function codecForVersion(version2){return version2!==void 0&&isModernProtocolVersion(version2)?rev2026Codec:rev2025Codec}function classifiedWireEra(classification){return classification.revision!==void 0?codecForVersion(classification.revision).era:classification.era==="modern"?rev2026Codec.era:rev2025Codec.era}function isSpecRequestMethod(method){return ALL_CODECS.some(codec=>codec.hasRequestMethod(method))}function isSpecNotificationMethod(method){return ALL_CODECS.some(codec=>codec.hasNotificationMethod(method))}function isPlainObject$3(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function requestMetaOf(params){if(!isPlainObject$3(params))return;let meta2=params._meta;return isPlainObject$3(meta2)?meta2:void 0}function hasEnvelopeClaim(params){let meta2=requestMetaOf(params);return meta2!==void 0&&PROTOCOL_VERSION_META_KEY in meta2}function envelopeClaimVersion(params){let value=requestMetaOf(params)?.[PROTOCOL_VERSION_META_KEY];return typeof value=="string"?value:void 0}function validateEnvelopeMeta(meta2){return codecForVersion(MODERN_WIRE_REVISION).validateEnvelopeMeta(meta2)}function assertCompleteRequestPrompt(request){if(request.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`)}function assertCompleteRequestResourceTemplate(request){if(request.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`)}function scanXMcpHeaderDeclarations(inputSchema){let declarations=[],seenLower=new Map,visit=(node,path,reachable)=>{if(node===null||typeof node!="object")return;let schema2=node;if(X_MCP_HEADER_KEY in schema2){if(!reachable||path.length===0)return`${pathName(path)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;let raw2=schema2[X_MCP_HEADER_KEY];if(typeof raw2!="string"||raw2.length===0)return`${pathName(path)}: x-mcp-header MUST be a non-empty string`;if(!RFC9110_TOKEN.test(raw2))return`${pathName(path)}: x-mcp-header '${raw2}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;let type=typeof schema2.type=="string"?schema2.type:void 0;if(type===void 0||!PERMITTED_X_MCP_HEADER_TYPES.has(type))return`${pathName(path)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${type??"<none>"}`;let lower=raw2.toLowerCase(),prior=seenLower.get(lower);if(prior!==void 0)return`x-mcp-header '${raw2}' is not case-insensitively unique (also declared as '${prior}')`;seenLower.set(lower,raw2),declarations.push({path,headerName:raw2,type})}let properties=schema2.properties;if(properties!==null&&typeof properties=="object")for(let[key,child]of Object.entries(properties)){let fault$1=visit(child,[...path,key],reachable);if(fault$1!==void 0)return fault$1}for(let k of NON_REACHABLE_SUBSCHEMA_KEYWORDS){let sub=schema2[k];if(sub===void 0)continue;let branches=Array.isArray(sub)?sub:sub!==null&&typeof sub=="object"&&OBJECT_VALUED_SUBSCHEMA_KEYWORDS.has(k)?Object.values(sub):[sub];for(let branch of branches){let fault$1=visit(branch,[...path,`<${k}>`],!1);if(fault$1!==void 0)return fault$1}}},fault=visit(inputSchema,[],!0);return fault===void 0?{valid:!0,declarations}:{valid:!1,reason:fault}}function pathName(path){return path.length===0?"<root>":path.join(".")}function mcpParamPrimitiveToString(value){if(typeof value=="string")return value;if(typeof value=="boolean")return value?"true":"false";if(typeof value=="number")return!Number.isFinite(value)||Number.isInteger(value)&&!Number.isSafeInteger(value)?void 0:String(value)}function base64ToUtf8(b64){let bin=atob(b64),bytes=new Uint8Array(bin.length);for(let i=0;i<bin.length;i++)bytes[i]=bin.codePointAt(i);return new TextDecoder("utf-8",{fatal:!0}).decode(bytes)}function decodeMcpParamValue(value){if(!(value.startsWith(BASE64_SENTINEL_PREFIX)&&value.endsWith(BASE64_SENTINEL_SUFFIX)))return value;let b64=value.slice(9,value.length-2);if(BASE64_CANONICAL.test(b64))try{return base64ToUtf8(b64)}catch{return}}function valueAtPath(root,path){let node=root;for(let key of path){if(node===null||typeof node!="object")return;node=node[key]}return node}function validateMcpParamHeaders(declarations,args,headers){for(let decl of declarations){let headerKey=`${MCP_PARAM_HEADER_PREFIX}${decl.headerName}`,headerValue=headers.get(headerKey),bodyRaw=valueAtPath(args,decl.path);if(bodyRaw==null)continue;let bodyString=mcpParamPrimitiveToString(bodyRaw);if(bodyString===void 0)continue;if(headerValue===null)return paramHeaderMismatchRejection("param-header-missing",headerKey,`the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)} but the ${headerKey} header is absent`);let decoded=decodeMcpParamValue(headerValue);if(decoded===void 0)return paramHeaderMismatchRejection("param-header-invalid-encoding",headerKey,`the ${headerKey} header carries an invalid Base64 sentinel value`);if(!((decl.type==="integer"||decl.type==="number")&&CANONICAL_DECIMAL.test(decoded)&&typeof bodyRaw=="number"?Number(decoded)===bodyRaw:decoded===bodyString))return paramHeaderMismatchRejection("param-header-mismatch",headerKey,`the ${headerKey} header decodes to ${JSON.stringify(decoded)} but the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)}`)}}function paramHeaderMismatchRejection(cell,header,body){return{kind:"reject",rung:"param-header-validation",cell,httpStatus:400,code:HEADER_MISMATCH_ERROR_CODE,message:`Bad Request: the request headers and body disagree: ${body}`,data:{mismatch:{header,body}},settled:!0}}function httpStatusForErrorCode(code,origin){return origin==="in-band"?code===ProtocolErrorCode.MissingRequiredClientCapability?400:200:LADDER_ERROR_HTTP_STATUS[code]??400}function rejection(rung,cell,httpStatus,error3,settled){return{kind:"reject",rung,cell,httpStatus,code:error3.code,message:error3.message,...error3.data!==void 0&&{data:error3.data},settled}}function crossCheckMismatch(cell,header,body,rung="era-classification"){return rejection(rung,cell,400,new ProtocolError(HEADER_MISMATCH_ERROR_CODE,`Bad Request: the request headers and body disagree: ${body}`,{mismatch:{header,body}}),!0)}function stripHttpOws(value){let start=0;for(;start<value.length;){let code=value.codePointAt(start);if(code!==9&&code!==32)break;start+=1}let end=value.length;for(;end>start;){let code=value.codePointAt(end-1);if(code!==9&&code!==32)break;end-=1}return start===0&&end===value.length?value:value.slice(start,end)}function validateStandardRequestHeaders(request,route){if(route.messageKind!=="request")return;let method=route.message.method;if(request.mcpMethodHeader===void 0)return crossCheckMismatch("method-header-missing","(missing)",`the body names method ${method} but the required Mcp-Method header is absent`,"standard-header-validation");let sourceField=Object.hasOwn(MCP_NAME_HEADER_SOURCE,method)?MCP_NAME_HEADER_SOURCE[method]:void 0;if(sourceField===void 0)return;let sourceValue=route.message.params?.[sourceField],bodyValue=typeof sourceValue=="string"?sourceValue:void 0;if(request.mcpNameHeader===void 0)return bodyValue===void 0?void 0:crossCheckMismatch("name-header-missing","(missing)",`the body carries params.${sourceField}="${bodyValue}" but the required Mcp-Name header is absent`,"standard-header-validation");let normalizedNameHeader=stripHttpOws(request.mcpNameHeader),decoded=decodeMcpParamValue(normalizedNameHeader);if(decoded===void 0)return crossCheckMismatch("name-header-invalid-encoding",normalizedNameHeader,"the Mcp-Name header carries an invalid Base64 sentinel value","standard-header-validation");if(bodyValue!==void 0&&decoded!==bodyValue)return crossCheckMismatch("name-header-mismatch",normalizedNameHeader,`the body carries params.${sourceField}="${bodyValue}" but the Mcp-Name header names "${decoded}"`,"standard-header-validation")}function isPlainObject$2(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function classificationForClaim(claimedVersion){return claimedVersion===void 0?{era:"modern"}:{era:isModernProtocolVersion(claimedVersion)?"modern":"legacy",revision:claimedVersion}}function carriesValidModernEnvelopeClaim(params){if(!hasEnvelopeClaim(params))return!1;let claimedVersion=envelopeClaimVersion(params);if(claimedVersion===void 0||!isModernProtocolVersion(claimedVersion))return!1;let meta2=requestMetaOf(params);return meta2!==void 0&&validateEnvelopeMeta(meta2).length===0}function classifyBatch(body){if(body.length===0)return rejection("jsonrpc-shape","empty-batch",400,new ProtocolError(ProtocolErrorCode.InvalidRequest,"Bad Request: empty JSON-RPC batch"),!0);for(let element of body){if(hasEnvelopeClaim(isPlainObject$2(element)?element.params:void 0))return rejection("jsonrpc-shape","batch-with-modern-element",400,new ProtocolError(ProtocolErrorCode.InvalidRequest,"Bad Request: JSON-RPC batches may not contain requests for protocol revision 2026-07-28 or later"),!0);if(!(isJSONRPCRequest(element)||isJSONRPCNotification(element)||isJSONRPCResultResponse(element)||isJSONRPCErrorResponse(element)))return rejection("jsonrpc-shape","batch-with-invalid-element",400,new ProtocolError(ProtocolErrorCode.InvalidRequest,"Bad Request: JSON-RPC batch contains an invalid message"),!0)}return{kind:"legacy",reason:"batch"}}function classifyRequestBody(request,body){let params=body.params,method=body.method,headerVersion=request.protocolVersionHeader,headerNamesModern=headerVersion!==void 0&&isModernProtocolVersion(headerVersion);if(method==="initialize"&&!carriesValidModernEnvelopeClaim(params)){if(headerNamesModern)return crossCheckMismatch("initialize-with-modern-header",headerVersion,"an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header");let requestedVersion=isPlainObject$2(params)&&typeof params.protocolVersion=="string"?params.protocolVersion:void 0;return{kind:"legacy",reason:"initialize",...requestedVersion!==void 0&&{requestedVersion}}}if(hasEnvelopeClaim(params)){let meta2=requestMetaOf(params),firstIssue=(meta2===void 0?[]:validateEnvelopeMeta(meta2))[0];if(firstIssue!==void 0)return rejection("envelope","envelope-invalid",400,new ProtocolError(ProtocolErrorCode.InvalidParams,`Invalid _meta envelope for protocol revision 2026-07-28: ${firstIssue.key}: ${firstIssue.problem}`,{envelope:firstIssue}),!0);let claimedVersion=envelopeClaimVersion(params);return headerVersion!==void 0&&claimedVersion!==void 0&&headerVersion!==claimedVersion?crossCheckMismatch("header-body-version-mismatch",headerVersion,`the body envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`):request.mcpMethodHeader!==void 0&&request.mcpMethodHeader!==method?crossCheckMismatch("method-header-mismatch",request.mcpMethodHeader,`the body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`):{kind:"modern",messageKind:"request",message:body,classification:classificationForClaim(claimedVersion)}}if(headerNamesModern){let meta2=requestMetaOf(params),missingFromEnvelope=validateEnvelopeMeta(meta2??{}).filter(issue2=>issue2.problem==="missing").map(issue2=>issue2.key),missing=meta2===void 0?["_meta"]:missingFromEnvelope.length>0?missingFromEnvelope:[PROTOCOL_VERSION_META_KEY];return rejection("envelope","modern-header-without-claim",400,new ProtocolError(ProtocolErrorCode.InvalidParams,`Invalid params: the MCP-Protocol-Version header names protocol revision ${headerVersion}, but the request is missing the required per-request envelope key(s): ${missing.join(", ")}`,{envelope:{missing}}),!0)}return{kind:"legacy",reason:"no-claim",...headerVersion!==void 0&&{requestedVersion:headerVersion}}}function classifyNotificationBody(request,body){let params=body.params,method=body.method,headerVersion=request.protocolVersionHeader,headerNamesModern=headerVersion!==void 0&&isModernProtocolVersion(headerVersion);if(hasEnvelopeClaim(params)){let claimedVersion=envelopeClaimVersion(params);if(claimedVersion===void 0){let meta2=requestMetaOf(params),claimIssue=(meta2===void 0?[]:validateEnvelopeMeta(meta2)).find(issue2=>issue2.key===PROTOCOL_VERSION_META_KEY)??{key:PROTOCOL_VERSION_META_KEY,problem:"expected a protocol version string"};return rejection("envelope","notification-envelope-invalid",400,new ProtocolError(ProtocolErrorCode.InvalidParams,`Invalid _meta envelope for protocol revision 2026-07-28: ${claimIssue.key}: ${claimIssue.problem}`,{envelope:claimIssue}),!0)}if(headerVersion!==void 0&&headerVersion!==claimedVersion)return crossCheckMismatch("notification-header-body-version-mismatch",headerVersion,`the notification envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`);let classification=classificationForClaim(claimedVersion);return classification.era==="modern"&&request.mcpMethodHeader!==void 0&&request.mcpMethodHeader!==method?crossCheckMismatch("notification-method-header-mismatch",request.mcpMethodHeader,`the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`):{kind:"modern",messageKind:"notification",message:body,classification}}return headerNamesModern?request.mcpMethodHeader!==void 0&&request.mcpMethodHeader!==method?crossCheckMismatch("notification-method-header-mismatch",request.mcpMethodHeader,`the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`):{kind:"modern",messageKind:"notification",message:body,classification:{era:"modern",revision:headerVersion}}:{kind:"legacy",reason:"notification",...headerVersion!==void 0&&{requestedVersion:headerVersion}}}function classifyInboundRequest(request){if(request={...request,...request.protocolVersionHeader!==void 0&&{protocolVersionHeader:stripHttpOws(request.protocolVersionHeader)},...request.mcpMethodHeader!==void 0&&{mcpMethodHeader:stripHttpOws(request.mcpMethodHeader)},...request.mcpNameHeader!==void 0&&{mcpNameHeader:stripHttpOws(request.mcpNameHeader)}},request.httpMethod.toUpperCase()!=="POST")return{kind:"legacy",reason:"http-method"};let body=request.body;return Array.isArray(body)?classifyBatch(body):isJSONRPCResultResponse(body)||isJSONRPCErrorResponse(body)?{kind:"legacy",reason:"response"}:isPlainObject$2(body)&&isJSONRPCRequest(body)?classifyRequestBody(request,body):isPlainObject$2(body)&&isJSONRPCNotification(body)?classifyNotificationBody(request,body):rejection("jsonrpc-shape","invalid-json-rpc-body",400,new ProtocolError(ProtocolErrorCode.InvalidRequest,"Bad Request: the request body is not a valid JSON-RPC message"),!0)}function modernOnlyStrictRejection(route,supportedVersions){switch(route.reason){case"http-method":return rejection("http-method","modern-only-method-not-allowed",405,new ProtocolError(-32e3,"Method not allowed."),!0);case"batch":return rejection("jsonrpc-shape","modern-only-batch-not-supported",400,new ProtocolError(ProtocolErrorCode.InvalidRequest,"Bad Request: JSON-RPC batches are not supported by this endpoint"),!0);case"response":return rejection("jsonrpc-shape","modern-only-response-post",400,new ProtocolError(ProtocolErrorCode.InvalidRequest,"Bad Request: JSON-RPC responses cannot be posted to this endpoint"),!0);case"notification":return;case"initialize":case"no-claim":{let requested=route.requestedVersion;return rejection("era-classification","modern-only-missing-envelope",400,requested===void 0?new ProtocolError(ProtocolErrorCode.UnsupportedProtocolVersion,"Unsupported protocol version: the request did not name a protocol version",{supported:[...supportedVersions]}):new UnsupportedProtocolVersionError({supported:[...supportedVersions],requested}),!0)}}}function parseSchema(schema2,data){return safeParse2(schema2,data)}function shapeKeys(schemas){return new Set(schemas.flatMap(schema2=>Object.keys(schema2.shape)))}function isStandardSchema(schema2){if(schema2==null)return!1;let schemaType=typeof schema2;return schemaType!=="object"&&schemaType!=="function"||!("~standard"in schema2)?!1:typeof schema2["~standard"]?.validate=="function"}function standardSchemaToJsonSchema(schema2,io="input"){let std=schema2["~standard"],result;if(std.jsonSchema)result=std.jsonSchema[io]({target:JSON_SCHEMA_CONVERSION_TARGET});else if(std.vendor==="zod"){if(!("_zod"in schema2))throw new Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().");warnedZodFallback||(warnedZodFallback=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.")),result=toJSONSchema(schema2,{target:JSON_SCHEMA_CONVERSION_TARGET,io})}else throw new Error(`Schema library "${std.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(io==="output")return result.type!==void 0?result:isProvablyObjectShapedRoot(result)?{type:"object",...result}:result;if(result.type!==void 0&&result.type!=="object")throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(result.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:"object",...result}}function isProvablyObjectShapedRoot(schema2){if("properties"in schema2||"patternProperties"in schema2||"additionalProperties"in schema2||"required"in schema2)return!0;for(let key of["oneOf","anyOf","allOf"]){let members=schema2[key];if(Array.isArray(members)&&members.length>0)return members.every(m=>m!==null&&typeof m=="object"&&(m.type==="object"||isProvablyObjectShapedRoot(m)))}return!1}function formatIssue(issue2){return issue2.path?.length?`${issue2.path.map(p=>String(typeof p=="object"?p.key:p)).join(".")}: ${issue2.message}`:issue2.message}async function validateStandardSchema(schema2,data){let result=await schema2["~standard"].validate(data);return result.issues&&result.issues.length>0?{success:!1,error:result.issues.map(i=>formatIssue(i)).join(", ")}:{success:!0,data:result.value}}function zodEmittedPattern(schema2){let jsonSchema=toJSONSchema(schema2,{target:JSON_SCHEMA_CONVERSION_TARGET,io:"input"});return typeof jsonSchema.pattern=="string"?jsonSchema.pattern:void 0}function datetimeReferenceSchemas(pattern){let fractionDigits=DATETIME_FRACTION_DIGITS.exec(pattern),precisions=[void 0,-1,0];return fractionDigits&&precisions.push(Number(fractionDigits[1])),[!1,!0].flatMap(local=>[!1,!0].flatMap(offset=>precisions.map(precision=>iso_exports.datetime({local,offset,precision}))))}function referencePatternsForFormat(format,pattern){let referenceSchemas;switch(format){case"email":referenceSchemas=[email2()];break;case"uri":referenceSchemas=[url()];break;case"date":referenceSchemas=[iso_exports.date()];break;case"date-time":referenceSchemas=datetimeReferenceSchemas(pattern);break}return new Set(referenceSchemas.map(schema2=>zodEmittedPattern(schema2)).filter(emitted=>emitted!==void 0))}function isLibraryFormatPattern(format,pattern,vendor){return vendor!=="zod"?!0:referencePatternsForFormat(format,pattern).has(pattern)}function promptArgumentsFromStandardSchema(schema2){let jsonSchema=standardSchemaToJsonSchema(schema2,"input"),properties=jsonSchema.properties||{},required2=jsonSchema.required||[];return Object.entries(properties).map(([name,prop])=>({name,description:prop?.description,required:required2.includes(name)}))}function isJsonObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function convertStandardElicitationSchema(schema2){try{return standardSchemaToJsonSchema(schema2,"input")}catch(error3){let detail=error3 instanceof Error?error3.message:String(error3);throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${detail}`)}}function isAnnotationOnlyJsonSchemaKeyword(key){return ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS.has(key)||key.startsWith("x-")}function walkProperty(node,path,vendor,unsupported){if(!isJsonObject(node))return node;let allowedKeys=typeof node.type=="string"&&Object.hasOwn(PROPERTY_KEYS_BY_TYPE,node.type)?PROPERTY_KEYS_BY_TYPE[node.type]:void 0;if(allowedKeys===void 0)return node;let pruned={};for(let[key,value]of Object.entries(node))allowedKeys.has(key)||isAnnotationOnlyJsonSchemaKeyword(key)?pruned[key]=value:key==="pattern"&&node.type==="string"&&typeof node.format=="string"?SUPPORTED_STRING_FORMATS.has(node.format)?(typeof value!="string"||!isLibraryFormatPattern(node.format,value,vendor))&&unsupported.push(`${path}.${key}`):pruned[key]=value:unsupported.push(`${path}.${key}`);return pruned}function walkRequestedSchema(converted,vendor){let pruned={},unsupported=[];for(let[key,value]of Object.entries(converted))key==="properties"&&isJsonObject(value)?pruned[key]=Object.fromEntries(Object.entries(value).map(([name,node])=>[name,walkProperty(node,`properties.${name}`,vendor,unsupported)])):ROOT_KEYS.has(key)?pruned[key]=value:isAnnotationOnlyJsonSchemaKeyword(key)||unsupported.push(key);if(unsupported.length>0)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${unsupported.join(", ")}`);return pruned}function describeUnsupportedProperties(pruned,fallback){if(!isJsonObject(pruned.properties))return fallback;let offenders=Object.entries(pruned.properties).filter(([,node])=>!parseSchema(PrimitiveSchemaDefinitionSchema,node).success).map(([name])=>`properties.${name}`);return offenders.length>0?offenders.join(", "):fallback}function findDroppedConstraintPaths(original,parsed,path=""){return Array.isArray(original)&&Array.isArray(parsed)?original.flatMap((item,index)=>findDroppedConstraintPaths(item,parsed[index],`${path}[${index}]`)):!isJsonObject(original)||!isJsonObject(parsed)?[]:Object.entries(original).flatMap(([key,value])=>{let childPath=path?`${path}.${key}`:key;return Object.prototype.hasOwnProperty.call(parsed,key)?findDroppedConstraintPaths(value,parsed[key],childPath):isAnnotationOnlyJsonSchemaKeyword(key)?[]:[childPath]})}function normalizeElicitInputParams(input){if(!isStandardSchema(input.requestedSchema))return{...input,mode:"form",requestedSchema:input.requestedSchema};let vendor=input.requestedSchema["~standard"].vendor,pruned=walkRequestedSchema(convertStandardElicitationSchema(input.requestedSchema),vendor),parsed=parseSchema(ElicitRequestFormParamsSchema.shape.requestedSchema,pruned);if(!parsed.success)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${describeUnsupportedProperties(pruned,parsed.error.message)}`);let droppedConstraints=findDroppedConstraintPaths(pruned,parsed.data);if(droppedConstraints.length>0)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${droppedConstraints.join(", ")}`);let danglingRequired=(parsed.data.required??[]).filter(key=>!Object.prototype.hasOwnProperty.call(parsed.data.properties,key));if(danglingRequired.length>0)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${danglingRequired.join(", ")}`);return{...input,mode:"form",requestedSchema:parsed.data}}function buildInputRequired(spec){let hasInputRequests=spec.inputRequests!==void 0&&Object.keys(spec.inputRequests).length>0,hasRequestState=typeof spec.requestState=="string";if(!hasInputRequests&&!hasRequestState)throw new TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)");return{resultType:"input_required",...spec.inputRequests!==void 0&&{inputRequests:spec.inputRequests},...spec.requestState!==void 0&&{requestState:spec.requestState}}}function acceptedContent(responses,key,schema2){let view=inputResponse(responses,key);if(view.kind!=="elicit"||view.action!=="accept"||view.content===void 0)return;if(schema2===void 0)return view.content;let outcome=schema2["~standard"].validate(view.content);if(outcome instanceof Promise)throw new TypeError("acceptedContent(responses, key, schema) requires a synchronously-validating schema");return outcome.issues===void 0?outcome.value:void 0}function inputResponse(responses,key){if(responses===void 0||typeof responses!="object"||responses===null)return{kind:"missing"};let entry=responses[key];if(entry===null||typeof entry!="object"||Array.isArray(entry))return{kind:"missing"};let candidate=entry;if(candidate.action==="accept"||candidate.action==="decline"||candidate.action==="cancel"){let content=candidate.content;return{kind:"elicit",action:candidate.action,...content!==null&&typeof content=="object"&&!Array.isArray(content)&&{content}}}return Array.isArray(candidate.roots)?{kind:"roots",roots:candidate.roots}:typeof candidate.role=="string"&&candidate.content!==void 0?{kind:"sampling",result:candidate}:{kind:"missing"}}function inputRequiredRoundsExceededMessage(method,maxRounds){return`Multi-round-trip request '${method}' still required input after ${maxRounds} rounds (inputRequired.maxRounds)`}function sleep(ms,signal){return new Promise((resolve,reject)=>{if(signal?.aborted){reject(signal.reason instanceof SdkError?signal.reason:new SdkError(SdkErrorCode.RequestTimeout,String(signal.reason)));return}let timer=setTimeout(()=>{signal?.removeEventListener("abort",onAbort),resolve()},ms),onAbort=()=>{clearTimeout(timer),reject(signal?.reason instanceof SdkError?signal.reason:new SdkError(SdkErrorCode.RequestTimeout,String(signal?.reason)))};signal?.addEventListener("abort",onAbort,{once:!0})})}function linkedRoundAbort(outer){let controller=new AbortController,onOuterAbort=()=>controller.abort(outer?.reason);return outer?.addEventListener("abort",onOuterAbort,{once:!0}),outer?.aborted&&controller.abort(outer.reason),{signal:controller.signal,abort:reason=>controller.abort(reason),dispose:()=>outer?.removeEventListener("abort",onOuterAbort)}}function register(key,schema2){let name=key.slice(0,-6);_specTypeSchemas[name]=schema2,_isSpecType[name]=v=>schema2.safeParse(v).success}function bootstrapOutboundCodec(method){switch(method){case"initialize":case"notifications/initialized":return codecForVersion(void 0);case"server/discover":return codecForVersion(MODERN_WIRE_REVISION);default:return}}function liftWireOnlyMaterial(message,kind){let params=message.params;if(!isPlainObject$1(params))return{message,lifted:{}};let meta2=params._meta,envelopeKeys=isPlainObject$1(meta2)?RESERVED_ENVELOPE_META_KEYS.filter(key=>key in meta2):[],retryKeys=kind==="request"?RETRY_PARAMS_KEYS.filter(key=>key in params):[];if(envelopeKeys.length===0&&retryKeys.length===0)return{message,lifted:{}};let lifted={},nextParams={...params};if(envelopeKeys.length>0&&isPlainObject$1(meta2)){let envelope={},nextMeta={...meta2};for(let key of envelopeKeys)envelope[key]=meta2[key],delete nextMeta[key];lifted.envelope=envelope,Object.keys(nextMeta).length>0?nextParams._meta=nextMeta:delete nextParams._meta}for(let key of retryKeys)key==="inputResponses"&&(lifted.inputResponses=nextParams[key]),key==="requestState"&&(lifted.requestState=nextParams[key]),delete nextParams[key];return{message:{...message,params:nextParams},lifted}}function codecResultValidator(codec,method){let probe=codec.validateResult(method,void 0);if(!(!probe.ok&&probe.reason==="not-in-era"))return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(value){let outcome=codec.validateResult(method,value);return outcome.ok?{value:outcome.value}:{issues:[{message:outcome.reason==="invalid"?outcome.message:`not-in-era: ${method}`}]}}}}}function requestStateAccessor(value){return()=>value}function withRequestStateValue(ctx,value){return{...ctx,mcpReq:{...ctx.mcpReq,requestState:requestStateAccessor(value)}}}function setNegotiatedProtocolVersion(instance,version2){writeNegotiatedProtocolVersion(instance,version2)}function isPlainObject$1(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function mergeCapabilities(base,additional){let result={...base};for(let key in additional){let k=key,addValue=additional[k];if(addValue===void 0)continue;let baseValue=result[k];result[k]=isPlainObject$1(baseValue)&&isPlainObject$1(addValue)?{...baseValue,...addValue}:addValue}return result}function isPlainObject2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function partitionInputResponses(inputResponses){let accepted={},droppedKeys=[];if(!isPlainObject2(inputResponses))return{accepted,droppedKeys};for(let[key,entry]of Object.entries(inputResponses)){if(!isPlainObject2(entry)||"method"in entry||"result"in entry){droppedKeys.push(key);continue}accepted[key]=entry}return{accepted,droppedKeys}}function manualInputRequiredValue(decoded){return{resultType:"input_required",inputRequests:decoded.inputRequests,...decoded.requestState!==void 0&&{requestState:decoded.requestState}}}function mediaTypeEssence(header){if(header)try{return import_content_type.parse(header).type}catch{let essence=(header.split(";",1)[0]??"").trim().toLowerCase();return essence===""||header.slice(essence.length).includes(",")?void 0:essence}}function isJsonContentType(header){return header==="application/json"?!0:mediaTypeEssence(header)==="application/json"}function validateToolName(name){let warnings=[];if(name.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(name.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${name.length})`]};if(name.includes(" ")&&warnings.push("Tool name contains spaces, which may cause parsing issues"),name.includes(",")&&warnings.push("Tool name contains commas, which may cause parsing issues"),(name.startsWith("-")||name.endsWith("-"))&&warnings.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(name.startsWith(".")||name.endsWith("."))&&warnings.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!TOOL_NAME_REGEX.test(name)){let invalidChars=[...name].filter(char=>!/[A-Za-z0-9._-]/.test(char)).filter((char,index,arr)=>arr.indexOf(char)===index);return warnings.push(`Tool name contains invalid characters: ${invalidChars.map(c=>`"${c}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings}}return{isValid:!0,warnings}}function issueToolNameWarning(name,warnings){if(warnings.length>0){console.warn(`Tool name validation warning for "${name}":`);for(let warning of warnings)console.warn(` - ${warning}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function validateAndWarnToolName(name){let result=validateToolName(name);return issueToolNameWarning(name,result.warnings),result.isValid}function isZodV4Schema(v){return typeof v=="object"&&v!==null&&"_zod"in v}function looksLikeZodV3(v){return typeof v=="object"&&v!==null&&!("_zod"in v)&&"_def"in v&&typeof v._def?.typeName=="string"}function isZodRawShape(obj){if(typeof obj!="object"||obj===null||isStandardSchema(obj))return!1;let proto=Object.getPrototypeOf(obj);return proto!==Object.prototype&&proto!==null?!1:Object.values(obj).every(v=>isZodV4Schema(v))}function normalizeRawShapeSchema(schema2){if(schema2!==void 0){if(isZodRawShape(schema2))return object(schema2);if(typeof schema2=="object"&&schema2!==null&&!isStandardSchema(schema2)&&Object.values(schema2).some(v=>looksLikeZodV3(v)))throw new TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself.");if(!isStandardSchema(schema2))throw new TypeError("inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() }).");return schema2}}function fromJsonSchema(schema2,validator){let check=validator.getValidator(schema2);return{"~standard":{version:1,vendor:"mcp",jsonSchema:{input:()=>schema2,output:()=>schema2},validate:data=>{let result=check(data);return result.valid?{value:result.data}:{issues:[{message:result.errorMessage}]}}}}}var BRANDS,OAuthErrorCode,OAuthError,SdkErrorCode,SdkError,SdkHttpError,REQUIRED_CLIENT_CAPABILITIES_BY_METHOD,FIRST_MODERN_PROTOCOL_VERSION,SUPPORTED_MODERN_PROTOCOL_VERSIONS,TOOL_RESULT_FOREIGN_FAMILY_KEYS,memo$1,REF_REWRITE_DATA_POSITION_KEYS,REF_REWRITE_NAME_MAP_KEYS,requestMethodKeys$1,notificationMethodKeys$1,resultMethodKeys,maps$1,rev2025RequestMethods,rev2025NotificationMethods,NOT_IN_ERA$1,rev2025Codec,memo,CACHEABLE_RESULT_METHODS,RESULT_CACHE_HINT_FALLBACK,ProtocolErrorCode,ProtocolError,ResourceNotFoundError,UrlElicitationRequiredError,UnsupportedProtocolVersionError,MissingRequiredClientCapabilityError,DEFAULT_CACHE_TTL_MS,DEFAULT_CACHE_SCOPE,EXTENDED_RESULT_TYPE_METHODS,INPUT_REQUEST_METHODS_2026,maps,requestMethodKeys,notificationMethodKeys,rev2026RequestMethods,rev2026NotificationMethods,NOT_IN_ERA,REQUIRED_ENVELOPE_KEYS,rev2026Codec,wireResultSchemasMemo,MODERN_WIRE_REVISION,ALL_CODECS,schemas_exports2,isJSONRPCRequest,isJSONRPCNotification,isJSONRPCResultResponse,isJSONRPCErrorResponse,isInputRequiredResult,isInitializeRequest,MCP_PARAM_HEADER_PREFIX,X_MCP_HEADER_KEY,RFC9110_TOKEN,PERMITTED_X_MCP_HEADER_TYPES,NON_REACHABLE_SUBSCHEMA_KEYWORDS,OBJECT_VALUED_SUBSCHEMA_KEYWORDS,BASE64_SENTINEL_PREFIX,BASE64_SENTINEL_SUFFIX,BASE64_CANONICAL,CANONICAL_DECIMAL,HEADER_MISMATCH_ERROR_CODE,INBOUND_VALIDATION_LADDER,LADDER_ERROR_HTTP_STATUS,MCP_NAME_HEADER_SOURCE,warnedZodFallback,JSON_SCHEMA_CONVERSION_TARGET,DATETIME_FRACTION_DIGITS,ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS,ROOT_KEYS,PROPERTY_KEYS_BY_TYPE,SUPPORTED_STRING_FORMATS,inputRequired,REQUEST_STATE_ONLY_LEG_PACING_MS,SPEC_SCHEMA_KEYS,authSchemas,_specTypeSchemas,_isSpecType,specTypeSchemas,isSpecType,DEFAULT_REQUEST_TIMEOUT_MSEC,RESERVED_ENVELOPE_META_KEYS,RETRY_PARAMS_KEYS,NO_REQUEST_STATE,writeNegotiatedProtocolVersion,Protocol,require_content_type,import_content_type,STDIO_DEFAULT_MAX_BUFFER_SIZE,TOOL_NAME_REGEX,MAX_TEMPLATE_LENGTH,MAX_VARIABLE_LENGTH,MAX_TEMPLATE_EXPRESSIONS,MAX_REGEX_LENGTH,UriTemplate,init_src_CX2iR2pK=__esm({"../../node_modules/.pnpm/@modelcontextprotocol+server@2.0.0_patch_hash=2a5f5402571efdc40802e9603a3dd09e22588b4aacad710814c204d79568091e/node_modules/@modelcontextprotocol/server/dist/src-CX2iR2pK.mjs"(){"use strict";init_chunk_Br0eD_fh();init_dialects_DoSzNhcb();init_internal();init_v4();BRANDS=Symbol.for("mcp.sdk.errorBrands");OAuthErrorCode=(function(OAuthErrorCode$1){return OAuthErrorCode$1.InvalidRequest="invalid_request",OAuthErrorCode$1.InvalidClient="invalid_client",OAuthErrorCode$1.InvalidGrant="invalid_grant",OAuthErrorCode$1.UnauthorizedClient="unauthorized_client",OAuthErrorCode$1.UnsupportedGrantType="unsupported_grant_type",OAuthErrorCode$1.InvalidScope="invalid_scope",OAuthErrorCode$1.AccessDenied="access_denied",OAuthErrorCode$1.ServerError="server_error",OAuthErrorCode$1.TemporarilyUnavailable="temporarily_unavailable",OAuthErrorCode$1.UnsupportedResponseType="unsupported_response_type",OAuthErrorCode$1.UnsupportedTokenType="unsupported_token_type",OAuthErrorCode$1.InvalidToken="invalid_token",OAuthErrorCode$1.MethodNotAllowed="method_not_allowed",OAuthErrorCode$1.TooManyRequests="too_many_requests",OAuthErrorCode$1.InvalidClientMetadata="invalid_client_metadata",OAuthErrorCode$1.InvalidRedirectUri="invalid_redirect_uri",OAuthErrorCode$1.InsufficientScope="insufficient_scope",OAuthErrorCode$1.InvalidTarget="invalid_target",OAuthErrorCode$1})({}),OAuthError=class OAuthError2 extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](value){return brandedHasInstance(this,value)}static isInstance(value){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return brandedHasInstance(this,value)}constructor(code,message,errorUri){super(message),this.code=code,this.errorUri=errorUri,this.name="OAuthError",stampErrorBrands(this,new.target)}toResponseObject(){let response={error:this.code,error_description:this.message};return this.errorUri&&(response.error_uri=this.errorUri),response}static fromResponse(response){return new OAuthError2(response.error,response.error_description??response.error,response.error_uri)}},SdkErrorCode=(function(SdkErrorCode$1){return SdkErrorCode$1.NotConnected="NOT_CONNECTED",SdkErrorCode$1.AlreadyConnected="ALREADY_CONNECTED",SdkErrorCode$1.NotInitialized="NOT_INITIALIZED",SdkErrorCode$1.CapabilityNotSupported="CAPABILITY_NOT_SUPPORTED",SdkErrorCode$1.RequestTimeout="REQUEST_TIMEOUT",SdkErrorCode$1.ConnectionClosed="CONNECTION_CLOSED",SdkErrorCode$1.SendFailed="SEND_FAILED",SdkErrorCode$1.InvalidResult="INVALID_RESULT",SdkErrorCode$1.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",SdkErrorCode$1.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",SdkErrorCode$1.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",SdkErrorCode$1.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",SdkErrorCode$1.EraNegotiationFailed="ERA_NEGOTIATION_FAILED",SdkErrorCode$1.ClientHttpNotImplemented="CLIENT_HTTP_NOT_IMPLEMENTED",SdkErrorCode$1.ClientHttpAuthentication="CLIENT_HTTP_AUTHENTICATION",SdkErrorCode$1.ClientHttpForbidden="CLIENT_HTTP_FORBIDDEN",SdkErrorCode$1.ClientHttpUnexpectedContent="CLIENT_HTTP_UNEXPECTED_CONTENT",SdkErrorCode$1.ClientHttpFailedToOpenStream="CLIENT_HTTP_FAILED_TO_OPEN_STREAM",SdkErrorCode$1.ClientHttpFailedToTerminateSession="CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION",SdkErrorCode$1})({}),SdkError=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](value){return brandedHasInstance(this,value)}static isInstance(value){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return brandedHasInstance(this,value)}constructor(code,message,data){super(message),this.code=code,this.data=data,this.name="SdkError",stampErrorBrands(this,new.target)}},SdkHttpError=class extends SdkError{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor(code,message,data){super(code,message,data),this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}},REQUIRED_CLIENT_CAPABILITIES_BY_METHOD={};FIRST_MODERN_PROTOCOL_VERSION="2026-07-28",SUPPORTED_MODERN_PROTOCOL_VERSIONS=[FIRST_MODERN_PROTOCOL_VERSION];TOOL_RESULT_FOREIGN_FAMILY_KEYS=["task","inputRequests","requestState"];REF_REWRITE_DATA_POSITION_KEYS=new Set(["const","enum","default","examples"]),REF_REWRITE_NAME_MAP_KEYS=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);requestMethodKeys$1={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},notificationMethodKeys$1={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},resultMethodKeys={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null};rev2025RequestMethods=Object.keys(requestMethodKeys$1),rev2025NotificationMethods=Object.keys(notificationMethodKeys$1);NOT_IN_ERA$1={ok:!1,reason:"not-in-era"};rev2025Codec={era:"2025-11-25",hasRequestMethod:hasRequestMethod2025,hasNotificationMethod:hasNotificationMethod2025,validateRequest:(method,raw2)=>triState$1(getRequestSchema(method),raw2),validateResult:(method,raw2)=>triState$1(getResultSchema(method),raw2),validateNotification:(method,raw2)=>triState$1(getNotificationSchema(method),raw2),hasInputRequestMethod:()=>!1,validateInputRequest:()=>NOT_IN_ERA$1,validateInputResponse:()=>NOT_IN_ERA$1,samplingResultVariant:((hasTools,raw2)=>{let s=buildSchemas2025();return triState$1(hasTools?s.CreateMessageResultWithToolsSchema:s.CreateMessageResultSchema,raw2)}),outboundEnvelope:_material=>{},validateEnvelopeMeta:_meta=>[],projectCallToolResult(result,advertisedOutputSchema){let withText=appendTextFallbackForNonObject(result),sc=withText.structuredContent;if(sc===void 0)return withText;let valueIsNonObject=typeof sc!="object"||sc===null||Array.isArray(sc),schemaWrapped=advertisedOutputSchema!==void 0&&isNonObjectJsonSchemaRoot(advertisedOutputSchema);return!valueIsNonObject&&!schemaWrapped?withText:{...withText,structuredContent:{result:sc}}},decodeResult(_method,raw2){if(isPlainObject$6(raw2)&&"resultType"in raw2){let stripped={...raw2};return delete stripped.resultType,{kind:"complete",result:stripped}}return{kind:"complete",result:raw2}},encodeResult(method,result){if(method!=="tools/list")return result;let tools=result.tools;return!Array.isArray(tools)||!tools.some(t=>toolNeedsLegacyWrap(t))?result:{...result,tools:tools.map(t=>toolNeedsLegacyWrap(t)?{...t,outputSchema:wrapOutputSchemaForLegacy(t.outputSchema)}:t)}},encodeErrorCode:code=>code===-32002?-32602:code,checkInboundEnvelope:_material=>{}};CACHEABLE_RESULT_METHODS=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];RESULT_CACHE_HINT_FALLBACK=Symbol("modelcontextprotocol.resultCacheHintFallback");ProtocolErrorCode=(function(ProtocolErrorCode$1){return ProtocolErrorCode$1[ProtocolErrorCode$1.ParseError=-32700]="ParseError",ProtocolErrorCode$1[ProtocolErrorCode$1.InvalidRequest=-32600]="InvalidRequest",ProtocolErrorCode$1[ProtocolErrorCode$1.MethodNotFound=-32601]="MethodNotFound",ProtocolErrorCode$1[ProtocolErrorCode$1.InvalidParams=-32602]="InvalidParams",ProtocolErrorCode$1[ProtocolErrorCode$1.InternalError=-32603]="InternalError",ProtocolErrorCode$1[ProtocolErrorCode$1.ResourceNotFound=-32002]="ResourceNotFound",ProtocolErrorCode$1[ProtocolErrorCode$1.MissingRequiredClientCapability=-32021]="MissingRequiredClientCapability",ProtocolErrorCode$1[ProtocolErrorCode$1.UnsupportedProtocolVersion=-32022]="UnsupportedProtocolVersion",ProtocolErrorCode$1[ProtocolErrorCode$1.UrlElicitationRequired=-32042]="UrlElicitationRequired",ProtocolErrorCode$1})({}),ProtocolError=class ProtocolError2 extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](value){return brandedHasInstance(this,value)}static isInstance(value){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return brandedHasInstance(this,value)}constructor(code,message,data){super(message),this.code=code,this.data=data,this.name="ProtocolError",stampErrorBrands(this,new.target)}static fromError(code,message,data){if(code===ProtocolErrorCode.UrlElicitationRequired&&data){let errorData=data;if(errorData.elicitations)return new UrlElicitationRequiredError(errorData.elicitations,message)}if(code===ProtocolErrorCode.UnsupportedProtocolVersion&&data){let errorData=data;if(Array.isArray(errorData.supported)&&typeof errorData.requested=="string")return new UnsupportedProtocolVersionError({supported:errorData.supported,requested:errorData.requested},message)}if(code===ProtocolErrorCode.InvalidParams||code===ProtocolErrorCode.ResourceNotFound){let errorData=data;if(typeof errorData?.uri=="string"&&(code===ProtocolErrorCode.ResourceNotFound||Object.keys(errorData).length===1))return new ResourceNotFoundError(errorData.uri,message)}if(code===ProtocolErrorCode.MissingRequiredClientCapability&&data){let errorData=data;if(errorData.requiredCapabilities!==null&&typeof errorData.requiredCapabilities=="object"&&!Array.isArray(errorData.requiredCapabilities))return new MissingRequiredClientCapabilityError({requiredCapabilities:errorData.requiredCapabilities},message)}return new ProtocolError2(code,message,data)}},ResourceNotFoundError=class extends ProtocolError{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(uri,message=`Resource not found: ${uri}`){super(ProtocolErrorCode.InvalidParams,message,{uri})}get uri(){return this.data.uri}},UrlElicitationRequiredError=class extends ProtocolError{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(elicitations,message=`URL elicitation${elicitations.length>1?"s":""} required`){super(ProtocolErrorCode.UrlElicitationRequired,message,{elicitations})}get elicitations(){return this.data?.elicitations??[]}},UnsupportedProtocolVersionError=class extends ProtocolError{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(data,message=`Unsupported protocol version: ${data.requested}`){super(ProtocolErrorCode.UnsupportedProtocolVersion,message,data)}get supported(){return this.data.supported}get requested(){return this.data.requested}},MissingRequiredClientCapabilityError=class extends ProtocolError{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"})}constructor(data,message=`Missing required client capabilities: ${Object.keys(data.requiredCapabilities).join(", ")}`){super(ProtocolErrorCode.MissingRequiredClientCapability,message,data)}get requiredCapabilities(){return this.data.requiredCapabilities}},DEFAULT_CACHE_TTL_MS=0,DEFAULT_CACHE_SCOPE="private",EXTENDED_RESULT_TYPE_METHODS=["tools/call","prompts/get","resources/read"];INPUT_REQUEST_METHODS_2026=["elicitation/create","sampling/createMessage","roots/list"];requestMethodKeys={"tools/call":null,"tools/list":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"completion/complete":null,"server/discover":null,"subscriptions/listen":null},notificationMethodKeys={"notifications/cancelled":null,"notifications/progress":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/subscriptions/acknowledged":null};rev2026RequestMethods=Object.keys(requestMethodKeys),rev2026NotificationMethods=Object.keys(notificationMethodKeys);NOT_IN_ERA={ok:!1,reason:"not-in-era"},REQUIRED_ENVELOPE_KEYS=[PROTOCOL_VERSION_META_KEY,CLIENT_CAPABILITIES_META_KEY];rev2026Codec={era:"2026-07-28",hasRequestMethod:hasRequestMethod2026,hasNotificationMethod:hasNotificationMethod2026,hasInputRequestMethod:method=>getInputRequestSchema2026(method)!==void 0,validateRequest:(method,raw2)=>triState(getRequestSchema2026(method),raw2),validateResult:(method,raw2)=>triState(getResultSchema2026(method),raw2),validateNotification:(method,raw2)=>triState(getNotificationSchema2026(method),raw2),validateInputRequest:(method,raw2)=>triState(getInputRequestSchema2026(method),raw2),validateInputResponse:(method,raw2)=>triState(getInputResponseSchema2026(method),raw2),samplingResultVariant:()=>NOT_IN_ERA,outboundEnvelope(material){return{[PROTOCOL_VERSION_META_KEY]:material.protocolVersion,[CLIENT_INFO_META_KEY]:material.clientInfo,[CLIENT_CAPABILITIES_META_KEY]:material.clientCapabilities,...material.logLevel!==void 0&&{[LOG_LEVEL_META_KEY]:material.logLevel}}},validateEnvelopeMeta(meta2){let issues=[];for(let key of REQUIRED_ENVELOPE_KEYS)key in meta2||issues.push({key,problem:"missing"});let parsed=buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(meta2);if(!parsed.success)for(let issue2 of parsed.error.issues){let path=issue2.path.map(String),key=path.length>0?path.join("."):"_meta";path.length===1&&issues.some(existing=>existing.key===key&&existing.problem==="missing")||issues.push({key,problem:issue2.message})}return issues},projectCallToolResult:result=>appendTextFallbackForNonObject(result),inputRequestSchema:getInputRequestSchema2026,decodeResult(method,raw2){if(!isPlainObject$4(raw2))return{kind:"invalid",error:new SdkError(SdkErrorCode.InvalidResult,`Invalid result for ${method}: not an object`,{method})};let rawResultType=raw2.resultType;if(rawResultType===void 0)return{kind:"invalid",error:new SdkError(SdkErrorCode.InvalidResult,`Invalid result for ${method}: missing required resultType \u2014 servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,{method,violation:"missing-resultType"})};if(typeof rawResultType!="string")return{kind:"invalid",error:new SdkError(SdkErrorCode.InvalidResult,`Invalid result for ${method}: non-string resultType`,{method,resultType:rawResultType})};if(rawResultType==="input_required"){let rawInputRequests=raw2.inputRequests,inputRequests=isPlainObject$4(rawInputRequests)?rawInputRequests:{},requestState=raw2.requestState;return Object.keys(inputRequests).length===0&&typeof requestState!="string"?{kind:"invalid",error:new SdkError(SdkErrorCode.InvalidResult,`Invalid result for ${method}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method,violation:"input-required-missing-both"})}:{kind:"input_required",inputRequests,...typeof requestState=="string"&&{requestState}}}if(rawResultType!=="complete")return{kind:"invalid",error:new SdkError(SdkErrorCode.UnsupportedResultType,`Unsupported result type '${rawResultType}' for ${method}`,{resultType:rawResultType,method})};let wireResultSchemas=getWireResultSchemas(),wireSchema=Object.hasOwn(wireResultSchemas,method)?wireResultSchemas[method]:void 0;if(wireSchema!==void 0){let parsed=wireSchema.safeParse(raw2);if(!parsed.success)return{kind:"invalid",error:new SdkError(SdkErrorCode.InvalidResult,`Invalid result for ${method}: ${parsed.error}`,{method})}}let lifted={...raw2};return delete lifted.resultType,{kind:"complete",result:lifted}},encodeResult(method,result,serverInfo){return stampServerInfoMeta(fillCacheFields(method,stampResultType(method,enforceDeletedFields(method,result))),serverInfo)},encodeErrorCode:code=>code===-32002?-32602:code,checkInboundEnvelope(material){if(material.envelope===void 0)return"Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)";let parsed=buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(material.envelope);if(!parsed.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${parsed.error.issues.map(issue2=>issue2.message).join("; ")}`}};MODERN_WIRE_REVISION="2026-07-28";ALL_CODECS=[rev2025Codec,rev2026Codec];schemas_exports2=__exportAll({AnnotationsSchema:()=>AnnotationsSchema,AudioContentSchema:()=>AudioContentSchema,BaseMetadataSchema:()=>BaseMetadataSchema,BaseRequestParamsSchema:()=>BaseRequestParamsSchema,BlobResourceContentsSchema:()=>BlobResourceContentsSchema,BooleanSchemaSchema:()=>BooleanSchemaSchema,CallToolRequestParamsSchema:()=>CallToolRequestParamsSchema,CallToolRequestSchema:()=>CallToolRequestSchema,CallToolResultSchema:()=>CallToolResultSchema,CancelTaskRequestSchema:()=>CancelTaskRequestSchema,CancelTaskResultSchema:()=>CancelTaskResultSchema,CancelledNotificationParamsSchema:()=>CancelledNotificationParamsSchema,CancelledNotificationSchema:()=>CancelledNotificationSchema,ClientCapabilitiesSchema:()=>ClientCapabilitiesSchema,ClientNotificationSchema:()=>ClientNotificationSchema,ClientRequestSchema:()=>ClientRequestSchema,ClientResultSchema:()=>ClientResultSchema,ClientTasksCapabilitySchema:()=>ClientTasksCapabilitySchema,CompatibilityCallToolResultSchema:()=>CompatibilityCallToolResultSchema,CompleteRequestParamsSchema:()=>CompleteRequestParamsSchema,CompleteRequestSchema:()=>CompleteRequestSchema,CompleteResultSchema:()=>CompleteResultSchema,ContentBlockSchema:()=>ContentBlockSchema,CreateMessageRequestParamsSchema:()=>CreateMessageRequestParamsSchema,CreateMessageRequestSchema:()=>CreateMessageRequestSchema,CreateMessageResultSchema:()=>CreateMessageResultSchema,CreateMessageResultWithToolsSchema:()=>CreateMessageResultWithToolsSchema,CreateTaskResultSchema:()=>CreateTaskResultSchema,CursorSchema:()=>CursorSchema,DiscoverRequestSchema:()=>DiscoverRequestSchema,DiscoverResultSchema:()=>DiscoverResultSchema,ElicitRequestFormParamsSchema:()=>ElicitRequestFormParamsSchema,ElicitRequestParamsSchema:()=>ElicitRequestParamsSchema,ElicitRequestSchema:()=>ElicitRequestSchema,ElicitRequestURLParamsSchema:()=>ElicitRequestURLParamsSchema,ElicitResultSchema:()=>ElicitResultSchema,ElicitationCompleteNotificationParamsSchema:()=>ElicitationCompleteNotificationParamsSchema,ElicitationCompleteNotificationSchema:()=>ElicitationCompleteNotificationSchema,EmbeddedResourceSchema:()=>EmbeddedResourceSchema,EmptyResultSchema:()=>EmptyResultSchema,EnumSchemaSchema:()=>EnumSchemaSchema,GetPromptRequestParamsSchema:()=>GetPromptRequestParamsSchema,GetPromptRequestSchema:()=>GetPromptRequestSchema,GetPromptResultSchema:()=>GetPromptResultSchema,GetTaskPayloadRequestSchema:()=>GetTaskPayloadRequestSchema,GetTaskPayloadResultSchema:()=>GetTaskPayloadResultSchema,GetTaskRequestSchema:()=>GetTaskRequestSchema,GetTaskResultSchema:()=>GetTaskResultSchema,IconSchema:()=>IconSchema,IconsSchema:()=>IconsSchema,ImageContentSchema:()=>ImageContentSchema,ImplementationSchema:()=>ImplementationSchema,InitializeRequestParamsSchema:()=>InitializeRequestParamsSchema,InitializeRequestSchema:()=>InitializeRequestSchema,InitializeResultSchema:()=>InitializeResultSchema,InitializedNotificationSchema:()=>InitializedNotificationSchema,JSONArraySchema:()=>JSONArraySchema,JSONObjectSchema:()=>JSONObjectSchema,JSONRPCErrorResponseSchema:()=>JSONRPCErrorResponseSchema,JSONRPCMessageSchema:()=>JSONRPCMessageSchema,JSONRPCNotificationSchema:()=>JSONRPCNotificationSchema,JSONRPCRequestSchema:()=>JSONRPCRequestSchema,JSONRPCResponseSchema:()=>JSONRPCResponseSchema,JSONRPCResultResponseSchema:()=>JSONRPCResultResponseSchema,JSONValueSchema:()=>JSONValueSchema,LegacyTitledEnumSchemaSchema:()=>LegacyTitledEnumSchemaSchema,ListChangedOptionsBaseSchema:()=>ListChangedOptionsBaseSchema,ListPromptsRequestSchema:()=>ListPromptsRequestSchema,ListPromptsResultSchema:()=>ListPromptsResultSchema,ListResourceTemplatesRequestSchema:()=>ListResourceTemplatesRequestSchema,ListResourceTemplatesResultSchema:()=>ListResourceTemplatesResultSchema,ListResourcesRequestSchema:()=>ListResourcesRequestSchema,ListResourcesResultSchema:()=>ListResourcesResultSchema,ListRootsRequestSchema:()=>ListRootsRequestSchema,ListRootsResultSchema:()=>ListRootsResultSchema,ListTasksRequestSchema:()=>ListTasksRequestSchema,ListTasksResultSchema:()=>ListTasksResultSchema,ListToolsRequestSchema:()=>ListToolsRequestSchema,ListToolsResultSchema:()=>ListToolsResultSchema,LoggingLevelSchema:()=>LoggingLevelSchema,LoggingMessageNotificationParamsSchema:()=>LoggingMessageNotificationParamsSchema,LoggingMessageNotificationSchema:()=>LoggingMessageNotificationSchema,ModelHintSchema:()=>ModelHintSchema,ModelPreferencesSchema:()=>ModelPreferencesSchema,MultiSelectEnumSchemaSchema:()=>MultiSelectEnumSchemaSchema,NotificationSchema:()=>NotificationSchema,NotificationsParamsSchema:()=>NotificationsParamsSchema,NumberSchemaSchema:()=>NumberSchemaSchema,PaginatedRequestParamsSchema:()=>PaginatedRequestParamsSchema,PaginatedRequestSchema:()=>PaginatedRequestSchema,PaginatedResultSchema:()=>PaginatedResultSchema,PingRequestSchema:()=>PingRequestSchema,PrimitiveSchemaDefinitionSchema:()=>PrimitiveSchemaDefinitionSchema,ProgressNotificationParamsSchema:()=>ProgressNotificationParamsSchema,ProgressNotificationSchema:()=>ProgressNotificationSchema,ProgressSchema:()=>ProgressSchema,ProgressTokenSchema:()=>ProgressTokenSchema,PromptArgumentSchema:()=>PromptArgumentSchema,PromptListChangedNotificationSchema:()=>PromptListChangedNotificationSchema,PromptMessageSchema:()=>PromptMessageSchema,PromptReferenceSchema:()=>PromptReferenceSchema,PromptSchema:()=>PromptSchema,ReadResourceRequestParamsSchema:()=>ReadResourceRequestParamsSchema,ReadResourceRequestSchema:()=>ReadResourceRequestSchema,ReadResourceResultSchema:()=>ReadResourceResultSchema,RelatedTaskMetadataSchema:()=>RelatedTaskMetadataSchema,RequestIdSchema:()=>RequestIdSchema,RequestMetaSchema:()=>RequestMetaSchema,RequestSchema:()=>RequestSchema,ResourceContentsSchema:()=>ResourceContentsSchema,ResourceLinkSchema:()=>ResourceLinkSchema,ResourceListChangedNotificationSchema:()=>ResourceListChangedNotificationSchema,ResourceRequestParamsSchema:()=>ResourceRequestParamsSchema,ResourceSchema:()=>ResourceSchema,ResourceTemplateReferenceSchema:()=>ResourceTemplateReferenceSchema,ResourceTemplateSchema:()=>ResourceTemplateSchema,ResourceUpdatedNotificationParamsSchema:()=>ResourceUpdatedNotificationParamsSchema,ResourceUpdatedNotificationSchema:()=>ResourceUpdatedNotificationSchema,ResultMetaObjectSchema:()=>ResultMetaObjectSchema,ResultSchema:()=>ResultSchema,RoleSchema:()=>RoleSchema,RootSchema:()=>RootSchema,RootsListChangedNotificationSchema:()=>RootsListChangedNotificationSchema,SamplingContentSchema:()=>SamplingContentSchema,SamplingMessageContentBlockSchema:()=>SamplingMessageContentBlockSchema,SamplingMessageSchema:()=>SamplingMessageSchema,ServerCapabilitiesSchema:()=>ServerCapabilitiesSchema,ServerNotificationSchema:()=>ServerNotificationSchema,ServerRequestSchema:()=>ServerRequestSchema,ServerResultSchema:()=>ServerResultSchema,ServerTasksCapabilitySchema:()=>ServerTasksCapabilitySchema,SetLevelRequestParamsSchema:()=>SetLevelRequestParamsSchema,SetLevelRequestSchema:()=>SetLevelRequestSchema,SingleSelectEnumSchemaSchema:()=>SingleSelectEnumSchemaSchema,StringSchemaSchema:()=>StringSchemaSchema,SubscribeRequestParamsSchema:()=>SubscribeRequestParamsSchema,SubscribeRequestSchema:()=>SubscribeRequestSchema,SubscriptionFilterSchema:()=>SubscriptionFilterSchema,SubscriptionsAcknowledgedNotificationParamsSchema:()=>SubscriptionsAcknowledgedNotificationParamsSchema,SubscriptionsAcknowledgedNotificationSchema:()=>SubscriptionsAcknowledgedNotificationSchema,SubscriptionsListenRequestParamsSchema:()=>SubscriptionsListenRequestParamsSchema,SubscriptionsListenRequestSchema:()=>SubscriptionsListenRequestSchema,SubscriptionsListenResultMetaSchema:()=>SubscriptionsListenResultMetaSchema,SubscriptionsListenResultSchema:()=>SubscriptionsListenResultSchema,TaskAugmentedRequestParamsSchema:()=>TaskAugmentedRequestParamsSchema,TaskCreationParamsSchema:()=>TaskCreationParamsSchema,TaskMetadataSchema:()=>TaskMetadataSchema,TaskSchema:()=>TaskSchema,TaskStatusNotificationParamsSchema:()=>TaskStatusNotificationParamsSchema,TaskStatusNotificationSchema:()=>TaskStatusNotificationSchema,TaskStatusSchema:()=>TaskStatusSchema,TextContentSchema:()=>TextContentSchema,TextResourceContentsSchema:()=>TextResourceContentsSchema,TitledMultiSelectEnumSchemaSchema:()=>TitledMultiSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema:()=>TitledSingleSelectEnumSchemaSchema,ToolAnnotationsSchema:()=>ToolAnnotationsSchema,ToolChoiceSchema:()=>ToolChoiceSchema,ToolExecutionSchema:()=>ToolExecutionSchema,ToolListChangedNotificationSchema:()=>ToolListChangedNotificationSchema,ToolResultContentSchema:()=>ToolResultContentSchema,ToolSchema:()=>ToolSchema,ToolUseContentSchema:()=>ToolUseContentSchema,UnsubscribeRequestParamsSchema:()=>UnsubscribeRequestParamsSchema,UnsubscribeRequestSchema:()=>UnsubscribeRequestSchema,UntitledMultiSelectEnumSchemaSchema:()=>UntitledMultiSelectEnumSchemaSchema,UntitledSingleSelectEnumSchemaSchema:()=>UntitledSingleSelectEnumSchemaSchema}),isJSONRPCRequest=value=>JSONRPCRequestSchema.safeParse(value).success,isJSONRPCNotification=value=>JSONRPCNotificationSchema.safeParse(value).success,isJSONRPCResultResponse=value=>typeof value=="object"&&value!==null&&Object.hasOwn(value,"result")&&JSONRPCResultResponseSchema.safeParse(value).success,isJSONRPCErrorResponse=value=>typeof value=="object"&&value!==null&&Object.hasOwn(value,"error")&&JSONRPCErrorResponseSchema.safeParse(value).success,isInputRequiredResult=value=>typeof value=="object"&&value!==null&&!Array.isArray(value)&&value.resultType==="input_required",isInitializeRequest=value=>InitializeRequestSchema.safeParse(value).success;MCP_PARAM_HEADER_PREFIX="Mcp-Param-",X_MCP_HEADER_KEY="x-mcp-header",RFC9110_TOKEN=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,PERMITTED_X_MCP_HEADER_TYPES=new Set(["string","integer","boolean","number"]);NON_REACHABLE_SUBSCHEMA_KEYWORDS=["items","prefixItems","contains","additionalProperties","unevaluatedProperties","unevaluatedItems","propertyNames","patternProperties","dependentSchemas","oneOf","anyOf","allOf","not","if","then","else","$defs","definitions"],OBJECT_VALUED_SUBSCHEMA_KEYWORDS=new Set(["patternProperties","dependentSchemas","$defs","definitions"]);BASE64_SENTINEL_PREFIX="=?base64?",BASE64_SENTINEL_SUFFIX="?=",BASE64_CANONICAL=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,CANONICAL_DECIMAL=/^-?\d+(\.\d+)?$/;HEADER_MISMATCH_ERROR_CODE=-32020,INBOUND_VALIDATION_LADDER=[{rung:"http-method",order:1,evaluatedAt:"edge",codes:[-32e3],conformance:[],rationale:"The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read."},{rung:"jsonrpc-shape",order:2,evaluatedAt:"edge",codes:[ProtocolErrorCode.InvalidRequest],conformance:["server-stateless"],rationale:"The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic."},{rung:"era-classification",order:3,evaluatedAt:"edge",codes:[HEADER_MISMATCH_ERROR_CODE,ProtocolErrorCode.UnsupportedProtocolVersion],conformance:["server-stateless","http-header-validation","http-custom-header-server-validation"],rationale:"Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions."},{rung:"envelope",order:4,evaluatedAt:"edge",codes:[ProtocolErrorCode.InvalidParams],conformance:["server-stateless"],rationale:"A present envelope claim with a malformed envelope \u2014 and a missing envelope on a request whose protocol-version header names a modern revision \u2014 is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400."},{rung:"method-registry",order:5,evaluatedAt:"dispatch",codes:[ProtocolErrorCode.MethodNotFound],conformance:["server-stateless"],rationale:"Method existence outranks parameter validity: a method absent from the negotiated revision\u2019s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at."},{rung:"request-params",order:6,evaluatedAt:"dispatch",codes:[ProtocolErrorCode.InvalidParams],conformance:[],rationale:"Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table."},{rung:"standard-header-validation",order:7,evaluatedAt:"pre-dispatch",codes:[HEADER_MISMATCH_ERROR_CODE],conformance:["http-header-validation"],rationale:"SEP-2243 standard `Mcp-Method` / `Mcp-Name` headers \u2014 presence, sentinel decoding, and `Mcp-Name` \u2194 body cross-check \u2014 are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The classifier\u2019s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5\u20136) are consulted."},{rung:"client-capabilities",order:8,evaluatedAt:"pre-dispatch",codes:[ProtocolErrorCode.MissingRequiredClientCapability],conformance:["server-stateless"],rationale:"The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced \u2014 pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable."},{rung:"param-header-validation",order:9,evaluatedAt:"pre-dispatch",codes:[HEADER_MISMATCH_ERROR_CODE],conformance:["http-custom-header-server-validation"],rationale:"SEP-2243 `Mcp-Param-*` headers are validated against the named tool\u2019s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung."}],LADDER_ERROR_HTTP_STATUS={[ProtocolErrorCode.ParseError]:400,[ProtocolErrorCode.InvalidRequest]:400,[ProtocolErrorCode.MethodNotFound]:404,[ProtocolErrorCode.UnsupportedProtocolVersion]:400,[ProtocolErrorCode.MissingRequiredClientCapability]:400,[HEADER_MISMATCH_ERROR_CODE]:400};MCP_NAME_HEADER_SOURCE={"tools/call":"name","prompts/get":"name","resources/read":"uri"};warnedZodFallback=!1,JSON_SCHEMA_CONVERSION_TARGET="draft-2020-12";DATETIME_FRACTION_DIGITS=/\\\.\\d\{(\d+)\}/;ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);ROOT_KEYS=new Set(["$schema",...Object.keys(ElicitRequestFormParamsSchema.shape.requestedSchema.shape)]),PROPERTY_KEYS_BY_TYPE={string:shapeKeys([StringSchemaSchema,UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema,LegacyTitledEnumSchemaSchema]),number:shapeKeys([NumberSchemaSchema]),integer:shapeKeys([NumberSchemaSchema]),boolean:shapeKeys([BooleanSchemaSchema]),array:shapeKeys([UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema])},SUPPORTED_STRING_FORMATS=new Set(StringSchemaSchema.shape.format.unwrap().options);inputRequired=Object.assign(buildInputRequired,{elicit(params){try{return{method:"elicitation/create",params:normalizeElicitInputParams(params)}}catch(error3){throw error3 instanceof ProtocolError?new TypeError(error3.message,{cause:error3}):error3}},elicitUrl(params){return{method:"elicitation/create",params:{...params,mode:"url"}}},createMessage(params){return{method:"sampling/createMessage",params}},listRoots(){return{method:"roots/list"}}});REQUEST_STATE_ONLY_LEG_PACING_MS=250;SPEC_SCHEMA_KEYS=["AnnotationsSchema","AudioContentSchema","BaseMetadataSchema","BlobResourceContentsSchema","BooleanSchemaSchema","CallToolRequestSchema","CallToolRequestParamsSchema","CallToolResultSchema","CancelledNotificationSchema","CancelledNotificationParamsSchema","CancelTaskRequestSchema","CancelTaskResultSchema","ClientCapabilitiesSchema","ClientNotificationSchema","ClientRequestSchema","ClientResultSchema","CompatibilityCallToolResultSchema","CompleteRequestSchema","CompleteRequestParamsSchema","CompleteResultSchema","ContentBlockSchema","CreateMessageRequestSchema","CreateMessageRequestParamsSchema","CreateMessageResultSchema","CreateMessageResultWithToolsSchema","CreateTaskResultSchema","CursorSchema","DiscoverRequestSchema","DiscoverResultSchema","ElicitationCompleteNotificationSchema","ElicitationCompleteNotificationParamsSchema","ElicitRequestSchema","ElicitRequestFormParamsSchema","ElicitRequestParamsSchema","ElicitRequestURLParamsSchema","ElicitResultSchema","EmbeddedResourceSchema","EmptyResultSchema","EnumSchemaSchema","GetPromptRequestSchema","GetPromptRequestParamsSchema","GetPromptResultSchema","GetTaskPayloadRequestSchema","GetTaskPayloadResultSchema","GetTaskRequestSchema","GetTaskResultSchema","IconSchema","IconsSchema","ImageContentSchema","ImplementationSchema","InitializedNotificationSchema","InitializeRequestSchema","InitializeRequestParamsSchema","InitializeResultSchema","JSONArraySchema","JSONObjectSchema","JSONRPCErrorResponseSchema","JSONRPCMessageSchema","JSONRPCNotificationSchema","JSONRPCRequestSchema","JSONRPCResponseSchema","JSONRPCResultResponseSchema","JSONValueSchema","LegacyTitledEnumSchemaSchema","ListPromptsRequestSchema","ListPromptsResultSchema","ListResourcesRequestSchema","ListResourcesResultSchema","ListResourceTemplatesRequestSchema","ListResourceTemplatesResultSchema","ListRootsRequestSchema","ListRootsResultSchema","ListTasksRequestSchema","ListTasksResultSchema","ListToolsRequestSchema","ListToolsResultSchema","LoggingLevelSchema","LoggingMessageNotificationSchema","LoggingMessageNotificationParamsSchema","ModelHintSchema","ModelPreferencesSchema","MultiSelectEnumSchemaSchema","NotificationSchema","NumberSchemaSchema","PaginatedRequestSchema","PaginatedRequestParamsSchema","PaginatedResultSchema","PingRequestSchema","PrimitiveSchemaDefinitionSchema","ProgressSchema","ProgressNotificationSchema","ProgressNotificationParamsSchema","ProgressTokenSchema","PromptSchema","PromptArgumentSchema","PromptListChangedNotificationSchema","PromptMessageSchema","PromptReferenceSchema","ReadResourceRequestSchema","ReadResourceRequestParamsSchema","ReadResourceResultSchema","RelatedTaskMetadataSchema","RequestSchema","RequestIdSchema","RequestMetaSchema","ResourceSchema","ResourceContentsSchema","ResourceLinkSchema","ResourceListChangedNotificationSchema","ResourceRequestParamsSchema","ResourceTemplateSchema","ResourceTemplateReferenceSchema","ResourceUpdatedNotificationSchema","ResourceUpdatedNotificationParamsSchema","ResultMetaObjectSchema","ResultSchema","RoleSchema","RootSchema","RootsListChangedNotificationSchema","SamplingContentSchema","SamplingMessageSchema","SamplingMessageContentBlockSchema","ServerCapabilitiesSchema","ServerNotificationSchema","ServerRequestSchema","ServerResultSchema","SetLevelRequestSchema","SetLevelRequestParamsSchema","SingleSelectEnumSchemaSchema","StringSchemaSchema","SubscribeRequestSchema","SubscribeRequestParamsSchema","SubscriptionFilterSchema","SubscriptionsAcknowledgedNotificationSchema","SubscriptionsAcknowledgedNotificationParamsSchema","SubscriptionsListenRequestSchema","SubscriptionsListenRequestParamsSchema","SubscriptionsListenResultSchema","SubscriptionsListenResultMetaSchema","TaskAugmentedRequestParamsSchema","TaskCreationParamsSchema","TaskMetadataSchema","TaskSchema","TaskStatusSchema","TaskStatusNotificationSchema","TaskStatusNotificationParamsSchema","TextContentSchema","TextResourceContentsSchema","TitledMultiSelectEnumSchemaSchema","TitledSingleSelectEnumSchemaSchema","ToolSchema","ToolAnnotationsSchema","ToolChoiceSchema","ToolExecutionSchema","ToolListChangedNotificationSchema","ToolResultContentSchema","ToolUseContentSchema","UnsubscribeRequestSchema","UnsubscribeRequestParamsSchema","UntitledMultiSelectEnumSchemaSchema","UntitledSingleSelectEnumSchemaSchema"],authSchemas={IdJagTokenExchangeResponseSchema,OAuthClientInformationFullSchema,OAuthClientInformationSchema,OAuthClientMetadataSchema,OAuthClientRegistrationErrorSchema,OAuthErrorResponseSchema,OAuthMetadataSchema,OAuthProtectedResourceMetadataSchema,OAuthTokenRevocationRequestSchema,OAuthTokensSchema,OpenIdProviderDiscoveryMetadataSchema,OpenIdProviderMetadataSchema},_specTypeSchemas={},_isSpecType={};for(let key of SPEC_SCHEMA_KEYS)register(key,schemas_exports2[key]);for(let[key,schema2]of Object.entries(authSchemas))register(key,schema2);specTypeSchemas=Object.freeze(_specTypeSchemas),isSpecType=Object.freeze(_isSpecType);DEFAULT_REQUEST_TIMEOUT_MSEC=6e4,RESERVED_ENVELOPE_META_KEYS=[PROTOCOL_VERSION_META_KEY,CLIENT_INFO_META_KEY,CLIENT_CAPABILITIES_META_KEY,LOG_LEVEL_META_KEY],RETRY_PARAMS_KEYS=["inputResponses","requestState"];NO_REQUEST_STATE=requestStateAccessor(void 0);Protocol=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{writeNegotiatedProtocolVersion=(instance,version2)=>{instance._negotiatedProtocolVersion=version2}}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(_options){this._options=_options,this._supportedProtocolVersions=_options?.supportedProtocolVersions??SUPPORTED_PROTOCOL_VERSIONS,this.setNotificationHandler("notifications/cancelled",notification=>{this._oncancel(notification)}),this.setNotificationHandler("notifications/progress",notification=>{this._onprogress(notification)}),this.setRequestHandler("ping",_request=>({}))}_shouldDropInbound(_message){}_outboundMetaEnvelope(){}_envelopeOutbound(message){let envelope=this._outboundMetaEnvelope();if(envelope===void 0)return message;let params=message.params??{};return{...message,params:{...params,_meta:{...envelope,...params._meta}}}}_resolveNonCompleteResult(decoded,flow){return Promise.reject(new SdkError(SdkErrorCode.UnsupportedResultType,`Unsupported result type '${decoded.kind}' for ${flow.request.method}`,{resultType:decoded.kind,method:flow.request.method}))}_getRequestHandler(method){return this._requestHandlers.get(method)}async _oncancel(notification){notification.params.requestId&&this._requestHandlerAbortControllers.get(notification.params.requestId)?.abort(notification.params.reason)}_setupTimeout(messageId,timeout,maxTotalTimeout,onTimeout,resetTimeoutOnProgress=!1){this._timeoutInfo.set(messageId,{timeoutId:setTimeout(onTimeout,timeout),startTime:Date.now(),timeout,maxTotalTimeout,resetTimeoutOnProgress,onTimeout})}_resetTimeout(messageId){let info=this._timeoutInfo.get(messageId);if(!info)return!1;let totalElapsed=Date.now()-info.startTime;if(info.maxTotalTimeout&&totalElapsed>=info.maxTotalTimeout)throw this._timeoutInfo.delete(messageId),new SdkError(SdkErrorCode.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:info.maxTotalTimeout,totalElapsed});return clearTimeout(info.timeoutId),info.timeoutId=setTimeout(info.onTimeout,info.timeout),!0}_cleanupTimeout(messageId){let info=this._timeoutInfo.get(messageId);info&&(clearTimeout(info.timeoutId),this._timeoutInfo.delete(messageId))}async connect(transport){this._transport=transport;let _onclose=this.transport?.onclose;this._transport.onclose=()=>{try{_onclose?.()}finally{this._onclose()}};let _onerror=this.transport?.onerror;this._transport.onerror=error3=>{_onerror?.(error3),this._onerror(error3)};let _onmessage=this._transport?.onmessage;this._transport.onmessage=(message,extra)=>{_onmessage?.(message,extra),isJSONRPCResultResponse(message)||isJSONRPCErrorResponse(message)?this._onresponse(message):isJSONRPCRequest(message)?this._onrequest(message,extra):isJSONRPCNotification(message)?this._onnotification(message,extra):this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`))},transport.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let responseHandlers=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(let info of this._timeoutInfo.values())clearTimeout(info.timeoutId);this._timeoutInfo.clear();let requestHandlerAbortControllers=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let error3=new SdkError(SdkErrorCode.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(let handler of responseHandlers.values())handler(error3);for(let controller of requestHandlerAbortControllers.values())controller.abort(error3)}}_onerror(error3){this.onerror?.(error3)}_onnotification(rawNotification,extra){let{message:notification}=liftWireOnlyMaterial(rawNotification,"notification"),codec=this._negotiatedWireCodec();if(extra?.classification===void 0&&this._shouldDropInbound(rawNotification)==="drop")return;if(extra?.classification!==void 0){let classified=classifiedWireEra(extra.classification);if(classified!==codec.era){this._onerror(new Error(`Era mismatch on inbound notification '${notification.method}': classified as ${classified} but this instance serves ${codec.era}`));return}}if(isSpecNotificationMethod(notification.method)&&!codec.hasNotificationMethod(notification.method))return;let handler=this._notificationHandlers.get(notification.method),fallback=this.fallbackNotificationHandler;handler===void 0&&fallback===void 0||Promise.resolve().then(()=>handler===void 0?fallback(notification):handler(notification,codec)).catch(error3=>this._onerror(new Error(`Uncaught error in notification handler: ${error3}`)))}_onrequest(rawRequest,extra){let{message:request,lifted}=liftWireOnlyMaterial(rawRequest,"request"),codec=this._negotiatedWireCodec();if(extra?.classification===void 0&&this._shouldDropInbound(rawRequest)==="drop"){this._onerror(new Error(`Dropped inbound request '${rawRequest.method}': not servable on this connection's protocol era`));return}let capturedTransport=this._transport,sendErrorResponse=(code,message,data)=>{let errorResponse={jsonrpc:"2.0",id:request.id,error:{code,message,...data!==void 0&&{data}}};capturedTransport?.send(errorResponse).catch(error3=>this._onerror(new Error(`Failed to send an error response: ${error3}`)))};if(extra?.classification!==void 0){let classified=classifiedWireEra(extra.classification);if(classified!==codec.era){this._onerror(new Error(`Era mismatch on inbound request '${request.method}': classified as ${classified} but this instance serves ${codec.era}`));let requested=extra.classification.revision??classified;sendErrorResponse(ProtocolErrorCode.UnsupportedProtocolVersion,`Unsupported protocol version: ${requested}`,{supported:this._supportedProtocolVersions,requested});return}}if(isSpecRequestMethod(request.method)&&!codec.hasRequestMethod(request.method)){sendErrorResponse(ProtocolErrorCode.MethodNotFound,"Method not found");return}let handler=this._requestHandlers.get(request.method)??this.fallbackRequestHandler;if(handler===void 0){sendErrorResponse(ProtocolErrorCode.MethodNotFound,"Method not found");return}let envelopeError=codec.checkInboundEnvelope(lifted);if(envelopeError!==void 0){sendErrorResponse(ProtocolErrorCode.InvalidParams,envelopeError);return}let sendNotification=(notification,options)=>this._notificationViaCodec(this._resolveOutboundCodec(notification.method),notification,{...options,relatedRequestId:request.id}),sendRequest=(r,resultSchema,options)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(r.method),r,resultSchema,{...options,relatedRequestId:request.id}),abortController=new AbortController;this._requestHandlerAbortControllers.set(request.id,abortController);let partitionedInputResponses=lifted.inputResponses===void 0?void 0:partitionInputResponses(lifted.inputResponses),baseCtx={sessionId:capturedTransport?.sessionId,mcpReq:{id:request.id,method:request.method,_meta:request.params?._meta,...lifted.envelope!==void 0&&{envelope:lifted.envelope},...partitionedInputResponses!==void 0&&{inputResponses:partitionedInputResponses.accepted},...partitionedInputResponses!==void 0&&partitionedInputResponses.droppedKeys.length>0&&{droppedInputResponseKeys:partitionedInputResponses.droppedKeys},requestState:lifted.requestState===void 0?NO_REQUEST_STATE:requestStateAccessor(lifted.requestState),signal:abortController.signal,send:((r,schemaOrOptions,maybeOptions)=>{let sendCodec=this._resolveOutboundCodec(r.method);if(this._assertOutboundRequestInEra(sendCodec,r.method),isStandardSchema(schemaOrOptions))return sendRequest(r,schemaOrOptions,maybeOptions);let validate=codecResultValidator(sendCodec,r.method);if(validate===void 0)throw new TypeError(`'${r.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return sendRequest(r,validate,schemaOrOptions)}),notify:sendNotification},http:extra?.authInfo?{authInfo:extra.authInfo}:void 0},ctx=this.buildContext(baseCtx,extra);Promise.resolve().then(()=>handler(request,ctx)).then(async result=>{if(abortController.signal.aborted)return;let encoded;try{encoded=codec.encodeResult(request.method,result,this._outboundServerInfo())}catch(error3){this._onerror(new Error(`Failed to encode result for ${request.method}: ${error3}`)),sendErrorResponse(ProtocolErrorCode.InternalError,"Internal error");return}let response={result:encoded,jsonrpc:"2.0",id:request.id};await capturedTransport?.send(response)},async error3=>{if(abortController.signal.aborted)return;let thrownCode=Number.isSafeInteger(error3.code)?error3.code:ProtocolErrorCode.InternalError,errorResponse={jsonrpc:"2.0",id:request.id,error:{code:codec.encodeErrorCode(thrownCode),message:error3.message??"Internal error",...error3.data!==void 0&&{data:error3.data}}};await capturedTransport?.send(errorResponse)}).catch(error3=>this._onerror(new Error(`Failed to send response: ${error3}`))).finally(()=>{this._requestHandlerAbortControllers.get(request.id)===abortController&&this._requestHandlerAbortControllers.delete(request.id)})}_onprogress(notification){let{progressToken,...params}=notification.params,messageId=Number(progressToken),handler=this._progressHandlers.get(messageId);if(!handler){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));return}let responseHandler=this._responseHandlers.get(messageId),timeoutInfo=this._timeoutInfo.get(messageId);if(timeoutInfo&&responseHandler&&timeoutInfo.resetTimeoutOnProgress)try{this._resetTimeout(messageId)}catch(error3){this._responseHandlers.delete(messageId),this._progressHandlers.delete(messageId),this._cleanupTimeout(messageId),responseHandler(error3);return}handler(params)}_onresponse(response){let messageId=Number(response.id),handler=this._responseHandlers.get(messageId);if(handler===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));return}this._responseHandlers.delete(messageId),this._cleanupTimeout(messageId),this._progressHandlers.delete(messageId),isJSONRPCResultResponse(response)?handler(response):handler(ProtocolError.fromError(response.error.code,response.error.message,response.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(request,schemaOrOptions,maybeOptions){let codec=this._resolveOutboundCodec(request.method);if(this._assertOutboundRequestInEra(codec,request.method),isStandardSchema(schemaOrOptions))return this._requestWithSchemaViaCodec(codec,request,schemaOrOptions,maybeOptions);let validate=codecResultValidator(codec,request.method);if(validate===void 0)throw new TypeError(`'${request.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(codec,request,validate,schemaOrOptions)}_negotiatedWireCodec(){return codecForVersion(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(method){if(this._negotiatedProtocolVersion===void 0){let pinned=bootstrapOutboundCodec(method);if(pinned)return pinned}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(codec,method){if(isSpecRequestMethod(method)&&!codec.hasRequestMethod(method))throw new SdkError(SdkErrorCode.MethodNotSupportedByProtocolVersion,`Method '${method}' is not supported by the negotiated protocol version (wire era ${codec.era})`,{method,era:codec.era})}_requestWithSchema(request,resultSchema,options){let codec=this._resolveOutboundCodec(request.method);return this._assertOutboundRequestInEra(codec,request.method),this._requestWithSchemaViaCodec(codec,request,resultSchema,options)}_requestWithSchemaViaCodec(codec,request,resultSchema,options){let{relatedRequestId,resumptionToken,onresumptiontoken,headers}=options??{},flowStartedAt=Date.now(),onAbort,cleanupMessageId;return new Promise((resolve,reject)=>{let earlyReject=error3=>{reject(error3)};if(!this._transport){earlyReject(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(request.method)}catch(error3){earlyReject(error3);return}if(options?.signal?.aborted){let reason=options.signal.reason;throw reason instanceof SdkError?reason:new SdkError(SdkErrorCode.RequestTimeout,String(reason))}let requestAbort=codec.era===MODERN_WIRE_REVISION&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,messageId=this._requestMessageId++;cleanupMessageId=messageId;let jsonrpcRequest={...request,jsonrpc:"2.0",id:messageId};options?.onprogress&&(this._progressHandlers.set(messageId,options.onprogress),jsonrpcRequest.params={...request.params,_meta:{...request.params?._meta,progressToken:messageId}});let outbound=this._envelopeOutbound(jsonrpcRequest),responseReceived=!1,cancel=reason=>{responseReceived||(this._progressHandlers.delete(messageId),requestAbort===void 0?this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:messageId,reason:String(reason)}}),{relatedRequestId,resumptionToken,onresumptiontoken}).catch(error3=>this._onerror(new Error(`Failed to send cancellation: ${error3}`))):requestAbort.abort(),reject(reason instanceof SdkError?reason:new SdkError(SdkErrorCode.RequestTimeout,String(reason))))};this._responseHandlers.set(messageId,response=>{if(options?.signal?.aborted)return;if(responseReceived=!0,response instanceof Error)return reject(response);let decoded;try{decoded=codec.decodeResult(request.method,response.result)}catch(error3){return reject(error3 instanceof Error?error3:new Error(String(error3)))}if(decoded.kind==="invalid")return reject(decoded.error);if(decoded.kind==="input_required"){if(options?.allowInputRequired===!0)return resolve(manualInputRequiredValue(decoded));let flow={codec,request,resultSchema,options,flowStartedAt,retry:(params,legOptions)=>this._requestWithSchemaViaCodec(codec,params===void 0?{method:request.method}:{method:request.method,params},resultSchema,legOptions)};return resolve(this._resolveNonCompleteResult(decoded,flow))}let result=decoded.result;validateStandardSchema(resultSchema,result).then(parseResult=>{parseResult.success?resolve(parseResult.data):reject(new SdkError(SdkErrorCode.InvalidResult,`Invalid result for ${request.method}: ${parseResult.error}`))},reject)}),onAbort=()=>cancel(options?.signal?.reason),options?.signal?.addEventListener("abort",onAbort,{once:!0});let timeout=options?.timeout??DEFAULT_REQUEST_TIMEOUT_MSEC,timeoutHandler=()=>cancel(new SdkError(SdkErrorCode.RequestTimeout,"Request timed out",{timeout}));this._setupTimeout(messageId,timeout,options?.maxTotalTimeout,timeoutHandler,options?.resetTimeoutOnProgress??!1),this._transport.send(outbound,{relatedRequestId,resumptionToken,onresumptiontoken,headers,requestSignal:requestAbort?.signal}).catch(error3=>{this._progressHandlers.delete(messageId),reject(error3)})}).finally(()=>{onAbort&&options?.signal?.removeEventListener("abort",onAbort),cleanupMessageId!==void 0&&(this._responseHandlers.delete(cleanupMessageId),this._cleanupTimeout(cleanupMessageId))})}async notification(notification,options){return this._notificationViaCodec(this._resolveOutboundCodec(notification.method),notification,options)}async _notificationViaCodec(codec,notification,options){if(!this._transport)throw new SdkError(SdkErrorCode.NotConnected,"Not connected");if(isSpecNotificationMethod(notification.method)&&!codec.hasNotificationMethod(notification.method))throw new SdkError(SdkErrorCode.MethodNotSupportedByProtocolVersion,`Notification '${notification.method}' is not supported by the negotiated protocol version (wire era ${codec.era})`,{method:notification.method,era:codec.era});this.assertNotificationCapability(notification.method);let jsonrpcNotification=this._envelopeOutbound({jsonrpc:"2.0",...notification});if((this._options?.debouncedNotificationMethods??[]).includes(notification.method)&&!notification.params&&!options?.relatedRequestId){if(this._pendingDebouncedNotifications.has(notification.method))return;this._pendingDebouncedNotifications.add(notification.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(notification.method),this._transport&&this._transport?.send(jsonrpcNotification,options).catch(error3=>this._onerror(error3))});return}await this._transport.send(jsonrpcNotification,options)}setRequestHandler(method,schemasOrHandler,maybeHandler){this.assertRequestHandlerCapability(method);let stored;if(typeof schemasOrHandler=="function"){if(!isSpecRequestMethod(method))throw new TypeError(`'${method}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);stored=(request,ctx)=>{let dispatchCodec=this._negotiatedWireCodec(),outcome=dispatchCodec.validateRequest(method,request);if(!outcome.ok&&outcome.reason==="not-in-era"&&(outcome=dispatchCodec.validateInputRequest(method,request)),!outcome.ok)throw outcome.reason==="not-in-era"?new ProtocolError(ProtocolErrorCode.InternalError,`No wire schema for ${method} in the resolved era`):new Error(outcome.message);return Promise.resolve(schemasOrHandler(outcome.value,ctx))}}else if(maybeHandler)stored=async(request,ctx)=>{let parsed=await validateStandardSchema(schemasOrHandler.params,{...request.params});if(!parsed.success)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Invalid params for ${method}: ${parsed.error}`);return maybeHandler(parsed.data,ctx)};else throw new TypeError("setRequestHandler: handler is required");this._requestHandlers.set(method,this._wrapHandler(method,stored))}_wrapHandler(_method,handler){return handler}_outboundServerInfo(){}removeRequestHandler(method){this._requestHandlers.delete(method)}assertCanSetRequestHandler(method){if(this._requestHandlers.has(method))throw new Error(`A request handler for ${method} already exists, which would be overridden`)}setNotificationHandler(method,schemasOrHandler,maybeHandler){if(typeof schemasOrHandler=="function"){if(!isSpecNotificationMethod(method))throw new TypeError(`'${method}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(method,(notification,codec)=>{let outcome=codec.validateNotification(method,notification);if(!outcome.ok)throw outcome.reason==="not-in-era"?new ProtocolError(ProtocolErrorCode.InternalError,`No wire schema for ${method} in the resolved era`):new Error(outcome.message);return Promise.resolve(schemasOrHandler(outcome.value))});return}if(!maybeHandler)throw new TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(method,async notification=>{let parsed=await validateStandardSchema(schemasOrHandler.params,{...notification.params});if(!parsed.success)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Invalid params for notification ${method}: ${parsed.error}`);await maybeHandler(parsed.data,notification)})}removeNotificationHandler(method){this._notificationHandlers.delete(method)}};require_content_type=__commonJSMin((exports=>{var PARAM_REGEXP=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,QESC_REGEXP=/\\([\u000b\u0020-\u00ff])/g,TYPE_REGEXP=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;exports.parse=parse3;function parse3(string4){if(!string4)throw new TypeError("argument string is required");var header=typeof string4=="object"?getcontenttype(string4):string4;if(typeof header!="string")throw new TypeError("argument string is required to be a string");var index=header.indexOf(";"),type=index!==-1?header.slice(0,index).trim():header.trim();if(!TYPE_REGEXP.test(type))throw new TypeError("invalid media type");var obj=new ContentType(type.toLowerCase());if(index!==-1){var key,match2,value;for(PARAM_REGEXP.lastIndex=index;match2=PARAM_REGEXP.exec(header);){if(match2.index!==index)throw new TypeError("invalid parameter format");index+=match2[0].length,key=match2[1].toLowerCase(),value=match2[2],value.charCodeAt(0)===34&&(value=value.slice(1,-1),value.indexOf("\\")!==-1&&(value=value.replace(QESC_REGEXP,"$1"))),obj.parameters[key]=value}if(index!==header.length)throw new TypeError("invalid parameter format")}return obj}function getcontenttype(obj){var header;if(typeof obj.getHeader=="function"?header=obj.getHeader("content-type"):typeof obj.headers=="object"&&(header=obj.headers&&obj.headers["content-type"]),typeof header!="string")throw new TypeError("content-type header is missing from object");return header}function ContentType(type){this.parameters=Object.create(null),this.type=type}})),import_content_type=__toESM(require_content_type(),1);STDIO_DEFAULT_MAX_BUFFER_SIZE=10*1024*1024,TOOL_NAME_REGEX=/^[A-Za-z0-9._-]{1,128}$/;MAX_TEMPLATE_LENGTH=1e6,MAX_VARIABLE_LENGTH=1e6,MAX_TEMPLATE_EXPRESSIONS=1e4,MAX_REGEX_LENGTH=1e6,UriTemplate=class UriTemplate2{static isTemplate(str){return/\{[^}\s]+\}/.test(str)}static validateLength(str,max,context){if(str.length>max)throw new Error(`${context} exceeds maximum length of ${max} characters (got ${str.length})`)}template;parts;get variableNames(){return this.parts.flatMap(part=>typeof part=="string"?[]:part.names)}constructor(template){UriTemplate2.validateLength(template,MAX_TEMPLATE_LENGTH,"Template"),this.template=template,this.parts=this.parse(template)}toString(){return this.template}parse(template){let parts=[],currentText="",i=0,expressionCount=0;for(;i<template.length;)if(template[i]==="{"){currentText&&(parts.push(currentText),currentText="");let end=template.indexOf("}",i);if(end===-1)throw new Error("Unclosed template expression");if(expressionCount++,expressionCount>MAX_TEMPLATE_EXPRESSIONS)throw new Error(`Template contains too many expressions (max ${MAX_TEMPLATE_EXPRESSIONS})`);let expr=template.slice(i+1,end),operator=this.getOperator(expr),exploded=expr.includes("*"),names=this.getNames(expr),name=names[0];for(let name$1 of names)UriTemplate2.validateLength(name$1,MAX_VARIABLE_LENGTH,"Variable name");parts.push({name,operator,names,exploded}),i=end+1}else currentText+=template[i],i++;return currentText&&parts.push(currentText),parts}getOperator(expr){return["+","#",".","/","?","&"].find(op=>expr.startsWith(op))||""}getNames(expr){let operator=this.getOperator(expr);return expr.slice(operator.length).split(",").map(name=>name.replace("*","").trim()).filter(name=>name.length>0)}encodeValue(value,operator){return UriTemplate2.validateLength(value,MAX_VARIABLE_LENGTH,"Variable value"),operator==="+"||operator==="#"?encodeURI(value):encodeURIComponent(value)}expandPart(part,variables){if(part.operator==="?"||part.operator==="&"){let pairs=part.names.map(name=>{let value$1=variables[name];return value$1===void 0?"":`${name}=${Array.isArray(value$1)?value$1.map(v=>this.encodeValue(v,part.operator)).join(","):this.encodeValue(value$1.toString(),part.operator)}`}).filter(pair=>pair.length>0);return pairs.length===0?"":(part.operator==="?"?"?":"&")+pairs.join("&")}if(part.names.length>1){let values=part.names.map(name=>variables[name]).filter(v=>v!==void 0);return values.length===0?"":values.map(v=>Array.isArray(v)?v[0]:v).join(",")}let value=variables[part.name];if(value===void 0)return"";let encoded=(Array.isArray(value)?value:[value]).map(v=>this.encodeValue(v,part.operator));switch(part.operator){case"":return encoded.join(",");case"+":return encoded.join(",");case"#":return"#"+encoded.join(",");case".":return"."+encoded.join(".");case"/":return"/"+encoded.join("/");default:return encoded.join(",")}}expand(variables){let result="",hasQueryParam=!1;for(let part of this.parts){if(typeof part=="string"){result+=part;continue}let expanded=this.expandPart(part,variables);expanded&&(result+=(part.operator==="?"||part.operator==="&")&&hasQueryParam?expanded.replace("?","&"):expanded,(part.operator==="?"||part.operator==="&")&&(hasQueryParam=!0))}return result}escapeRegExp(str){return str.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`)}partToRegExp(part){let patterns=[];for(let name$1 of part.names)UriTemplate2.validateLength(name$1,MAX_VARIABLE_LENGTH,"Variable name");if(part.operator==="?"||part.operator==="&"){for(let i=0;i<part.names.length;i++){let name$1=part.names[i],prefix=i===0?"\\"+part.operator:"&";patterns.push({pattern:prefix+this.escapeRegExp(name$1)+"=([^&]+)",name:name$1})}return patterns}let pattern,name=part.name;switch(part.operator){case"":pattern=part.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)";break;case"+":case"#":pattern="(.+)";break;case".":pattern=String.raw`\.([^/,]+)`;break;case"/":pattern="/"+(part.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)");break;default:pattern="([^/]+)"}return patterns.push({pattern,name}),patterns}match(uri){UriTemplate2.validateLength(uri,MAX_TEMPLATE_LENGTH,"URI");let pattern="^",names=[];for(let part of this.parts)if(typeof part=="string")pattern+=this.escapeRegExp(part);else{let patterns=this.partToRegExp(part);for(let{pattern:partPattern,name}of patterns)pattern+=partPattern,names.push({name,exploded:part.exploded})}pattern+="$",UriTemplate2.validateLength(pattern,MAX_REGEX_LENGTH,"Generated regex pattern");let regex=new RegExp(pattern),match2=uri.match(regex);if(!match2)return null;let result={};for(let[i,name_]of names.entries()){let{name,exploded}=name_,value=match2[i+1],cleanName=name.replace("*","");result[cleanName]=exploded&&value.includes(",")?value.split(","):value}return result}}}});function createDefaultAjvInstance(engineClass){let ajv=new engineClass({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return addFormats(ajv),ajv}var require_code$1,require_scope,require_codegen,require_util,require_names,require_errors,require_boolSchema,require_rules,require_applicability,require_dataType,require_defaults,require_code,require_keyword,require_subschema,require_fast_deep_equal,require_json_schema_traverse,require_resolve,require_validate,require_validation_error,require_ref_error,require_compile,require_data,require_utils,require_schemes,require_fast_uri,require_uri,require_core$3,require_id,require_ref,require_core$2,require_limitNumber,require_multipleOf,require_ucs2length,require_limitLength,require_pattern,require_limitProperties,require_required,require_limitItems,require_equal,require_uniqueItems,require_const,require_enum,require_validation$2,require_additionalItems,require_items,require_prefixItems,require_items2020,require_contains,require_dependencies,require_propertyNames,require_additionalProperties,require_properties,require_patternProperties,require_not,require_anyOf,require_oneOf,require_allOf,require_if,require_thenElse,require_applicator$2,require_format$2,require_format$1,require_metadata,require_draft7,require_types,require_discriminator,require_json_schema_draft_07,require_ajv,require_dynamicAnchor,require_dynamicRef,require_recursiveAnchor,require_recursiveRef,require_dynamic,require_dependentRequired,require_dependentSchemas,require_limitContains,require_next,require_unevaluatedProperties,require_unevaluatedItems,require_unevaluated$1,require_schema$1,require_applicator$1,require_content$1,require_core$1,require_format,require_meta_data$1,require_validation$1,require_json_schema_2019_09,require__2019,require_draft2020,require_schema,require_applicator,require_unevaluated,require_content,require_core,require_format_annotation,require_meta_data,require_validation,require_json_schema_2020_12,require__2020,require_formats,require_limit,require_dist,import_ajv,import__2019,import__2020,import_dist,addFormats,AjvJsonSchemaValidator,Ajv,init_ajvProvider_CEoC_sr=__esm({"../../node_modules/.pnpm/@modelcontextprotocol+server@2.0.0_patch_hash=2a5f5402571efdc40802e9603a3dd09e22588b4aacad710814c204d79568091e/node_modules/@modelcontextprotocol/server/dist/ajvProvider-CEoC__sr.mjs"(){"use strict";init_chunk_Br0eD_fh();init_dialects_DoSzNhcb();require_code$1=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.regexpCode=exports.getEsmExportName=exports.getProperty=exports.safeStringify=exports.stringify=exports.strConcat=exports.addCodeArg=exports.str=exports._=exports.nil=exports._Code=exports.Name=exports.IDENTIFIER=exports._CodeOrName=void 0;var _CodeOrName=class{};exports._CodeOrName=_CodeOrName,exports.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Name=class extends _CodeOrName{constructor(s){if(super(),!exports.IDENTIFIER.test(s))throw new Error("CodeGen: name must be a valid identifier");this.str=s}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};exports.Name=Name;var _Code=class extends _CodeOrName{constructor(code){super(),this._items=typeof code=="string"?[code]:code}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let item=this._items[0];return item===""||item==='""'}get str(){var _a3;return(_a3=this._str)!==null&&_a3!==void 0?_a3:this._str=this._items.reduce((s,c)=>`${s}${c}`,"")}get names(){var _a3;return(_a3=this._names)!==null&&_a3!==void 0?_a3:this._names=this._items.reduce((names,c)=>(c instanceof Name&&(names[c.str]=(names[c.str]||0)+1),names),{})}};exports._Code=_Code,exports.nil=new _Code("");function _(strs,...args){let code=[strs[0]],i=0;for(;i<args.length;)addCodeArg(code,args[i]),code.push(strs[++i]);return new _Code(code)}exports._=_;let plus=new _Code("+");function str(strs,...args){let expr=[safeStringify(strs[0])],i=0;for(;i<args.length;)expr.push(plus),addCodeArg(expr,args[i]),expr.push(plus,safeStringify(strs[++i]));return optimize(expr),new _Code(expr)}exports.str=str;function addCodeArg(code,arg){arg instanceof _Code?code.push(...arg._items):arg instanceof Name?code.push(arg):code.push(interpolate(arg))}exports.addCodeArg=addCodeArg;function optimize(expr){let i=1;for(;i<expr.length-1;){if(expr[i]===plus){let res=mergeExprItems(expr[i-1],expr[i+1]);if(res!==void 0){expr.splice(i-1,3,res);continue}expr[i++]="+"}i++}}function mergeExprItems(a,b){if(b==='""')return a;if(a==='""')return b;if(typeof a=="string")return b instanceof Name||a[a.length-1]!=='"'?void 0:typeof b!="string"?`${a.slice(0,-1)}${b}"`:b[0]==='"'?a.slice(0,-1)+b.slice(1):void 0;if(typeof b=="string"&&b[0]==='"'&&!(a instanceof Name))return`"${a}${b.slice(1)}`}function strConcat(c1,c2){return c2.emptyStr()?c1:c1.emptyStr()?c2:str`${c1}${c2}`}exports.strConcat=strConcat;function interpolate(x){return typeof x=="number"||typeof x=="boolean"||x===null?x:safeStringify(Array.isArray(x)?x.join(","):x)}function stringify(x){return new _Code(safeStringify(x))}exports.stringify=stringify;function safeStringify(x){return JSON.stringify(x).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}exports.safeStringify=safeStringify;function getProperty(key){return typeof key=="string"&&exports.IDENTIFIER.test(key)?new _Code(`.${key}`):_`[${key}]`}exports.getProperty=getProperty;function getEsmExportName(key){if(typeof key=="string"&&exports.IDENTIFIER.test(key))return new _Code(`${key}`);throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`)}exports.getEsmExportName=getEsmExportName;function regexpCode(rx){return new _Code(rx.toString())}exports.regexpCode=regexpCode})),require_scope=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.ValueScope=exports.ValueScopeName=exports.Scope=exports.varKinds=exports.UsedValueState=void 0;let code_1=require_code$1();var ValueError=class extends Error{constructor(name){super(`CodeGen: "code" for ${name} not defined`),this.value=name.value}},UsedValueState;(function(UsedValueState2){UsedValueState2[UsedValueState2.Started=0]="Started",UsedValueState2[UsedValueState2.Completed=1]="Completed"})(UsedValueState||(exports.UsedValueState=UsedValueState={})),exports.varKinds={const:new code_1.Name("const"),let:new code_1.Name("let"),var:new code_1.Name("var")};var Scope=class{constructor({prefixes,parent}={}){this._names={},this._prefixes=prefixes,this._parent=parent}toName(nameOrPrefix){return nameOrPrefix instanceof code_1.Name?nameOrPrefix:this.name(nameOrPrefix)}name(prefix){return new code_1.Name(this._newName(prefix))}_newName(prefix){let ng=this._names[prefix]||this._nameGroup(prefix);return`${prefix}${ng.index++}`}_nameGroup(prefix){var _a3,_b;if(!((_b=(_a3=this._parent)===null||_a3===void 0?void 0:_a3._prefixes)===null||_b===void 0)&&_b.has(prefix)||this._prefixes&&!this._prefixes.has(prefix))throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`);return this._names[prefix]={prefix,index:0}}};exports.Scope=Scope;var ValueScopeName=class extends code_1.Name{constructor(prefix,nameStr){super(nameStr),this.prefix=prefix}setValue(value,{property,itemIndex}){this.value=value,this.scopePath=(0,code_1._)`.${new code_1.Name(property)}[${itemIndex}]`}};exports.ValueScopeName=ValueScopeName;let line=(0,code_1._)`\n`;var ValueScope=class extends Scope{constructor(opts){super(opts),this._values={},this._scope=opts.scope,this.opts={...opts,_n:opts.lines?line:code_1.nil}}get(){return this._scope}name(prefix){return new ValueScopeName(prefix,this._newName(prefix))}value(nameOrPrefix,value){var _a3;if(value.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let name=this.toName(nameOrPrefix),{prefix}=name,valueKey=(_a3=value.key)!==null&&_a3!==void 0?_a3:value.ref,vs=this._values[prefix];if(vs){let _name=vs.get(valueKey);if(_name)return _name}else vs=this._values[prefix]=new Map;vs.set(valueKey,name);let s=this._scope[prefix]||(this._scope[prefix]=[]),itemIndex=s.length;return s[itemIndex]=value.ref,name.setValue(value,{property:prefix,itemIndex}),name}getValue(prefix,keyOrRef){let vs=this._values[prefix];if(vs)return vs.get(keyOrRef)}scopeRefs(scopeName,values=this._values){return this._reduceValues(values,name=>{if(name.scopePath===void 0)throw new Error(`CodeGen: name "${name}" has no value`);return(0,code_1._)`${scopeName}${name.scopePath}`})}scopeCode(values=this._values,usedValues,getCode){return this._reduceValues(values,name=>{if(name.value===void 0)throw new Error(`CodeGen: name "${name}" has no value`);return name.value.code},usedValues,getCode)}_reduceValues(values,valueCode,usedValues={},getCode){let code=code_1.nil;for(let prefix in values){let vs=values[prefix];if(!vs)continue;let nameSet=usedValues[prefix]=usedValues[prefix]||new Map;vs.forEach(name=>{if(nameSet.has(name))return;nameSet.set(name,UsedValueState.Started);let c=valueCode(name);if(c){let def=this.opts.es5?exports.varKinds.var:exports.varKinds.const;code=(0,code_1._)`${code}${def} ${name} = ${c};${this.opts._n}`}else if(c=getCode?.(name))code=(0,code_1._)`${code}${c}${this.opts._n}`;else throw new ValueError(name);nameSet.set(name,UsedValueState.Completed)})}return code}};exports.ValueScope=ValueScope})),require_codegen=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.or=exports.and=exports.not=exports.CodeGen=exports.operators=exports.varKinds=exports.ValueScopeName=exports.ValueScope=exports.Scope=exports.Name=exports.regexpCode=exports.stringify=exports.getProperty=exports.nil=exports.strConcat=exports.str=exports._=void 0;let code_1=require_code$1(),scope_1=require_scope();var code_2=require_code$1();Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return code_2._}}),Object.defineProperty(exports,"str",{enumerable:!0,get:function(){return code_2.str}}),Object.defineProperty(exports,"strConcat",{enumerable:!0,get:function(){return code_2.strConcat}}),Object.defineProperty(exports,"nil",{enumerable:!0,get:function(){return code_2.nil}}),Object.defineProperty(exports,"getProperty",{enumerable:!0,get:function(){return code_2.getProperty}}),Object.defineProperty(exports,"stringify",{enumerable:!0,get:function(){return code_2.stringify}}),Object.defineProperty(exports,"regexpCode",{enumerable:!0,get:function(){return code_2.regexpCode}}),Object.defineProperty(exports,"Name",{enumerable:!0,get:function(){return code_2.Name}});var scope_2=require_scope();Object.defineProperty(exports,"Scope",{enumerable:!0,get:function(){return scope_2.Scope}}),Object.defineProperty(exports,"ValueScope",{enumerable:!0,get:function(){return scope_2.ValueScope}}),Object.defineProperty(exports,"ValueScopeName",{enumerable:!0,get:function(){return scope_2.ValueScopeName}}),Object.defineProperty(exports,"varKinds",{enumerable:!0,get:function(){return scope_2.varKinds}}),exports.operators={GT:new code_1._Code(">"),GTE:new code_1._Code(">="),LT:new code_1._Code("<"),LTE:new code_1._Code("<="),EQ:new code_1._Code("==="),NEQ:new code_1._Code("!=="),NOT:new code_1._Code("!"),OR:new code_1._Code("||"),AND:new code_1._Code("&&"),ADD:new code_1._Code("+")};var Node3=class{optimizeNodes(){return this}optimizeNames(_names,_constants){return this}},Def=class extends Node3{constructor(varKind,name,rhs){super(),this.varKind=varKind,this.name=name,this.rhs=rhs}render({es5,_n}){let varKind=es5?scope_1.varKinds.var:this.varKind,rhs=this.rhs===void 0?"":` = ${this.rhs}`;return`${varKind} ${this.name}${rhs};`+_n}optimizeNames(names,constants){if(names[this.name.str])return this.rhs&&(this.rhs=optimizeExpr(this.rhs,names,constants)),this}get names(){return this.rhs instanceof code_1._CodeOrName?this.rhs.names:{}}},Assign=class extends Node3{constructor(lhs,rhs,sideEffects){super(),this.lhs=lhs,this.rhs=rhs,this.sideEffects=sideEffects}render({_n}){return`${this.lhs} = ${this.rhs};`+_n}optimizeNames(names,constants){if(!(this.lhs instanceof code_1.Name&&!names[this.lhs.str]&&!this.sideEffects))return this.rhs=optimizeExpr(this.rhs,names,constants),this}get names(){return addExprNames(this.lhs instanceof code_1.Name?{}:{...this.lhs.names},this.rhs)}},AssignOp=class extends Assign{constructor(lhs,op,rhs,sideEffects){super(lhs,rhs,sideEffects),this.op=op}render({_n}){return`${this.lhs} ${this.op}= ${this.rhs};`+_n}},Label=class extends Node3{constructor(label){super(),this.label=label,this.names={}}render({_n}){return`${this.label}:`+_n}},Break=class extends Node3{constructor(label){super(),this.label=label,this.names={}}render({_n}){return`break${this.label?` ${this.label}`:""};`+_n}},Throw=class extends Node3{constructor(error3){super(),this.error=error3}render({_n}){return`throw ${this.error};`+_n}get names(){return this.error.names}},AnyCode=class extends Node3{constructor(code){super(),this.code=code}render({_n}){return`${this.code};`+_n}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(names,constants){return this.code=optimizeExpr(this.code,names,constants),this}get names(){return this.code instanceof code_1._CodeOrName?this.code.names:{}}},ParentNode=class extends Node3{constructor(nodes=[]){super(),this.nodes=nodes}render(opts){return this.nodes.reduce((code,n)=>code+n.render(opts),"")}optimizeNodes(){let{nodes}=this,i=nodes.length;for(;i--;){let n=nodes[i].optimizeNodes();Array.isArray(n)?nodes.splice(i,1,...n):n?nodes[i]=n:nodes.splice(i,1)}return nodes.length>0?this:void 0}optimizeNames(names,constants){let{nodes}=this,i=nodes.length;for(;i--;){let n=nodes[i];n.optimizeNames(names,constants)||(subtractNames(names,n.names),nodes.splice(i,1))}return nodes.length>0?this:void 0}get names(){return this.nodes.reduce((names,n)=>addNames(names,n.names),{})}},BlockNode=class extends ParentNode{render(opts){return"{"+opts._n+super.render(opts)+"}"+opts._n}},Root=class extends ParentNode{},Else=class extends BlockNode{};Else.kind="else";var If=class If2 extends BlockNode{constructor(condition,nodes){super(nodes),this.condition=condition}render(opts){let code=`if(${this.condition})`+super.render(opts);return this.else&&(code+="else "+this.else.render(opts)),code}optimizeNodes(){super.optimizeNodes();let cond=this.condition;if(cond===!0)return this.nodes;let e=this.else;if(e){let ns=e.optimizeNodes();e=this.else=Array.isArray(ns)?new Else(ns):ns}if(e)return cond===!1?e instanceof If2?e:e.nodes:this.nodes.length?this:new If2(not(cond),e instanceof If2?[e]:e.nodes);if(!(cond===!1||!this.nodes.length))return this}optimizeNames(names,constants){var _a3;if(this.else=(_a3=this.else)===null||_a3===void 0?void 0:_a3.optimizeNames(names,constants),!!(super.optimizeNames(names,constants)||this.else))return this.condition=optimizeExpr(this.condition,names,constants),this}get names(){let names=super.names;return addExprNames(names,this.condition),this.else&&addNames(names,this.else.names),names}};If.kind="if";var For=class extends BlockNode{};For.kind="for";var ForLoop=class extends For{constructor(iteration){super(),this.iteration=iteration}render(opts){return`for(${this.iteration})`+super.render(opts)}optimizeNames(names,constants){if(super.optimizeNames(names,constants))return this.iteration=optimizeExpr(this.iteration,names,constants),this}get names(){return addNames(super.names,this.iteration.names)}},ForRange=class extends For{constructor(varKind,name,from,to){super(),this.varKind=varKind,this.name=name,this.from=from,this.to=to}render(opts){let varKind=opts.es5?scope_1.varKinds.var:this.varKind,{name,from,to}=this;return`for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)`+super.render(opts)}get names(){return addExprNames(addExprNames(super.names,this.from),this.to)}},ForIter=class extends For{constructor(loop,varKind,name,iterable){super(),this.loop=loop,this.varKind=varKind,this.name=name,this.iterable=iterable}render(opts){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(opts)}optimizeNames(names,constants){if(super.optimizeNames(names,constants))return this.iterable=optimizeExpr(this.iterable,names,constants),this}get names(){return addNames(super.names,this.iterable.names)}},Func=class extends BlockNode{constructor(name,args,async){super(),this.name=name,this.args=args,this.async=async}render(opts){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(opts)}};Func.kind="func";var Return=class extends ParentNode{render(opts){return"return "+super.render(opts)}};Return.kind="return";var Try=class extends BlockNode{render(opts){let code="try"+super.render(opts);return this.catch&&(code+=this.catch.render(opts)),this.finally&&(code+=this.finally.render(opts)),code}optimizeNodes(){var _a3,_b;return super.optimizeNodes(),(_a3=this.catch)===null||_a3===void 0||_a3.optimizeNodes(),(_b=this.finally)===null||_b===void 0||_b.optimizeNodes(),this}optimizeNames(names,constants){var _a3,_b;return super.optimizeNames(names,constants),(_a3=this.catch)===null||_a3===void 0||_a3.optimizeNames(names,constants),(_b=this.finally)===null||_b===void 0||_b.optimizeNames(names,constants),this}get names(){let names=super.names;return this.catch&&addNames(names,this.catch.names),this.finally&&addNames(names,this.finally.names),names}},Catch=class extends BlockNode{constructor(error3){super(),this.error=error3}render(opts){return`catch(${this.error})`+super.render(opts)}};Catch.kind="catch";var Finally=class extends BlockNode{render(opts){return"finally"+super.render(opts)}};Finally.kind="finally";var CodeGen=class{constructor(extScope,opts={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...opts,_n:opts.lines?`
64
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let entry of ctx.seen.entries()){let seen=entry[1];if(schema2===entry[0]){extractToDef(entry);continue}if(ctx.external){let ext=ctx.external.registry.get(entry[0])?.id;if(schema2!==entry[0]&&ext){extractToDef(entry);continue}}if(ctx.metadataRegistry.get(entry[0])?.id){extractToDef(entry);continue}if(seen.cycle){extractToDef(entry);continue}if(seen.count>1&&ctx.reused==="ref"){extractToDef(entry);continue}}}function finalize(ctx,schema2){let root=ctx.seen.get(schema2);if(!root)throw new Error("Unprocessed schema. This is a bug in Zod.");let flattenRef=zodSchema=>{let seen=ctx.seen.get(zodSchema);if(seen.ref===null)return;let schema3=seen.def??seen.schema,_cached={...schema3},ref=seen.ref;if(seen.ref=null,ref){flattenRef(ref);let refSeen=ctx.seen.get(ref),refSchema=refSeen.schema;if(refSchema.$ref&&(ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0")?(schema3.allOf=schema3.allOf??[],schema3.allOf.push(refSchema)):Object.assign(schema3,refSchema),Object.assign(schema3,_cached),zodSchema._zod.parent===ref)for(let key in schema3)key==="$ref"||key==="allOf"||key in _cached||delete schema3[key];if(refSchema.$ref&&refSeen.def)for(let key in schema3)key==="$ref"||key==="allOf"||key in refSeen.def&&JSON.stringify(schema3[key])===JSON.stringify(refSeen.def[key])&&delete schema3[key]}let parent=zodSchema._zod.parent;if(parent&&parent!==ref){flattenRef(parent);let parentSeen=ctx.seen.get(parent);if(parentSeen?.schema.$ref&&(schema3.$ref=parentSeen.schema.$ref,parentSeen.def))for(let key in schema3)key==="$ref"||key==="allOf"||key in parentSeen.def&&JSON.stringify(schema3[key])===JSON.stringify(parentSeen.def[key])&&delete schema3[key]}ctx.override({zodSchema,jsonSchema:schema3,path:seen.path??[]})};for(let entry of[...ctx.seen.entries()].reverse())flattenRef(entry[0]);let result={};if(ctx.target==="draft-2020-12"?result.$schema="https://json-schema.org/draft/2020-12/schema":ctx.target==="draft-07"?result.$schema="http://json-schema.org/draft-07/schema#":ctx.target==="draft-04"?result.$schema="http://json-schema.org/draft-04/schema#":ctx.target,ctx.external?.uri){let id=ctx.external.registry.get(schema2)?.id;if(!id)throw new Error("Schema is missing an `id` property");result.$id=ctx.external.uri(id)}Object.assign(result,root.def??root.schema);let rootMetaId=ctx.metadataRegistry.get(schema2)?.id;rootMetaId!==void 0&&result.id===rootMetaId&&delete result.id;let defs=ctx.external?.defs??{};for(let entry of ctx.seen.entries()){let seen=entry[1];seen.def&&seen.defId&&(seen.def.id===seen.defId&&delete seen.def.id,defs[seen.defId]=seen.def)}ctx.external||Object.keys(defs).length>0&&(ctx.target==="draft-2020-12"?result.$defs=defs:result.definitions=defs);try{let finalized=JSON.parse(JSON.stringify(result));return Object.defineProperty(finalized,"~standard",{value:{...schema2["~standard"],jsonSchema:{input:createStandardJSONSchemaMethod(schema2,"input",ctx.processors),output:createStandardJSONSchemaMethod(schema2,"output",ctx.processors)}},enumerable:!1,writable:!1}),finalized}catch{throw new Error("Error converting schema to JSON.")}}function isTransforming(_schema,_ctx){let ctx=_ctx??{seen:new Set};if(ctx.seen.has(_schema))return!1;ctx.seen.add(_schema);let def=_schema._zod.def;if(def.type==="transform")return!0;if(def.type==="array")return isTransforming(def.element,ctx);if(def.type==="set")return isTransforming(def.valueType,ctx);if(def.type==="lazy")return isTransforming(def.getter(),ctx);if(def.type==="promise"||def.type==="optional"||def.type==="nonoptional"||def.type==="nullable"||def.type==="readonly"||def.type==="default"||def.type==="prefault")return isTransforming(def.innerType,ctx);if(def.type==="intersection")return isTransforming(def.left,ctx)||isTransforming(def.right,ctx);if(def.type==="record"||def.type==="map")return isTransforming(def.keyType,ctx)||isTransforming(def.valueType,ctx);if(def.type==="pipe")return _schema._zod.traits.has("$ZodCodec")?!0:isTransforming(def.in,ctx)||isTransforming(def.out,ctx);if(def.type==="object"){for(let key in def.shape)if(isTransforming(def.shape[key],ctx))return!0;return!1}if(def.type==="union"){for(let option of def.options)if(isTransforming(option,ctx))return!0;return!1}if(def.type==="tuple"){for(let item of def.items)if(isTransforming(item,ctx))return!0;return!!(def.rest&&isTransforming(def.rest,ctx))}return!1}var createToJSONSchemaMethod,createStandardJSONSchemaMethod,init_to_json_schema=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/to-json-schema.js"(){"use strict";init_registries();createToJSONSchemaMethod=(schema2,processors={})=>params=>{let ctx=initializeContext({...params,processors});return process2(schema2,ctx),extractDefs(ctx,schema2),finalize(ctx,schema2)},createStandardJSONSchemaMethod=(schema2,io,processors={})=>params=>{let{libraryOptions,target}=params??{},ctx=initializeContext({...libraryOptions??{},target,io,processors});return process2(schema2,ctx),extractDefs(ctx,schema2),finalize(ctx,schema2)}}});function toJSONSchema(input,params){if("_idmap"in input){let registry2=input,ctx2=initializeContext({...params,processors:allProcessors}),defs={};for(let entry of registry2._idmap.entries()){let[_,schema2]=entry;process2(schema2,ctx2)}let schemas={},external={registry:registry2,uri:params?.uri,defs};ctx2.external=external;for(let entry of registry2._idmap.entries()){let[key,schema2]=entry;extractDefs(ctx2,schema2),schemas[key]=finalize(ctx2,schema2)}if(Object.keys(defs).length>0){let defsSegment=ctx2.target==="draft-2020-12"?"$defs":"definitions";schemas.__shared={[defsSegment]:defs}}return{schemas}}let ctx=initializeContext({...params,processors:allProcessors});return process2(input,ctx),extractDefs(ctx,input),finalize(ctx,input)}var formatMap,stringProcessor,numberProcessor,booleanProcessor,bigintProcessor,symbolProcessor,nullProcessor,undefinedProcessor,voidProcessor,neverProcessor,anyProcessor,unknownProcessor,dateProcessor,enumProcessor,literalProcessor,nanProcessor,templateLiteralProcessor,fileProcessor,successProcessor,customProcessor,functionProcessor,transformProcessor,mapProcessor,setProcessor,arrayProcessor,objectProcessor,unionProcessor,intersectionProcessor,tupleProcessor,recordProcessor,nullableProcessor,nonoptionalProcessor,defaultProcessor,prefaultProcessor,catchProcessor,pipeProcessor,readonlyProcessor,promiseProcessor,optionalProcessor,lazyProcessor,allProcessors,init_json_schema_processors=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-processors.js"(){"use strict";init_to_json_schema();init_util();formatMap={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},stringProcessor=(schema2,ctx,_json,_params)=>{let json=_json;json.type="string";let{minimum,maximum,format,patterns,contentEncoding}=schema2._zod.bag;if(typeof minimum=="number"&&(json.minLength=minimum),typeof maximum=="number"&&(json.maxLength=maximum),format&&(json.format=formatMap[format]??format,json.format===""&&delete json.format,format==="time"&&delete json.format),contentEncoding&&(json.contentEncoding=contentEncoding),patterns&&patterns.size>0){let regexes=[...patterns];regexes.length===1?json.pattern=regexes[0].source:regexes.length>1&&(json.allOf=[...regexes.map(regex=>({...ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0"?{type:"string"}:{},pattern:regex.source}))])}},numberProcessor=(schema2,ctx,_json,_params)=>{let json=_json,{minimum,maximum,format,multipleOf,exclusiveMaximum,exclusiveMinimum}=schema2._zod.bag;typeof format=="string"&&format.includes("int")?json.type="integer":json.type="number";let exMin=typeof exclusiveMinimum=="number"&&exclusiveMinimum>=(minimum??Number.NEGATIVE_INFINITY),exMax=typeof exclusiveMaximum=="number"&&exclusiveMaximum<=(maximum??Number.POSITIVE_INFINITY),legacy=ctx.target==="draft-04"||ctx.target==="openapi-3.0";exMin?legacy?(json.minimum=exclusiveMinimum,json.exclusiveMinimum=!0):json.exclusiveMinimum=exclusiveMinimum:typeof minimum=="number"&&(json.minimum=minimum),exMax?legacy?(json.maximum=exclusiveMaximum,json.exclusiveMaximum=!0):json.exclusiveMaximum=exclusiveMaximum:typeof maximum=="number"&&(json.maximum=maximum),typeof multipleOf=="number"&&(json.multipleOf=multipleOf)},booleanProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"},bigintProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},symbolProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},nullProcessor=(_schema,ctx,json,_params)=>{ctx.target==="openapi-3.0"?(json.type="string",json.nullable=!0,json.enum=[null]):json.type="null"},undefinedProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},voidProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},neverProcessor=(_schema,_ctx,json,_params)=>{json.not={}},anyProcessor=(_schema,_ctx,_json,_params)=>{},unknownProcessor=(_schema,_ctx,_json,_params)=>{},dateProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},enumProcessor=(schema2,_ctx,json,_params)=>{let def=schema2._zod.def,values=getEnumValues(def.entries);values.every(v=>typeof v=="number")&&(json.type="number"),values.every(v=>typeof v=="string")&&(json.type="string"),json.enum=values},literalProcessor=(schema2,ctx,json,_params)=>{let def=schema2._zod.def,vals=[];for(let val of def.values)if(val===void 0){if(ctx.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof val=="bigint"){if(ctx.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");vals.push(Number(val))}else vals.push(val);if(vals.length!==0)if(vals.length===1){let val=vals[0];json.type=val===null?"null":typeof val,ctx.target==="draft-04"||ctx.target==="openapi-3.0"?json.enum=[val]:json.const=val}else vals.every(v=>typeof v=="number")&&(json.type="number"),vals.every(v=>typeof v=="string")&&(json.type="string"),vals.every(v=>typeof v=="boolean")&&(json.type="boolean"),vals.every(v=>v===null)&&(json.type="null"),json.enum=vals},nanProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},templateLiteralProcessor=(schema2,_ctx,json,_params)=>{let _json=json,pattern=schema2._zod.pattern;if(!pattern)throw new Error("Pattern not found in template literal");_json.type="string",_json.pattern=pattern.source},fileProcessor=(schema2,_ctx,json,_params)=>{let _json=json,file={type:"string",format:"binary",contentEncoding:"binary"},{minimum,maximum,mime}=schema2._zod.bag;minimum!==void 0&&(file.minLength=minimum),maximum!==void 0&&(file.maxLength=maximum),mime?mime.length===1?(file.contentMediaType=mime[0],Object.assign(_json,file)):(Object.assign(_json,file),_json.anyOf=mime.map(m=>({contentMediaType:m}))):Object.assign(_json,file)},successProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"},customProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},functionProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},transformProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},mapProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},setProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},arrayProcessor=(schema2,ctx,_json,params)=>{let json=_json,def=schema2._zod.def,{minimum,maximum}=schema2._zod.bag;typeof minimum=="number"&&(json.minItems=minimum),typeof maximum=="number"&&(json.maxItems=maximum),json.type="array",json.items=process2(def.element,ctx,{...params,path:[...params.path,"items"]})},objectProcessor=(schema2,ctx,_json,params)=>{let json=_json,def=schema2._zod.def;json.type="object",json.properties={};let shape=def.shape;for(let key in shape)json.properties[key]=process2(shape[key],ctx,{...params,path:[...params.path,"properties",key]});let allKeys=new Set(Object.keys(shape)),requiredKeys=new Set([...allKeys].filter(key=>{let v=def.shape[key]._zod;return ctx.io==="input"?v.optin===void 0:v.optout===void 0}));requiredKeys.size>0&&(json.required=Array.from(requiredKeys)),def.catchall?._zod.def.type==="never"?json.additionalProperties=!1:def.catchall?def.catchall&&(json.additionalProperties=process2(def.catchall,ctx,{...params,path:[...params.path,"additionalProperties"]})):ctx.io==="output"&&(json.additionalProperties=!1)},unionProcessor=(schema2,ctx,json,params)=>{let def=schema2._zod.def,isExclusive=def.inclusive===!1,options=def.options.map((x,i)=>process2(x,ctx,{...params,path:[...params.path,isExclusive?"oneOf":"anyOf",i]}));isExclusive?json.oneOf=options:json.anyOf=options},intersectionProcessor=(schema2,ctx,json,params)=>{let def=schema2._zod.def,a=process2(def.left,ctx,{...params,path:[...params.path,"allOf",0]}),b=process2(def.right,ctx,{...params,path:[...params.path,"allOf",1]}),isSimpleIntersection=val=>"allOf"in val&&Object.keys(val).length===1,allOf=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(b)?b.allOf:[b]];json.allOf=allOf},tupleProcessor=(schema2,ctx,_json,params)=>{let json=_json,def=schema2._zod.def;json.type="array";let prefixPath=ctx.target==="draft-2020-12"?"prefixItems":"items",restPath=ctx.target==="draft-2020-12"||ctx.target==="openapi-3.0"?"items":"additionalItems",prefixItems=def.items.map((x,i)=>process2(x,ctx,{...params,path:[...params.path,prefixPath,i]})),rest=def.rest?process2(def.rest,ctx,{...params,path:[...params.path,restPath,...ctx.target==="openapi-3.0"?[def.items.length]:[]]}):null;ctx.target==="draft-2020-12"?(json.prefixItems=prefixItems,rest&&(json.items=rest)):ctx.target==="openapi-3.0"?(json.items={anyOf:prefixItems},rest&&json.items.anyOf.push(rest),json.minItems=prefixItems.length,rest||(json.maxItems=prefixItems.length)):(json.items=prefixItems,rest&&(json.additionalItems=rest));let{minimum,maximum}=schema2._zod.bag;typeof minimum=="number"&&(json.minItems=minimum),typeof maximum=="number"&&(json.maxItems=maximum)},recordProcessor=(schema2,ctx,_json,params)=>{let json=_json,def=schema2._zod.def;json.type="object";let keyType=def.keyType,patterns=keyType._zod.bag?.patterns;if(def.mode==="loose"&&patterns&&patterns.size>0){let valueSchema=process2(def.valueType,ctx,{...params,path:[...params.path,"patternProperties","*"]});json.patternProperties={};for(let pattern of patterns)json.patternProperties[pattern.source]=valueSchema}else(ctx.target==="draft-07"||ctx.target==="draft-2020-12")&&(json.propertyNames=process2(def.keyType,ctx,{...params,path:[...params.path,"propertyNames"]})),json.additionalProperties=process2(def.valueType,ctx,{...params,path:[...params.path,"additionalProperties"]});let keyValues=keyType._zod.values;if(keyValues){let validKeyValues=[...keyValues].filter(v=>typeof v=="string"||typeof v=="number");validKeyValues.length>0&&(json.required=validKeyValues)}},nullableProcessor=(schema2,ctx,json,params)=>{let def=schema2._zod.def,inner=process2(def.innerType,ctx,params),seen=ctx.seen.get(schema2);ctx.target==="openapi-3.0"?(seen.ref=def.innerType,json.nullable=!0):json.anyOf=[inner,{type:"null"}]},nonoptionalProcessor=(schema2,ctx,_json,params)=>{let def=schema2._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema2);seen.ref=def.innerType},defaultProcessor=(schema2,ctx,json,params)=>{let def=schema2._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema2);seen.ref=def.innerType,json.default=JSON.parse(JSON.stringify(def.defaultValue))},prefaultProcessor=(schema2,ctx,json,params)=>{let def=schema2._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema2);seen.ref=def.innerType,ctx.io==="input"&&(json._prefault=JSON.parse(JSON.stringify(def.defaultValue)))},catchProcessor=(schema2,ctx,json,params)=>{let def=schema2._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema2);seen.ref=def.innerType;let catchValue;try{catchValue=def.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}json.default=catchValue},pipeProcessor=(schema2,ctx,_json,params)=>{let def=schema2._zod.def,inIsTransform=def.in._zod.traits.has("$ZodTransform"),innerType=ctx.io==="input"?inIsTransform?def.out:def.in:def.out;process2(innerType,ctx,params);let seen=ctx.seen.get(schema2);seen.ref=innerType},readonlyProcessor=(schema2,ctx,json,params)=>{let def=schema2._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema2);seen.ref=def.innerType,json.readOnly=!0},promiseProcessor=(schema2,ctx,_json,params)=>{let def=schema2._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema2);seen.ref=def.innerType},optionalProcessor=(schema2,ctx,_json,params)=>{let def=schema2._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema2);seen.ref=def.innerType},lazyProcessor=(schema2,ctx,_json,params)=>{let innerType=schema2._zod.innerType;process2(innerType,ctx,params);let seen=ctx.seen.get(schema2);seen.ref=innerType},allProcessors={string:stringProcessor,number:numberProcessor,boolean:booleanProcessor,bigint:bigintProcessor,symbol:symbolProcessor,null:nullProcessor,undefined:undefinedProcessor,void:voidProcessor,never:neverProcessor,any:anyProcessor,unknown:unknownProcessor,date:dateProcessor,enum:enumProcessor,literal:literalProcessor,nan:nanProcessor,template_literal:templateLiteralProcessor,file:fileProcessor,success:successProcessor,custom:customProcessor,function:functionProcessor,transform:transformProcessor,map:mapProcessor,set:setProcessor,array:arrayProcessor,object:objectProcessor,union:unionProcessor,intersection:intersectionProcessor,tuple:tupleProcessor,record:recordProcessor,nullable:nullableProcessor,nonoptional:nonoptionalProcessor,default:defaultProcessor,prefault:prefaultProcessor,catch:catchProcessor,pipe:pipeProcessor,readonly:readonlyProcessor,promise:promiseProcessor,optional:optionalProcessor,lazy:lazyProcessor}}});var init_json_schema=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema.js"(){"use strict"}});var init_core2=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/index.js"(){"use strict";init_core();init_parse();init_errors();init_schemas();init_checks();init_versions();init_util();init_regexes();init_locales();init_registries();init_doc();init_api();init_to_json_schema();init_json_schema()}});var init_checks2=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/checks.js"(){"use strict";init_core2()}});var iso_exports={};__export(iso_exports,{ZodISODate:()=>ZodISODate,ZodISODateTime:()=>ZodISODateTime,ZodISODuration:()=>ZodISODuration,ZodISOTime:()=>ZodISOTime,date:()=>date2,datetime:()=>datetime2,duration:()=>duration2,time:()=>time2});function datetime2(params){return _isoDateTime(ZodISODateTime,params)}function date2(params){return _isoDate(ZodISODate,params)}function time2(params){return _isoTime(ZodISOTime,params)}function duration2(params){return _isoDuration(ZodISODuration,params)}var ZodISODateTime,ZodISODate,ZodISOTime,ZodISODuration,init_iso=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/iso.js"(){"use strict";init_core2();init_schemas2();ZodISODateTime=$constructor("ZodISODateTime",(inst,def)=>{$ZodISODateTime.init(inst,def),ZodStringFormat.init(inst,def)});ZodISODate=$constructor("ZodISODate",(inst,def)=>{$ZodISODate.init(inst,def),ZodStringFormat.init(inst,def)});ZodISOTime=$constructor("ZodISOTime",(inst,def)=>{$ZodISOTime.init(inst,def),ZodStringFormat.init(inst,def)});ZodISODuration=$constructor("ZodISODuration",(inst,def)=>{$ZodISODuration.init(inst,def),ZodStringFormat.init(inst,def)})}});var initializer2,ZodRealError,init_errors2=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/errors.js"(){"use strict";init_core2();init_core2();init_util();initializer2=(inst,issues)=>{$ZodError.init(inst,issues),inst.name="ZodError",Object.defineProperties(inst,{format:{value:mapper=>formatError(inst,mapper)},flatten:{value:mapper=>flattenError(inst,mapper)},addIssue:{value:issue2=>{inst.issues.push(issue2),inst.message=JSON.stringify(inst.issues,jsonStringifyReplacer,2)}},addIssues:{value:issues2=>{inst.issues.push(...issues2),inst.message=JSON.stringify(inst.issues,jsonStringifyReplacer,2)}},isEmpty:{get(){return inst.issues.length===0}}})},ZodRealError=$constructor("ZodError",initializer2,{Parent:Error})}});var parse2,parseAsync2,safeParse2,safeParseAsync2,encode,decode,encodeAsync,decodeAsync,safeEncode,safeDecode,safeEncodeAsync,safeDecodeAsync,init_parse2=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/parse.js"(){"use strict";init_core2();init_errors2();parse2=_parse(ZodRealError),parseAsync2=_parseAsync(ZodRealError),safeParse2=_safeParse(ZodRealError),safeParseAsync2=_safeParseAsync(ZodRealError),encode=_encode(ZodRealError),decode=_decode(ZodRealError),encodeAsync=_encodeAsync(ZodRealError),decodeAsync=_decodeAsync(ZodRealError),safeEncode=_safeEncode(ZodRealError),safeDecode=_safeDecode(ZodRealError),safeEncodeAsync=_safeEncodeAsync(ZodRealError),safeDecodeAsync=_safeDecodeAsync(ZodRealError)}});function _installLazyMethods(inst,group,methods){let proto=Object.getPrototypeOf(inst),installed=_installedGroups.get(proto);if(installed||(installed=new Set,_installedGroups.set(proto,installed)),!installed.has(group)){installed.add(group);for(let key in methods){let fn=methods[key];Object.defineProperty(proto,key,{configurable:!0,enumerable:!1,get(){let bound=fn.bind(this);return Object.defineProperty(this,key,{configurable:!0,writable:!0,enumerable:!0,value:bound}),bound},set(v){Object.defineProperty(this,key,{configurable:!0,writable:!0,enumerable:!0,value:v})}})}}}function string2(params){return _string(ZodString,params)}function email2(params){return _email(ZodEmail,params)}function url(params){return _url(ZodURL,params)}function number2(params){return _number(ZodNumber,params)}function int(params){return _int(ZodNumberFormat,params)}function boolean2(params){return _boolean(ZodBoolean,params)}function _null3(params){return _null2(ZodNull,params)}function any(){return _any(ZodAny)}function unknown(){return _unknown(ZodUnknown)}function never(params){return _never(ZodNever,params)}function array(element,params){return _array(ZodArray,element,params)}function object(shape,params){let def={type:"object",shape:shape??{},...util_exports.normalizeParams(params)};return new ZodObject(def)}function looseObject(shape,params){return new ZodObject({type:"object",shape,catchall:unknown(),...util_exports.normalizeParams(params)})}function union(options,params){return new ZodUnion({type:"union",options,...util_exports.normalizeParams(params)})}function discriminatedUnion(discriminator,options,params){return new ZodDiscriminatedUnion({type:"union",options,discriminator,...util_exports.normalizeParams(params)})}function intersection(left,right){return new ZodIntersection({type:"intersection",left,right})}function record(keyType,valueType,params){return!valueType||!valueType._zod?new ZodRecord({type:"record",keyType:string2(),valueType:keyType,...util_exports.normalizeParams(valueType)}):new ZodRecord({type:"record",keyType,valueType,...util_exports.normalizeParams(params)})}function _enum(values,params){let entries=Array.isArray(values)?Object.fromEntries(values.map(v=>[v,v])):values;return new ZodEnum({type:"enum",entries,...util_exports.normalizeParams(params)})}function literal(value,params){return new ZodLiteral({type:"literal",values:Array.isArray(value)?value:[value],...util_exports.normalizeParams(params)})}function transform(fn){return new ZodTransform({type:"transform",transform:fn})}function optional(innerType){return new ZodOptional({type:"optional",innerType})}function exactOptional(innerType){return new ZodExactOptional({type:"optional",innerType})}function nullable(innerType){return new ZodNullable({type:"nullable",innerType})}function _default(innerType,defaultValue){return new ZodDefault({type:"default",innerType,get defaultValue(){return typeof defaultValue=="function"?defaultValue():util_exports.shallowClone(defaultValue)}})}function prefault(innerType,defaultValue){return new ZodPrefault({type:"prefault",innerType,get defaultValue(){return typeof defaultValue=="function"?defaultValue():util_exports.shallowClone(defaultValue)}})}function nonoptional(innerType,params){return new ZodNonOptional({type:"nonoptional",innerType,...util_exports.normalizeParams(params)})}function _catch(innerType,catchValue){return new ZodCatch({type:"catch",innerType,catchValue:typeof catchValue=="function"?catchValue:()=>catchValue})}function pipe(in_,out){return new ZodPipe({type:"pipe",in:in_,out})}function readonly(innerType){return new ZodReadonly({type:"readonly",innerType})}function lazy(getter){return new ZodLazy({type:"lazy",getter})}function refine(fn,_params={}){return _refine(ZodCustom,fn,_params)}function superRefine(fn,params){return _superRefine(fn,params)}function preprocess(fn,schema2){return new ZodPreprocess({type:"pipe",in:transform(fn),out:schema2})}var _installedGroups,ZodType,_ZodString,ZodString,ZodStringFormat,ZodEmail,ZodGUID,ZodUUID,ZodURL,ZodEmoji,ZodNanoID,ZodCUID,ZodCUID2,ZodULID,ZodXID,ZodKSUID,ZodIPv4,ZodIPv6,ZodCIDRv4,ZodCIDRv6,ZodBase64,ZodBase64URL,ZodE164,ZodJWT,ZodNumber,ZodNumberFormat,ZodBoolean,ZodBigInt,ZodNull,ZodAny,ZodUnknown,ZodNever,ZodDate,ZodArray,ZodObject,ZodUnion,ZodDiscriminatedUnion,ZodIntersection,ZodRecord,ZodEnum,ZodLiteral,ZodTransform,ZodOptional,ZodExactOptional,ZodNullable,ZodDefault,ZodPrefault,ZodNonOptional,ZodCatch,ZodPipe,ZodPreprocess,ZodReadonly,ZodLazy,ZodCustom,init_schemas2=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js"(){"use strict";init_core2();init_core2();init_json_schema_processors();init_to_json_schema();init_checks2();init_iso();init_parse2();_installedGroups=new WeakMap;ZodType=$constructor("ZodType",(inst,def)=>($ZodType.init(inst,def),Object.assign(inst["~standard"],{jsonSchema:{input:createStandardJSONSchemaMethod(inst,"input"),output:createStandardJSONSchemaMethod(inst,"output")}}),inst.toJSONSchema=createToJSONSchemaMethod(inst,{}),inst.def=def,inst.type=def.type,Object.defineProperty(inst,"_def",{value:def}),inst.parse=(data,params)=>parse2(inst,data,params,{callee:inst.parse}),inst.safeParse=(data,params)=>safeParse2(inst,data,params),inst.parseAsync=async(data,params)=>parseAsync2(inst,data,params,{callee:inst.parseAsync}),inst.safeParseAsync=async(data,params)=>safeParseAsync2(inst,data,params),inst.spa=inst.safeParseAsync,inst.encode=(data,params)=>encode(inst,data,params),inst.decode=(data,params)=>decode(inst,data,params),inst.encodeAsync=async(data,params)=>encodeAsync(inst,data,params),inst.decodeAsync=async(data,params)=>decodeAsync(inst,data,params),inst.safeEncode=(data,params)=>safeEncode(inst,data,params),inst.safeDecode=(data,params)=>safeDecode(inst,data,params),inst.safeEncodeAsync=async(data,params)=>safeEncodeAsync(inst,data,params),inst.safeDecodeAsync=async(data,params)=>safeDecodeAsync(inst,data,params),_installLazyMethods(inst,"ZodType",{check(...chks){let def2=this.def;return this.clone(util_exports.mergeDefs(def2,{checks:[...def2.checks??[],...chks.map(ch=>typeof ch=="function"?{_zod:{check:ch,def:{check:"custom"},onattach:[]}}:ch)]}),{parent:!0})},with(...chks){return this.check(...chks)},clone(def2,params){return clone(this,def2,params)},brand(){return this},register(reg,meta2){return reg.add(this,meta2),this},refine(check,params){return this.check(refine(check,params))},superRefine(refinement,params){return this.check(superRefine(refinement,params))},overwrite(fn){return this.check(_overwrite(fn))},optional(){return optional(this)},exactOptional(){return exactOptional(this)},nullable(){return nullable(this)},nullish(){return optional(nullable(this))},nonoptional(params){return nonoptional(this,params)},array(){return array(this)},or(arg){return union([this,arg])},and(arg){return intersection(this,arg)},transform(tx){return pipe(this,transform(tx))},default(d){return _default(this,d)},prefault(d){return prefault(this,d)},catch(params){return _catch(this,params)},pipe(target){return pipe(this,target)},readonly(){return readonly(this)},describe(description){let cl=this.clone();return globalRegistry.add(cl,{description}),cl},meta(...args){if(args.length===0)return globalRegistry.get(this);let cl=this.clone();return globalRegistry.add(cl,args[0]),cl},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(fn){return fn(this)}}),Object.defineProperty(inst,"description",{get(){return globalRegistry.get(inst)?.description},configurable:!0}),inst)),_ZodString=$constructor("_ZodString",(inst,def)=>{$ZodString.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>stringProcessor(inst,ctx,json,params);let bag=inst._zod.bag;inst.format=bag.format??null,inst.minLength=bag.minimum??null,inst.maxLength=bag.maximum??null,_installLazyMethods(inst,"_ZodString",{regex(...args){return this.check(_regex(...args))},includes(...args){return this.check(_includes(...args))},startsWith(...args){return this.check(_startsWith(...args))},endsWith(...args){return this.check(_endsWith(...args))},min(...args){return this.check(_minLength(...args))},max(...args){return this.check(_maxLength(...args))},length(...args){return this.check(_length(...args))},nonempty(...args){return this.check(_minLength(1,...args))},lowercase(params){return this.check(_lowercase(params))},uppercase(params){return this.check(_uppercase(params))},trim(){return this.check(_trim())},normalize(...args){return this.check(_normalize(...args))},toLowerCase(){return this.check(_toLowerCase())},toUpperCase(){return this.check(_toUpperCase())},slugify(){return this.check(_slugify())}})}),ZodString=$constructor("ZodString",(inst,def)=>{$ZodString.init(inst,def),_ZodString.init(inst,def),inst.email=params=>inst.check(_email(ZodEmail,params)),inst.url=params=>inst.check(_url(ZodURL,params)),inst.jwt=params=>inst.check(_jwt(ZodJWT,params)),inst.emoji=params=>inst.check(_emoji2(ZodEmoji,params)),inst.guid=params=>inst.check(_guid(ZodGUID,params)),inst.uuid=params=>inst.check(_uuid(ZodUUID,params)),inst.uuidv4=params=>inst.check(_uuidv4(ZodUUID,params)),inst.uuidv6=params=>inst.check(_uuidv6(ZodUUID,params)),inst.uuidv7=params=>inst.check(_uuidv7(ZodUUID,params)),inst.nanoid=params=>inst.check(_nanoid(ZodNanoID,params)),inst.guid=params=>inst.check(_guid(ZodGUID,params)),inst.cuid=params=>inst.check(_cuid(ZodCUID,params)),inst.cuid2=params=>inst.check(_cuid2(ZodCUID2,params)),inst.ulid=params=>inst.check(_ulid(ZodULID,params)),inst.base64=params=>inst.check(_base64(ZodBase64,params)),inst.base64url=params=>inst.check(_base64url(ZodBase64URL,params)),inst.xid=params=>inst.check(_xid(ZodXID,params)),inst.ksuid=params=>inst.check(_ksuid(ZodKSUID,params)),inst.ipv4=params=>inst.check(_ipv4(ZodIPv4,params)),inst.ipv6=params=>inst.check(_ipv6(ZodIPv6,params)),inst.cidrv4=params=>inst.check(_cidrv4(ZodCIDRv4,params)),inst.cidrv6=params=>inst.check(_cidrv6(ZodCIDRv6,params)),inst.e164=params=>inst.check(_e164(ZodE164,params)),inst.datetime=params=>inst.check(datetime2(params)),inst.date=params=>inst.check(date2(params)),inst.time=params=>inst.check(time2(params)),inst.duration=params=>inst.check(duration2(params))});ZodStringFormat=$constructor("ZodStringFormat",(inst,def)=>{$ZodStringFormat.init(inst,def),_ZodString.init(inst,def)}),ZodEmail=$constructor("ZodEmail",(inst,def)=>{$ZodEmail.init(inst,def),ZodStringFormat.init(inst,def)});ZodGUID=$constructor("ZodGUID",(inst,def)=>{$ZodGUID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodUUID=$constructor("ZodUUID",(inst,def)=>{$ZodUUID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodURL=$constructor("ZodURL",(inst,def)=>{$ZodURL.init(inst,def),ZodStringFormat.init(inst,def)});ZodEmoji=$constructor("ZodEmoji",(inst,def)=>{$ZodEmoji.init(inst,def),ZodStringFormat.init(inst,def)}),ZodNanoID=$constructor("ZodNanoID",(inst,def)=>{$ZodNanoID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodCUID=$constructor("ZodCUID",(inst,def)=>{$ZodCUID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodCUID2=$constructor("ZodCUID2",(inst,def)=>{$ZodCUID2.init(inst,def),ZodStringFormat.init(inst,def)}),ZodULID=$constructor("ZodULID",(inst,def)=>{$ZodULID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodXID=$constructor("ZodXID",(inst,def)=>{$ZodXID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodKSUID=$constructor("ZodKSUID",(inst,def)=>{$ZodKSUID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodIPv4=$constructor("ZodIPv4",(inst,def)=>{$ZodIPv4.init(inst,def),ZodStringFormat.init(inst,def)}),ZodIPv6=$constructor("ZodIPv6",(inst,def)=>{$ZodIPv6.init(inst,def),ZodStringFormat.init(inst,def)}),ZodCIDRv4=$constructor("ZodCIDRv4",(inst,def)=>{$ZodCIDRv4.init(inst,def),ZodStringFormat.init(inst,def)}),ZodCIDRv6=$constructor("ZodCIDRv6",(inst,def)=>{$ZodCIDRv6.init(inst,def),ZodStringFormat.init(inst,def)}),ZodBase64=$constructor("ZodBase64",(inst,def)=>{$ZodBase64.init(inst,def),ZodStringFormat.init(inst,def)}),ZodBase64URL=$constructor("ZodBase64URL",(inst,def)=>{$ZodBase64URL.init(inst,def),ZodStringFormat.init(inst,def)}),ZodE164=$constructor("ZodE164",(inst,def)=>{$ZodE164.init(inst,def),ZodStringFormat.init(inst,def)}),ZodJWT=$constructor("ZodJWT",(inst,def)=>{$ZodJWT.init(inst,def),ZodStringFormat.init(inst,def)}),ZodNumber=$constructor("ZodNumber",(inst,def)=>{$ZodNumber.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>numberProcessor(inst,ctx,json,params),_installLazyMethods(inst,"ZodNumber",{gt(value,params){return this.check(_gt(value,params))},gte(value,params){return this.check(_gte(value,params))},min(value,params){return this.check(_gte(value,params))},lt(value,params){return this.check(_lt(value,params))},lte(value,params){return this.check(_lte(value,params))},max(value,params){return this.check(_lte(value,params))},int(params){return this.check(int(params))},safe(params){return this.check(int(params))},positive(params){return this.check(_gt(0,params))},nonnegative(params){return this.check(_gte(0,params))},negative(params){return this.check(_lt(0,params))},nonpositive(params){return this.check(_lte(0,params))},multipleOf(value,params){return this.check(_multipleOf(value,params))},step(value,params){return this.check(_multipleOf(value,params))},finite(){return this}});let bag=inst._zod.bag;inst.minValue=Math.max(bag.minimum??Number.NEGATIVE_INFINITY,bag.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,inst.maxValue=Math.min(bag.maximum??Number.POSITIVE_INFINITY,bag.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,inst.isInt=(bag.format??"").includes("int")||Number.isSafeInteger(bag.multipleOf??.5),inst.isFinite=!0,inst.format=bag.format??null});ZodNumberFormat=$constructor("ZodNumberFormat",(inst,def)=>{$ZodNumberFormat.init(inst,def),ZodNumber.init(inst,def)});ZodBoolean=$constructor("ZodBoolean",(inst,def)=>{$ZodBoolean.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>booleanProcessor(inst,ctx,json,params)});ZodBigInt=$constructor("ZodBigInt",(inst,def)=>{$ZodBigInt.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>bigintProcessor(inst,ctx,json,params),inst.gte=(value,params)=>inst.check(_gte(value,params)),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.gt=(value,params)=>inst.check(_gt(value,params)),inst.gte=(value,params)=>inst.check(_gte(value,params)),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.lt=(value,params)=>inst.check(_lt(value,params)),inst.lte=(value,params)=>inst.check(_lte(value,params)),inst.max=(value,params)=>inst.check(_lte(value,params)),inst.positive=params=>inst.check(_gt(BigInt(0),params)),inst.negative=params=>inst.check(_lt(BigInt(0),params)),inst.nonpositive=params=>inst.check(_lte(BigInt(0),params)),inst.nonnegative=params=>inst.check(_gte(BigInt(0),params)),inst.multipleOf=(value,params)=>inst.check(_multipleOf(value,params));let bag=inst._zod.bag;inst.minValue=bag.minimum??null,inst.maxValue=bag.maximum??null,inst.format=bag.format??null}),ZodNull=$constructor("ZodNull",(inst,def)=>{$ZodNull.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nullProcessor(inst,ctx,json,params)});ZodAny=$constructor("ZodAny",(inst,def)=>{$ZodAny.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>anyProcessor(inst,ctx,json,params)});ZodUnknown=$constructor("ZodUnknown",(inst,def)=>{$ZodUnknown.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>unknownProcessor(inst,ctx,json,params)});ZodNever=$constructor("ZodNever",(inst,def)=>{$ZodNever.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>neverProcessor(inst,ctx,json,params)});ZodDate=$constructor("ZodDate",(inst,def)=>{$ZodDate.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>dateProcessor(inst,ctx,json,params),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.max=(value,params)=>inst.check(_lte(value,params));let c=inst._zod.bag;inst.minDate=c.minimum?new Date(c.minimum):null,inst.maxDate=c.maximum?new Date(c.maximum):null}),ZodArray=$constructor("ZodArray",(inst,def)=>{$ZodArray.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>arrayProcessor(inst,ctx,json,params),inst.element=def.element,_installLazyMethods(inst,"ZodArray",{min(n,params){return this.check(_minLength(n,params))},nonempty(params){return this.check(_minLength(1,params))},max(n,params){return this.check(_maxLength(n,params))},length(n,params){return this.check(_length(n,params))},unwrap(){return this.element}})});ZodObject=$constructor("ZodObject",(inst,def)=>{$ZodObjectJIT.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>objectProcessor(inst,ctx,json,params),util_exports.defineLazy(inst,"shape",()=>def.shape),_installLazyMethods(inst,"ZodObject",{keyof(){return _enum(Object.keys(this._zod.def.shape))},catchall(catchall){return this.clone({...this._zod.def,catchall})},passthrough(){return this.clone({...this._zod.def,catchall:unknown()})},loose(){return this.clone({...this._zod.def,catchall:unknown()})},strict(){return this.clone({...this._zod.def,catchall:never()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(incoming){return util_exports.extend(this,incoming)},safeExtend(incoming){return util_exports.safeExtend(this,incoming)},merge(other){return util_exports.merge(this,other)},pick(mask){return util_exports.pick(this,mask)},omit(mask){return util_exports.omit(this,mask)},partial(...args){return util_exports.partial(ZodOptional,this,args[0])},required(...args){return util_exports.required(ZodNonOptional,this,args[0])}})});ZodUnion=$constructor("ZodUnion",(inst,def)=>{$ZodUnion.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>unionProcessor(inst,ctx,json,params),inst.options=def.options});ZodDiscriminatedUnion=$constructor("ZodDiscriminatedUnion",(inst,def)=>{ZodUnion.init(inst,def),$ZodDiscriminatedUnion.init(inst,def)});ZodIntersection=$constructor("ZodIntersection",(inst,def)=>{$ZodIntersection.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>intersectionProcessor(inst,ctx,json,params)});ZodRecord=$constructor("ZodRecord",(inst,def)=>{$ZodRecord.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>recordProcessor(inst,ctx,json,params),inst.keyType=def.keyType,inst.valueType=def.valueType});ZodEnum=$constructor("ZodEnum",(inst,def)=>{$ZodEnum.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>enumProcessor(inst,ctx,json,params),inst.enum=def.entries,inst.options=Object.values(def.entries);let keys=new Set(Object.keys(def.entries));inst.extract=(values,params)=>{let newEntries={};for(let value of values)if(keys.has(value))newEntries[value]=def.entries[value];else throw new Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...util_exports.normalizeParams(params),entries:newEntries})},inst.exclude=(values,params)=>{let newEntries={...def.entries};for(let value of values)if(keys.has(value))delete newEntries[value];else throw new Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...util_exports.normalizeParams(params),entries:newEntries})}});ZodLiteral=$constructor("ZodLiteral",(inst,def)=>{$ZodLiteral.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>literalProcessor(inst,ctx,json,params),inst.values=new Set(def.values),Object.defineProperty(inst,"value",{get(){if(def.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return def.values[0]}})});ZodTransform=$constructor("ZodTransform",(inst,def)=>{$ZodTransform.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>transformProcessor(inst,ctx,json,params),inst._zod.parse=(payload,_ctx)=>{if(_ctx.direction==="backward")throw new $ZodEncodeError(inst.constructor.name);payload.addIssue=issue2=>{if(typeof issue2=="string")payload.issues.push(util_exports.issue(issue2,payload.value,def));else{let _issue=issue2;_issue.fatal&&(_issue.continue=!1),_issue.code??(_issue.code="custom"),_issue.input??(_issue.input=payload.value),_issue.inst??(_issue.inst=inst),payload.issues.push(util_exports.issue(_issue))}};let output=def.transform(payload.value,payload);return output instanceof Promise?output.then(output2=>(payload.value=output2,payload.fallback=!0,payload)):(payload.value=output,payload.fallback=!0,payload)}});ZodOptional=$constructor("ZodOptional",(inst,def)=>{$ZodOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>optionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodExactOptional=$constructor("ZodExactOptional",(inst,def)=>{$ZodExactOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>optionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodNullable=$constructor("ZodNullable",(inst,def)=>{$ZodNullable.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nullableProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodDefault=$constructor("ZodDefault",(inst,def)=>{$ZodDefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>defaultProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeDefault=inst.unwrap});ZodPrefault=$constructor("ZodPrefault",(inst,def)=>{$ZodPrefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>prefaultProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodNonOptional=$constructor("ZodNonOptional",(inst,def)=>{$ZodNonOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nonoptionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodCatch=$constructor("ZodCatch",(inst,def)=>{$ZodCatch.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>catchProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeCatch=inst.unwrap});ZodPipe=$constructor("ZodPipe",(inst,def)=>{$ZodPipe.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>pipeProcessor(inst,ctx,json,params),inst.in=def.in,inst.out=def.out});ZodPreprocess=$constructor("ZodPreprocess",(inst,def)=>{ZodPipe.init(inst,def),$ZodPreprocess.init(inst,def)}),ZodReadonly=$constructor("ZodReadonly",(inst,def)=>{$ZodReadonly.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>readonlyProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodLazy=$constructor("ZodLazy",(inst,def)=>{$ZodLazy.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>lazyProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.getter()});ZodCustom=$constructor("ZodCustom",(inst,def)=>{$ZodCustom.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>customProcessor(inst,ctx,json,params)})}});var ZodIssueCode,ZodFirstPartyTypeKind,init_compat=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/compat.js"(){"use strict";ZodIssueCode={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={})}});var coerce_exports={};__export(coerce_exports,{bigint:()=>bigint2,boolean:()=>boolean3,date:()=>date3,number:()=>number3,string:()=>string3});function string3(params){return _coercedString(ZodString,params)}function number3(params){return _coercedNumber(ZodNumber,params)}function boolean3(params){return _coercedBoolean(ZodBoolean,params)}function bigint2(params){return _coercedBigint(ZodBigInt,params)}function date3(params){return _coercedDate(ZodDate,params)}var init_coerce=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/coerce.js"(){"use strict";init_core2();init_schemas2()}});var init_external=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js"(){"use strict";init_core2();init_schemas2();init_checks2();init_errors2();init_parse2();init_compat();init_core2();init_en();init_core2();init_json_schema_processors();init_locales();init_iso();init_coerce();config(en_default())}});var init_classic=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/index.js"(){"use strict";init_external()}});var init_v4=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/index.js"(){"use strict";init_classic()}});var LATEST_PROTOCOL_VERSION,DEFAULT_NEGOTIATED_PROTOCOL_VERSION,SUPPORTED_PROTOCOL_VERSIONS,RELATED_TASK_META_KEY,PROTOCOL_VERSION_META_KEY,CLIENT_INFO_META_KEY,SERVER_INFO_META_KEY,CLIENT_CAPABILITIES_META_KEY,SUBSCRIPTION_ID_META_KEY,LOG_LEVEL_META_KEY,JSONRPC_VERSION,INVALID_PARAMS,JSONValueSchema,JSONObjectSchema,JSONArraySchema,ProgressTokenSchema,CursorSchema,TaskMetadataSchema,RelatedTaskMetadataSchema,RequestMetaSchema,BaseRequestParamsSchema,TaskAugmentedRequestParamsSchema,RequestSchema,NotificationsParamsSchema,NotificationSchema,ResultMetaObjectSchema,ResultSchema,RequestIdSchema,JSONRPCRequestSchema,JSONRPCNotificationSchema,JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema,JSONRPCMessageSchema,JSONRPCResponseSchema,EmptyResultSchema,CancelledNotificationParamsSchema,CancelledNotificationSchema,IconSchema,IconsSchema,BaseMetadataSchema,ImplementationSchema,FormElicitationCapabilitySchema,ElicitationCapabilitySchema,ClientTasksCapabilitySchema,ServerTasksCapabilitySchema,ClientCapabilitiesSchema,InitializeRequestParamsSchema,InitializeRequestSchema,ServerCapabilitiesSchema,InitializeResultSchema,InitializedNotificationSchema,DiscoverRequestSchema,DiscoverResultSchema,PingRequestSchema,ProgressSchema,ProgressNotificationParamsSchema,ProgressNotificationSchema,PaginatedRequestParamsSchema,PaginatedRequestSchema,PaginatedResultSchema,ResourceContentsSchema,TextResourceContentsSchema,Base64Schema,BlobResourceContentsSchema,RoleSchema,AnnotationsSchema,ResourceSchema,ResourceTemplateSchema,ListResourcesRequestSchema,ListResourcesResultSchema,ListResourceTemplatesRequestSchema,ListResourceTemplatesResultSchema,ResourceRequestParamsSchema,ReadResourceRequestParamsSchema,ReadResourceRequestSchema,ReadResourceResultSchema,ResourceListChangedNotificationSchema,SubscribeRequestParamsSchema,SubscribeRequestSchema,UnsubscribeRequestParamsSchema,UnsubscribeRequestSchema,SubscriptionFilterSchema,SubscriptionsListenRequestParamsSchema,SubscriptionsListenRequestSchema,SubscriptionsAcknowledgedNotificationParamsSchema,SubscriptionsAcknowledgedNotificationSchema,SubscriptionsListenResultMetaSchema,SubscriptionsListenResultSchema,ResourceUpdatedNotificationParamsSchema,ResourceUpdatedNotificationSchema,PromptArgumentSchema,PromptSchema,ListPromptsRequestSchema,ListPromptsResultSchema,GetPromptRequestParamsSchema,GetPromptRequestSchema,TextContentSchema,ImageContentSchema,AudioContentSchema,ToolUseContentSchema,EmbeddedResourceSchema,ResourceLinkSchema,ContentBlockSchema,PromptMessageSchema,GetPromptResultSchema,PromptListChangedNotificationSchema,ToolAnnotationsSchema,ToolExecutionSchema,ToolSchema,ListToolsRequestSchema,ListToolsResultSchema,CallToolResultSchema,CompatibilityCallToolResultSchema,CallToolRequestParamsSchema,CallToolRequestSchema,ToolListChangedNotificationSchema,ListChangedOptionsBaseSchema,LoggingLevelSchema,SetLevelRequestParamsSchema,SetLevelRequestSchema,LoggingMessageNotificationParamsSchema,LoggingMessageNotificationSchema,ModelHintSchema,ModelPreferencesSchema,ToolChoiceSchema,ToolResultContentSchema,SamplingContentSchema,SamplingMessageContentBlockSchema,SamplingMessageSchema,CreateMessageRequestParamsSchema,CreateMessageRequestSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,BooleanSchemaSchema,StringSchemaSchema,NumberSchemaSchema,UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema,LegacyTitledEnumSchemaSchema,SingleSelectEnumSchemaSchema,UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema,MultiSelectEnumSchemaSchema,EnumSchemaSchema,PrimitiveSchemaDefinitionSchema,ElicitRequestFormParamsSchema,ElicitRequestURLParamsSchema,ElicitRequestParamsSchema,ElicitRequestSchema,ElicitationCompleteNotificationParamsSchema,ElicitationCompleteNotificationSchema,ElicitResultSchema,ResourceTemplateReferenceSchema,PromptReferenceSchema,CompleteRequestParamsSchema,CompleteRequestSchema,CompleteResultSchema,RootSchema,ListRootsRequestSchema,ListRootsResultSchema,RootsListChangedNotificationSchema,TaskCreationParamsSchema,TaskStatusSchema,TaskSchema,CreateTaskResultSchema,TaskStatusNotificationParamsSchema,TaskStatusNotificationSchema,GetTaskRequestSchema,GetTaskResultSchema,GetTaskPayloadRequestSchema,GetTaskPayloadResultSchema,ListTasksRequestSchema,ListTasksResultSchema,CancelTaskRequestSchema,CancelTaskResultSchema,ClientRequestSchema,ClientNotificationSchema,ClientResultSchema,ServerRequestSchema,ServerNotificationSchema,ServerResultSchema,SafeUrlSchema,OAuthProtectedResourceMetadataSchema,OAuthMetadataSchema,OpenIdProviderMetadataSchema,OpenIdProviderDiscoveryMetadataSchema,OAuthTokensSchema,IdJagTokenExchangeResponseSchema,OAuthErrorResponseSchema,OptionalSafeUrlSchema,OAuthClientMetadataSchema,OAuthClientInformationSchema,OAuthClientInformationFullSchema,OAuthClientRegistrationErrorSchema,OAuthTokenRevocationRequestSchema,init_auth_CUe6YdwF=__esm({"../../node_modules/.pnpm/@modelcontextprotocol+core@2.0.0/node_modules/@modelcontextprotocol/core/dist/auth-CUe6YdwF.mjs"(){"use strict";init_v4();LATEST_PROTOCOL_VERSION="2025-11-25",DEFAULT_NEGOTIATED_PROTOCOL_VERSION="2025-03-26",SUPPORTED_PROTOCOL_VERSIONS=[LATEST_PROTOCOL_VERSION,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],RELATED_TASK_META_KEY="io.modelcontextprotocol/related-task",PROTOCOL_VERSION_META_KEY="io.modelcontextprotocol/protocolVersion",CLIENT_INFO_META_KEY="io.modelcontextprotocol/clientInfo",SERVER_INFO_META_KEY="io.modelcontextprotocol/serverInfo",CLIENT_CAPABILITIES_META_KEY="io.modelcontextprotocol/clientCapabilities",SUBSCRIPTION_ID_META_KEY="io.modelcontextprotocol/subscriptionId",LOG_LEVEL_META_KEY="io.modelcontextprotocol/logLevel",JSONRPC_VERSION="2.0",INVALID_PARAMS=-32602,JSONValueSchema=lazy(()=>union([string2(),number2(),boolean2(),_null3(),record(string2(),JSONValueSchema),array(JSONValueSchema)])),JSONObjectSchema=record(string2(),JSONValueSchema),JSONArraySchema=array(JSONValueSchema),ProgressTokenSchema=union([string2(),number2().int()]),CursorSchema=string2(),TaskMetadataSchema=object({ttl:number2().optional()}),RelatedTaskMetadataSchema=object({taskId:string2()}),RequestMetaSchema=looseObject({progressToken:ProgressTokenSchema.optional(),[RELATED_TASK_META_KEY]:RelatedTaskMetadataSchema.optional()}),BaseRequestParamsSchema=object({_meta:RequestMetaSchema.optional()}),TaskAugmentedRequestParamsSchema=BaseRequestParamsSchema.extend({task:TaskMetadataSchema.optional()}),RequestSchema=object({method:string2(),params:BaseRequestParamsSchema.loose().optional()}),NotificationsParamsSchema=object({_meta:RequestMetaSchema.optional()}),NotificationSchema=object({method:string2(),params:NotificationsParamsSchema.loose().optional()}),ResultMetaObjectSchema=looseObject({get[SERVER_INFO_META_KEY](){return ImplementationSchema.optional().catch(void 0)}}),ResultSchema=looseObject({_meta:ResultMetaObjectSchema.optional()}),RequestIdSchema=union([string2(),number2().int()]),JSONRPCRequestSchema=object({jsonrpc:literal(JSONRPC_VERSION),id:RequestIdSchema,...RequestSchema.shape}).strict(),JSONRPCNotificationSchema=object({jsonrpc:literal(JSONRPC_VERSION),...NotificationSchema.shape}).strict(),JSONRPCResultResponseSchema=object({jsonrpc:literal(JSONRPC_VERSION),id:RequestIdSchema,result:ResultSchema}).strict(),JSONRPCErrorResponseSchema=object({jsonrpc:literal(JSONRPC_VERSION),id:RequestIdSchema.optional(),error:object({code:number2().int(),message:string2(),data:unknown().optional()})}).strict(),JSONRPCMessageSchema=union([JSONRPCRequestSchema,JSONRPCNotificationSchema,JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),JSONRPCResponseSchema=union([JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),EmptyResultSchema=ResultSchema.strict(),CancelledNotificationParamsSchema=NotificationsParamsSchema.extend({requestId:RequestIdSchema.optional(),reason:string2().optional()}),CancelledNotificationSchema=NotificationSchema.extend({method:literal("notifications/cancelled"),params:CancelledNotificationParamsSchema}),IconSchema=object({src:string2(),mimeType:string2().optional(),sizes:array(string2()).optional(),theme:_enum(["light","dark"]).optional()}),IconsSchema=object({icons:array(IconSchema).optional()}),BaseMetadataSchema=object({name:string2(),title:string2().optional()}),ImplementationSchema=BaseMetadataSchema.extend({...BaseMetadataSchema.shape,...IconsSchema.shape,version:string2(),websiteUrl:string2().optional(),description:string2().optional()}),FormElicitationCapabilitySchema=intersection(object({applyDefaults:boolean2().optional()}),JSONObjectSchema),ElicitationCapabilitySchema=preprocess(value=>value&&typeof value=="object"&&!Array.isArray(value)&&Object.keys(value).length===0?{form:{}}:value,intersection(object({form:FormElicitationCapabilitySchema.optional(),url:JSONObjectSchema.optional()}),JSONObjectSchema.optional())),ClientTasksCapabilitySchema=looseObject({list:JSONObjectSchema.optional(),cancel:JSONObjectSchema.optional(),requests:looseObject({sampling:looseObject({createMessage:JSONObjectSchema.optional()}).optional(),elicitation:looseObject({create:JSONObjectSchema.optional()}).optional()}).optional()}),ServerTasksCapabilitySchema=looseObject({list:JSONObjectSchema.optional(),cancel:JSONObjectSchema.optional(),requests:looseObject({tools:looseObject({call:JSONObjectSchema.optional()}).optional()}).optional()}),ClientCapabilitiesSchema=object({experimental:record(string2(),JSONObjectSchema).optional(),sampling:object({context:JSONObjectSchema.optional(),tools:JSONObjectSchema.optional()}).optional(),elicitation:ElicitationCapabilitySchema.optional(),roots:object({listChanged:boolean2().optional()}).optional(),tasks:ClientTasksCapabilitySchema.optional(),extensions:record(string2(),JSONObjectSchema).optional()}),InitializeRequestParamsSchema=BaseRequestParamsSchema.extend({protocolVersion:string2(),capabilities:ClientCapabilitiesSchema,clientInfo:ImplementationSchema}),InitializeRequestSchema=RequestSchema.extend({method:literal("initialize"),params:InitializeRequestParamsSchema}),ServerCapabilitiesSchema=object({experimental:record(string2(),JSONObjectSchema).optional(),logging:JSONObjectSchema.optional(),completions:JSONObjectSchema.optional(),prompts:object({listChanged:boolean2().optional()}).optional(),resources:object({subscribe:boolean2().optional(),listChanged:boolean2().optional()}).optional(),tools:object({listChanged:boolean2().optional()}).optional(),tasks:ServerTasksCapabilitySchema.optional(),extensions:record(string2(),JSONObjectSchema).optional()}),InitializeResultSchema=ResultSchema.extend({protocolVersion:string2(),capabilities:ServerCapabilitiesSchema,serverInfo:ImplementationSchema,instructions:string2().optional()}),InitializedNotificationSchema=NotificationSchema.extend({method:literal("notifications/initialized"),params:NotificationsParamsSchema.optional()}),DiscoverRequestSchema=RequestSchema.extend({method:literal("server/discover"),params:BaseRequestParamsSchema.optional()}),DiscoverResultSchema=ResultSchema.extend({supportedVersions:array(string2()),capabilities:ServerCapabilitiesSchema,instructions:string2().optional()}),PingRequestSchema=RequestSchema.extend({method:literal("ping"),params:BaseRequestParamsSchema.optional()}),ProgressSchema=object({progress:number2(),total:optional(number2()),message:optional(string2())}),ProgressNotificationParamsSchema=object({...NotificationsParamsSchema.shape,...ProgressSchema.shape,progressToken:ProgressTokenSchema}),ProgressNotificationSchema=NotificationSchema.extend({method:literal("notifications/progress"),params:ProgressNotificationParamsSchema}),PaginatedRequestParamsSchema=BaseRequestParamsSchema.extend({cursor:CursorSchema.optional()}),PaginatedRequestSchema=RequestSchema.extend({params:PaginatedRequestParamsSchema.optional()}),PaginatedResultSchema=ResultSchema.extend({nextCursor:CursorSchema.optional()}),ResourceContentsSchema=object({uri:string2(),mimeType:optional(string2()),_meta:record(string2(),unknown()).optional()}),TextResourceContentsSchema=ResourceContentsSchema.extend({text:string2()}),Base64Schema=string2().refine(val=>{try{return atob(val),!0}catch{return!1}},{message:"Invalid Base64 string"}),BlobResourceContentsSchema=ResourceContentsSchema.extend({blob:Base64Schema}),RoleSchema=_enum(["user","assistant"]),AnnotationsSchema=object({audience:array(RoleSchema).optional(),priority:number2().min(0).max(1).optional(),lastModified:iso_exports.datetime({offset:!0}).optional()}),ResourceSchema=object({...BaseMetadataSchema.shape,...IconsSchema.shape,uri:string2(),description:optional(string2()),mimeType:optional(string2()),size:optional(number2()),annotations:AnnotationsSchema.optional(),_meta:optional(looseObject({}))}),ResourceTemplateSchema=object({...BaseMetadataSchema.shape,...IconsSchema.shape,uriTemplate:string2(),description:optional(string2()),mimeType:optional(string2()),annotations:AnnotationsSchema.optional(),_meta:optional(looseObject({}))}),ListResourcesRequestSchema=PaginatedRequestSchema.extend({method:literal("resources/list")}),ListResourcesResultSchema=PaginatedResultSchema.extend({resources:array(ResourceSchema)}),ListResourceTemplatesRequestSchema=PaginatedRequestSchema.extend({method:literal("resources/templates/list")}),ListResourceTemplatesResultSchema=PaginatedResultSchema.extend({resourceTemplates:array(ResourceTemplateSchema)}),ResourceRequestParamsSchema=BaseRequestParamsSchema.extend({uri:string2()}),ReadResourceRequestParamsSchema=ResourceRequestParamsSchema,ReadResourceRequestSchema=RequestSchema.extend({method:literal("resources/read"),params:ReadResourceRequestParamsSchema}),ReadResourceResultSchema=ResultSchema.extend({contents:array(union([TextResourceContentsSchema,BlobResourceContentsSchema]))}),ResourceListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/resources/list_changed"),params:NotificationsParamsSchema.optional()}),SubscribeRequestParamsSchema=ResourceRequestParamsSchema,SubscribeRequestSchema=RequestSchema.extend({method:literal("resources/subscribe"),params:SubscribeRequestParamsSchema}),UnsubscribeRequestParamsSchema=ResourceRequestParamsSchema,UnsubscribeRequestSchema=RequestSchema.extend({method:literal("resources/unsubscribe"),params:UnsubscribeRequestParamsSchema}),SubscriptionFilterSchema=object({toolsListChanged:boolean2().optional(),promptsListChanged:boolean2().optional(),resourcesListChanged:boolean2().optional(),resourceSubscriptions:array(string2()).optional()}),SubscriptionsListenRequestParamsSchema=BaseRequestParamsSchema.extend({notifications:SubscriptionFilterSchema}),SubscriptionsListenRequestSchema=RequestSchema.extend({method:literal("subscriptions/listen"),params:SubscriptionsListenRequestParamsSchema}),SubscriptionsAcknowledgedNotificationParamsSchema=NotificationsParamsSchema.extend({notifications:SubscriptionFilterSchema}),SubscriptionsAcknowledgedNotificationSchema=NotificationSchema.extend({method:literal("notifications/subscriptions/acknowledged"),params:SubscriptionsAcknowledgedNotificationParamsSchema}),SubscriptionsListenResultMetaSchema=ResultMetaObjectSchema.extend({[SUBSCRIPTION_ID_META_KEY]:RequestIdSchema}),SubscriptionsListenResultSchema=ResultSchema.extend({_meta:SubscriptionsListenResultMetaSchema}),ResourceUpdatedNotificationParamsSchema=NotificationsParamsSchema.extend({uri:string2()}),ResourceUpdatedNotificationSchema=NotificationSchema.extend({method:literal("notifications/resources/updated"),params:ResourceUpdatedNotificationParamsSchema}),PromptArgumentSchema=object({name:string2(),description:optional(string2()),required:optional(boolean2())}),PromptSchema=object({...BaseMetadataSchema.shape,...IconsSchema.shape,description:optional(string2()),arguments:optional(array(PromptArgumentSchema)),_meta:optional(looseObject({}))}),ListPromptsRequestSchema=PaginatedRequestSchema.extend({method:literal("prompts/list")}),ListPromptsResultSchema=PaginatedResultSchema.extend({prompts:array(PromptSchema)}),GetPromptRequestParamsSchema=BaseRequestParamsSchema.extend({name:string2(),arguments:record(string2(),string2()).optional()}),GetPromptRequestSchema=RequestSchema.extend({method:literal("prompts/get"),params:GetPromptRequestParamsSchema}),TextContentSchema=object({type:literal("text"),text:string2(),annotations:AnnotationsSchema.optional(),_meta:record(string2(),unknown()).optional()}),ImageContentSchema=object({type:literal("image"),data:Base64Schema,mimeType:string2(),annotations:AnnotationsSchema.optional(),_meta:record(string2(),unknown()).optional()}),AudioContentSchema=object({type:literal("audio"),data:Base64Schema,mimeType:string2(),annotations:AnnotationsSchema.optional(),_meta:record(string2(),unknown()).optional()}),ToolUseContentSchema=object({type:literal("tool_use"),name:string2(),id:string2(),input:record(string2(),unknown()),_meta:record(string2(),unknown()).optional()}),EmbeddedResourceSchema=object({type:literal("resource"),resource:union([TextResourceContentsSchema,BlobResourceContentsSchema]),annotations:AnnotationsSchema.optional(),_meta:record(string2(),unknown()).optional()}),ResourceLinkSchema=ResourceSchema.extend({type:literal("resource_link")}),ContentBlockSchema=union([TextContentSchema,ImageContentSchema,AudioContentSchema,ResourceLinkSchema,EmbeddedResourceSchema]),PromptMessageSchema=object({role:RoleSchema,content:ContentBlockSchema}),GetPromptResultSchema=ResultSchema.extend({description:string2().optional(),messages:array(PromptMessageSchema)}),PromptListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/prompts/list_changed"),params:NotificationsParamsSchema.optional()}),ToolAnnotationsSchema=object({title:string2().optional(),readOnlyHint:boolean2().optional(),destructiveHint:boolean2().optional(),idempotentHint:boolean2().optional(),openWorldHint:boolean2().optional()}),ToolExecutionSchema=object({taskSupport:_enum(["required","optional","forbidden"]).optional()}),ToolSchema=object({...BaseMetadataSchema.shape,...IconsSchema.shape,description:string2().optional(),inputSchema:object({type:literal("object"),properties:record(string2(),JSONValueSchema).optional(),required:array(string2()).optional()}).catchall(unknown()),outputSchema:looseObject({$schema:string2().optional()}).optional(),annotations:ToolAnnotationsSchema.optional(),execution:ToolExecutionSchema.optional(),_meta:record(string2(),unknown()).optional()}),ListToolsRequestSchema=PaginatedRequestSchema.extend({method:literal("tools/list")}),ListToolsResultSchema=PaginatedResultSchema.extend({tools:array(ToolSchema)}),CallToolResultSchema=ResultSchema.extend({content:array(ContentBlockSchema).default([]),structuredContent:unknown().optional(),isError:boolean2().optional()}),CompatibilityCallToolResultSchema=CallToolResultSchema.or(ResultSchema.extend({toolResult:unknown()})),CallToolRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({name:string2(),arguments:record(string2(),unknown()).optional()}),CallToolRequestSchema=RequestSchema.extend({method:literal("tools/call"),params:CallToolRequestParamsSchema}),ToolListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/tools/list_changed"),params:NotificationsParamsSchema.optional()}),ListChangedOptionsBaseSchema=object({autoRefresh:boolean2().default(!0),debounceMs:number2().int().nonnegative().default(300)}),LoggingLevelSchema=_enum(["debug","info","notice","warning","error","critical","alert","emergency"]),SetLevelRequestParamsSchema=BaseRequestParamsSchema.extend({level:LoggingLevelSchema}),SetLevelRequestSchema=RequestSchema.extend({method:literal("logging/setLevel"),params:SetLevelRequestParamsSchema}),LoggingMessageNotificationParamsSchema=NotificationsParamsSchema.extend({level:LoggingLevelSchema,logger:string2().optional(),data:unknown()}),LoggingMessageNotificationSchema=NotificationSchema.extend({method:literal("notifications/message"),params:LoggingMessageNotificationParamsSchema}),ModelHintSchema=object({name:string2().optional()}),ModelPreferencesSchema=object({hints:array(ModelHintSchema).optional(),costPriority:number2().min(0).max(1).optional(),speedPriority:number2().min(0).max(1).optional(),intelligencePriority:number2().min(0).max(1).optional()}),ToolChoiceSchema=object({mode:_enum(["auto","required","none"]).optional()}),ToolResultContentSchema=object({type:literal("tool_result"),toolUseId:string2().describe("The unique identifier for the corresponding tool call."),content:array(ContentBlockSchema),structuredContent:unknown().optional(),isError:boolean2().optional(),_meta:record(string2(),unknown()).optional()}),SamplingContentSchema=discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema]),SamplingMessageContentBlockSchema=discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema,ToolUseContentSchema,ToolResultContentSchema]),SamplingMessageSchema=object({role:RoleSchema,content:union([SamplingMessageContentBlockSchema,array(SamplingMessageContentBlockSchema)]),_meta:record(string2(),unknown()).optional()}),CreateMessageRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({messages:array(SamplingMessageSchema),modelPreferences:ModelPreferencesSchema.optional(),systemPrompt:string2().optional(),includeContext:_enum(["none","thisServer","allServers"]).optional(),temperature:number2().optional(),maxTokens:number2().int(),stopSequences:array(string2()).optional(),metadata:JSONObjectSchema.optional(),tools:array(ToolSchema).optional(),toolChoice:ToolChoiceSchema.optional()}),CreateMessageRequestSchema=RequestSchema.extend({method:literal("sampling/createMessage"),params:CreateMessageRequestParamsSchema}),CreateMessageResultSchema=ResultSchema.extend({model:string2(),stopReason:optional(_enum(["endTurn","stopSequence","maxTokens"]).or(string2())),role:RoleSchema,content:SamplingContentSchema}),CreateMessageResultWithToolsSchema=ResultSchema.extend({model:string2(),stopReason:optional(_enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(string2())),role:RoleSchema,content:union([SamplingMessageContentBlockSchema,array(SamplingMessageContentBlockSchema)])}),BooleanSchemaSchema=object({type:literal("boolean"),title:string2().optional(),description:string2().optional(),default:boolean2().optional()}),StringSchemaSchema=object({type:literal("string"),title:string2().optional(),description:string2().optional(),minLength:number2().optional(),maxLength:number2().optional(),format:_enum(["email","uri","date","date-time"]).optional(),default:string2().optional()}),NumberSchemaSchema=object({type:_enum(["number","integer"]),title:string2().optional(),description:string2().optional(),minimum:number2().optional(),maximum:number2().optional(),default:number2().optional()}),UntitledSingleSelectEnumSchemaSchema=object({type:literal("string"),title:string2().optional(),description:string2().optional(),enum:array(string2()),default:string2().optional()}),TitledSingleSelectEnumSchemaSchema=object({type:literal("string"),title:string2().optional(),description:string2().optional(),oneOf:array(object({const:string2(),title:string2()})),default:string2().optional()}),LegacyTitledEnumSchemaSchema=object({type:literal("string"),title:string2().optional(),description:string2().optional(),enum:array(string2()),enumNames:array(string2()).optional(),default:string2().optional()}),SingleSelectEnumSchemaSchema=union([UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema]),UntitledMultiSelectEnumSchemaSchema=object({type:literal("array"),title:string2().optional(),description:string2().optional(),minItems:number2().optional(),maxItems:number2().optional(),items:object({type:literal("string"),enum:array(string2())}),default:array(string2()).optional()}),TitledMultiSelectEnumSchemaSchema=object({type:literal("array"),title:string2().optional(),description:string2().optional(),minItems:number2().optional(),maxItems:number2().optional(),items:object({anyOf:array(object({const:string2(),title:string2()}))}),default:array(string2()).optional()}),MultiSelectEnumSchemaSchema=union([UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema]),EnumSchemaSchema=union([LegacyTitledEnumSchemaSchema,SingleSelectEnumSchemaSchema,MultiSelectEnumSchemaSchema]),PrimitiveSchemaDefinitionSchema=union([EnumSchemaSchema,BooleanSchemaSchema,StringSchemaSchema,NumberSchemaSchema]),ElicitRequestFormParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal("form").optional(),message:string2(),requestedSchema:object({type:literal("object"),properties:record(string2(),PrimitiveSchemaDefinitionSchema),required:array(string2()).optional()}).catchall(unknown())}),ElicitRequestURLParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal("url"),message:string2(),elicitationId:string2(),url:string2().url()}),ElicitRequestParamsSchema=union([ElicitRequestFormParamsSchema,ElicitRequestURLParamsSchema]),ElicitRequestSchema=RequestSchema.extend({method:literal("elicitation/create"),params:ElicitRequestParamsSchema}),ElicitationCompleteNotificationParamsSchema=NotificationsParamsSchema.extend({elicitationId:string2()}),ElicitationCompleteNotificationSchema=NotificationSchema.extend({method:literal("notifications/elicitation/complete"),params:ElicitationCompleteNotificationParamsSchema}),ElicitResultSchema=ResultSchema.extend({action:_enum(["accept","decline","cancel"]),content:preprocess(val=>val===null?void 0:val,record(string2(),union([string2(),number2(),boolean2(),array(string2())])).optional())}),ResourceTemplateReferenceSchema=object({type:literal("ref/resource"),uri:string2()}),PromptReferenceSchema=object({type:literal("ref/prompt"),name:string2()}),CompleteRequestParamsSchema=BaseRequestParamsSchema.extend({ref:union([PromptReferenceSchema,ResourceTemplateReferenceSchema]),argument:object({name:string2(),value:string2()}),context:object({arguments:record(string2(),string2()).optional()}).optional()}),CompleteRequestSchema=RequestSchema.extend({method:literal("completion/complete"),params:CompleteRequestParamsSchema}),CompleteResultSchema=ResultSchema.extend({completion:looseObject({values:array(string2()).max(100),total:optional(number2().int()),hasMore:optional(boolean2())})}),RootSchema=object({uri:string2().startsWith("file://"),name:string2().optional(),_meta:record(string2(),unknown()).optional()}),ListRootsRequestSchema=RequestSchema.extend({method:literal("roots/list"),params:BaseRequestParamsSchema.optional()}),ListRootsResultSchema=ResultSchema.extend({roots:array(RootSchema)}),RootsListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/roots/list_changed"),params:NotificationsParamsSchema.optional()}),TaskCreationParamsSchema=looseObject({ttl:number2().optional(),pollInterval:number2().optional()}),TaskStatusSchema=_enum(["working","input_required","completed","failed","cancelled"]),TaskSchema=object({taskId:string2(),status:TaskStatusSchema,ttl:union([number2(),_null3()]),createdAt:string2(),lastUpdatedAt:string2(),pollInterval:optional(number2()),statusMessage:optional(string2())}),CreateTaskResultSchema=ResultSchema.extend({task:TaskSchema}),TaskStatusNotificationParamsSchema=NotificationsParamsSchema.merge(TaskSchema),TaskStatusNotificationSchema=NotificationSchema.extend({method:literal("notifications/tasks/status"),params:TaskStatusNotificationParamsSchema}),GetTaskRequestSchema=RequestSchema.extend({method:literal("tasks/get"),params:BaseRequestParamsSchema.extend({taskId:string2()})}),GetTaskResultSchema=ResultSchema.merge(TaskSchema),GetTaskPayloadRequestSchema=RequestSchema.extend({method:literal("tasks/result"),params:BaseRequestParamsSchema.extend({taskId:string2()})}),GetTaskPayloadResultSchema=ResultSchema.loose(),ListTasksRequestSchema=PaginatedRequestSchema.extend({method:literal("tasks/list")}),ListTasksResultSchema=PaginatedResultSchema.extend({tasks:array(TaskSchema)}),CancelTaskRequestSchema=RequestSchema.extend({method:literal("tasks/cancel"),params:BaseRequestParamsSchema.extend({taskId:string2()})}),CancelTaskResultSchema=ResultSchema.merge(TaskSchema),ClientRequestSchema=union([PingRequestSchema,InitializeRequestSchema,DiscoverRequestSchema,CompleteRequestSchema,SetLevelRequestSchema,GetPromptRequestSchema,ListPromptsRequestSchema,ListResourcesRequestSchema,ListResourceTemplatesRequestSchema,ReadResourceRequestSchema,SubscribeRequestSchema,UnsubscribeRequestSchema,SubscriptionsListenRequestSchema,CallToolRequestSchema,ListToolsRequestSchema]),ClientNotificationSchema=union([CancelledNotificationSchema,ProgressNotificationSchema,InitializedNotificationSchema,RootsListChangedNotificationSchema]),ClientResultSchema=union([EmptyResultSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,ElicitResultSchema,ListRootsResultSchema]),ServerRequestSchema=union([PingRequestSchema,CreateMessageRequestSchema,ElicitRequestSchema,ListRootsRequestSchema]),ServerNotificationSchema=union([CancelledNotificationSchema,ProgressNotificationSchema,LoggingMessageNotificationSchema,ResourceUpdatedNotificationSchema,ResourceListChangedNotificationSchema,ToolListChangedNotificationSchema,PromptListChangedNotificationSchema,SubscriptionsAcknowledgedNotificationSchema,ElicitationCompleteNotificationSchema]),ServerResultSchema=union([EmptyResultSchema,InitializeResultSchema,DiscoverResultSchema,CompleteResultSchema,GetPromptResultSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListResourceTemplatesResultSchema,ReadResourceResultSchema,CallToolResultSchema,ListToolsResultSchema,SubscriptionsListenResultSchema]),SafeUrlSchema=url().superRefine((val,ctx)=>{if(!URL.canParse(val))return ctx.addIssue({code:ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),NEVER}).refine(url2=>{let u=new URL(url2);return u.protocol!=="javascript:"&&u.protocol!=="data:"&&u.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),OAuthProtectedResourceMetadataSchema=looseObject({resource:string2().url(),authorization_servers:array(SafeUrlSchema).optional(),jwks_uri:string2().url().optional(),scopes_supported:array(string2()).optional(),bearer_methods_supported:array(string2()).optional(),resource_signing_alg_values_supported:array(string2()).optional(),resource_name:string2().optional(),resource_documentation:string2().optional(),resource_policy_uri:string2().url().optional(),resource_tos_uri:string2().url().optional(),tls_client_certificate_bound_access_tokens:boolean2().optional(),authorization_details_types_supported:array(string2()).optional(),dpop_signing_alg_values_supported:array(string2()).optional(),dpop_bound_access_tokens_required:boolean2().optional()}),OAuthMetadataSchema=looseObject({issuer:string2(),authorization_endpoint:SafeUrlSchema,token_endpoint:SafeUrlSchema,registration_endpoint:SafeUrlSchema.optional(),scopes_supported:array(string2()).optional(),response_types_supported:array(string2()),response_modes_supported:array(string2()).optional(),grant_types_supported:array(string2()).optional(),token_endpoint_auth_methods_supported:array(string2()).optional(),token_endpoint_auth_signing_alg_values_supported:array(string2()).optional(),service_documentation:SafeUrlSchema.optional(),revocation_endpoint:SafeUrlSchema.optional(),revocation_endpoint_auth_methods_supported:array(string2()).optional(),revocation_endpoint_auth_signing_alg_values_supported:array(string2()).optional(),introspection_endpoint:string2().optional(),introspection_endpoint_auth_methods_supported:array(string2()).optional(),introspection_endpoint_auth_signing_alg_values_supported:array(string2()).optional(),code_challenge_methods_supported:array(string2()).optional(),client_id_metadata_document_supported:boolean2().optional(),authorization_response_iss_parameter_supported:boolean2().optional().catch(void 0)}),OpenIdProviderMetadataSchema=looseObject({issuer:string2(),authorization_endpoint:SafeUrlSchema,token_endpoint:SafeUrlSchema,userinfo_endpoint:SafeUrlSchema.optional(),jwks_uri:SafeUrlSchema,registration_endpoint:SafeUrlSchema.optional(),scopes_supported:array(string2()).optional(),response_types_supported:array(string2()),response_modes_supported:array(string2()).optional(),grant_types_supported:array(string2()).optional(),acr_values_supported:array(string2()).optional(),subject_types_supported:array(string2()),id_token_signing_alg_values_supported:array(string2()),id_token_encryption_alg_values_supported:array(string2()).optional(),id_token_encryption_enc_values_supported:array(string2()).optional(),userinfo_signing_alg_values_supported:array(string2()).optional(),userinfo_encryption_alg_values_supported:array(string2()).optional(),userinfo_encryption_enc_values_supported:array(string2()).optional(),request_object_signing_alg_values_supported:array(string2()).optional(),request_object_encryption_alg_values_supported:array(string2()).optional(),request_object_encryption_enc_values_supported:array(string2()).optional(),token_endpoint_auth_methods_supported:array(string2()).optional(),token_endpoint_auth_signing_alg_values_supported:array(string2()).optional(),display_values_supported:array(string2()).optional(),claim_types_supported:array(string2()).optional(),claims_supported:array(string2()).optional(),service_documentation:string2().optional(),claims_locales_supported:array(string2()).optional(),ui_locales_supported:array(string2()).optional(),claims_parameter_supported:boolean2().optional(),request_parameter_supported:boolean2().optional(),request_uri_parameter_supported:boolean2().optional(),require_request_uri_registration:boolean2().optional(),op_policy_uri:SafeUrlSchema.optional(),op_tos_uri:SafeUrlSchema.optional(),client_id_metadata_document_supported:boolean2().optional(),authorization_response_iss_parameter_supported:boolean2().optional().catch(void 0)}),OpenIdProviderDiscoveryMetadataSchema=object({...OpenIdProviderMetadataSchema.shape,...OAuthMetadataSchema.pick({code_challenge_methods_supported:!0}).shape}),OAuthTokensSchema=object({access_token:string2(),id_token:string2().optional(),token_type:string2(),expires_in:coerce_exports.number().optional(),scope:string2().optional(),refresh_token:string2().optional()}).strip(),IdJagTokenExchangeResponseSchema=object({issued_token_type:literal("urn:ietf:params:oauth:token-type:id-jag"),access_token:string2(),token_type:string2().optional(),expires_in:number2().optional(),scope:string2().optional()}).strip(),OAuthErrorResponseSchema=object({error:string2(),error_description:string2().optional(),error_uri:string2().optional()}),OptionalSafeUrlSchema=SafeUrlSchema.optional().or(literal("").transform(()=>{})),OAuthClientMetadataSchema=object({redirect_uris:array(SafeUrlSchema),token_endpoint_auth_method:string2().optional(),grant_types:array(string2()).optional(),response_types:array(string2()).optional(),application_type:string2().optional(),client_name:string2().optional(),client_uri:SafeUrlSchema.optional(),logo_uri:OptionalSafeUrlSchema,scope:string2().optional(),contacts:array(string2()).optional(),tos_uri:OptionalSafeUrlSchema,policy_uri:string2().optional(),jwks_uri:SafeUrlSchema.optional(),jwks:any().optional(),software_id:string2().optional(),software_version:string2().optional(),software_statement:string2().optional()}).strip(),OAuthClientInformationSchema=object({client_id:string2(),client_secret:string2().optional(),client_id_issued_at:number2().optional(),client_secret_expires_at:number2().optional()}).strip(),OAuthClientInformationFullSchema=OAuthClientMetadataSchema.merge(OAuthClientInformationSchema),OAuthClientRegistrationErrorSchema=object({error:string2(),error_description:string2().optional()}).strip(),OAuthTokenRevocationRequestSchema=object({token:string2(),token_type_hint:string2().optional()}).strip()}});var init_internal=__esm({"../../node_modules/.pnpm/@modelcontextprotocol+core@2.0.0/node_modules/@modelcontextprotocol/core/dist/internal.mjs"(){"use strict";init_auth_CUe6YdwF()}});function stampErrorBrands(instance,ctor){let brands=new Set,current=ctor;for(;typeof current=="function";){let brand=current.mcpBrand;Object.prototype.hasOwnProperty.call(current,"mcpBrand")&&typeof brand=="string"&&brands.add(brand),current=Object.getPrototypeOf(current)}brands.size!==0&&Object.defineProperty(instance,BRANDS,{value:brands,enumerable:!1,configurable:!0})}function brandedHasInstance(cls,value){try{if(typeof value=="object"&&value!==null&&Object.prototype.hasOwnProperty.call(cls,"mcpBrand")&&typeof cls.mcpBrand=="string"&&Object.prototype.hasOwnProperty.call(value,BRANDS)){let carried=value[BRANDS];if(carried&&typeof carried.has=="function"&&carried.has(cls.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(cls,value)}function requiredClientCapabilitiesForRequest(method){return Object.hasOwn(REQUIRED_CLIENT_CAPABILITIES_BY_METHOD,method)?REQUIRED_CLIENT_CAPABILITIES_BY_METHOD[method]:void 0}function isPlainObject$7(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function isImpliedCapabilityMember(capability,member,declaredValue){return capability==="elicitation"&&member==="form"&&declaredValue.form===void 0&&declaredValue.url===void 0}function requiredClientCapabilitiesForInputRequest(entry){switch(entry.method){case"elicitation/create":return entry.params?.mode==="url"?{elicitation:{url:{}}}:{elicitation:{form:{}}};case"sampling/createMessage":{let params=entry.params;return params!==void 0&&(params.tools!==void 0||params.toolChoice!==void 0)?{sampling:{tools:{}}}:{sampling:{}}}case"roots/list":return{roots:{}};default:return}}function missingClientCapabilities(required2,declared){let missing={};for(let[capability,requirement]of Object.entries(required2)){if(requirement===void 0)continue;let declaredValue=declared===void 0?void 0:declared[capability];if(declaredValue===void 0){missing[capability]=requirement;continue}if(isPlainObject$7(requirement)&&isPlainObject$7(declaredValue)){let missingMembers={};for(let[member,memberRequirement]of Object.entries(requirement))memberRequirement!==void 0&&declaredValue[member]===void 0&&!isImpliedCapabilityMember(capability,member,declaredValue)&&(missingMembers[member]=memberRequirement);Object.keys(missingMembers).length>0&&(missing[capability]=missingMembers)}}return Object.keys(missing).length>0?missing:void 0}function isModernProtocolVersion(version2){return version2>=FIRST_MODERN_PROTOCOL_VERSION}function legacyProtocolVersions(versions){return versions.filter(version2=>!isModernProtocolVersion(version2))}function modernProtocolVersions(versions){return versions.filter(version2=>isModernProtocolVersion(version2))}function appendTextFallbackForNonObject(result){let sc=result.structuredContent;return sc===void 0||!(typeof sc!="object"||sc===null||Array.isArray(sc))||(result.content?.some(c=>c.type==="text")??!1)?result:{...result,content:[...result.content??[],{type:"text",text:JSON.stringify(sc)}]}}function normalizeContentlessToolResult(value){return value===null||typeof value!="object"||Array.isArray(value)||value.content!==void 0||TOOL_RESULT_FOREIGN_FAMILY_KEYS.some(key=>key in value)?value:{...value,content:[]}}function build$1(){let JSONValueSchema$1=lazy(()=>union([string2(),number2(),boolean2(),_null3(),record(string2(),JSONValueSchema$1),array(JSONValueSchema$1)])),JSONObjectSchema$1=record(string2(),JSONValueSchema$1),ProgressTokenSchema$1=union([string2(),number2().int()]),CursorSchema$1=string2(),TaskMetadataSchema$1=object({ttl:number2().optional()}),RelatedTaskMetadataSchema$1=object({taskId:string2()}),RequestMetaSchema$1=looseObject({progressToken:ProgressTokenSchema$1.optional(),"io.modelcontextprotocol/related-task":RelatedTaskMetadataSchema$1.optional()}),BaseRequestParamsSchema$1=object({_meta:RequestMetaSchema$1.optional()}),TaskAugmentedRequestParamsSchema$1=BaseRequestParamsSchema$1.extend({task:TaskMetadataSchema$1.optional()}),RequestSchema$1=object({method:string2(),params:BaseRequestParamsSchema$1.loose().optional()}),NotificationsParamsSchema$1=object({_meta:RequestMetaSchema$1.optional()}),NotificationSchema$1=object({method:string2(),params:NotificationsParamsSchema$1.loose().optional()}),ResultSchema$1=looseObject({_meta:RequestMetaSchema$1.optional()}),RequestIdSchema$1=union([string2(),number2().int()]),EmptyResultSchema$1=ResultSchema$1.strict(),CancelledNotificationParamsSchema$1=NotificationsParamsSchema$1.extend({requestId:RequestIdSchema$1.optional(),reason:string2().optional()}),CancelledNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/cancelled"),params:CancelledNotificationParamsSchema$1}),IconSchema$1=object({src:string2(),mimeType:string2().optional(),sizes:array(string2()).optional(),theme:_enum(["light","dark"]).optional()}),IconsSchema$1=object({icons:array(IconSchema$1).optional()}),BaseMetadataSchema$1=object({name:string2(),title:string2().optional()}),ImplementationSchema$1=BaseMetadataSchema$1.extend({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,version:string2(),websiteUrl:string2().optional(),description:string2().optional()}),FormElicitationCapabilitySchema2=intersection(object({applyDefaults:boolean2().optional()}),JSONObjectSchema$1),ElicitationCapabilitySchema2=preprocess(value=>value&&typeof value=="object"&&!Array.isArray(value)&&Object.keys(value).length===0?{form:{}}:value,intersection(object({form:FormElicitationCapabilitySchema2.optional(),url:JSONObjectSchema$1.optional()}),JSONObjectSchema$1.optional())),ClientTasksCapabilitySchema$1=looseObject({list:JSONObjectSchema$1.optional(),cancel:JSONObjectSchema$1.optional(),requests:looseObject({sampling:looseObject({createMessage:JSONObjectSchema$1.optional()}).optional(),elicitation:looseObject({create:JSONObjectSchema$1.optional()}).optional()}).optional()}),ServerTasksCapabilitySchema$1=looseObject({list:JSONObjectSchema$1.optional(),cancel:JSONObjectSchema$1.optional(),requests:looseObject({tools:looseObject({call:JSONObjectSchema$1.optional()}).optional()}).optional()}),ClientCapabilitiesSchema$1=object({experimental:record(string2(),JSONObjectSchema$1).optional(),sampling:object({context:JSONObjectSchema$1.optional(),tools:JSONObjectSchema$1.optional()}).optional(),elicitation:ElicitationCapabilitySchema2.optional(),roots:object({listChanged:boolean2().optional()}).optional(),tasks:ClientTasksCapabilitySchema$1.optional(),extensions:record(string2(),JSONObjectSchema$1).optional()}),InitializeRequestParamsSchema$1=BaseRequestParamsSchema$1.extend({protocolVersion:string2(),capabilities:ClientCapabilitiesSchema$1,clientInfo:ImplementationSchema$1}),InitializeRequestSchema$1=RequestSchema$1.extend({method:literal("initialize"),params:InitializeRequestParamsSchema$1}),ServerCapabilitiesSchema$1=object({experimental:record(string2(),JSONObjectSchema$1).optional(),logging:JSONObjectSchema$1.optional(),completions:JSONObjectSchema$1.optional(),prompts:object({listChanged:boolean2().optional()}).optional(),resources:object({subscribe:boolean2().optional(),listChanged:boolean2().optional()}).optional(),tools:object({listChanged:boolean2().optional()}).optional(),tasks:ServerTasksCapabilitySchema$1.optional(),extensions:record(string2(),JSONObjectSchema$1).optional()}),InitializeResultSchema$1=ResultSchema$1.extend({protocolVersion:string2(),capabilities:ServerCapabilitiesSchema$1,serverInfo:ImplementationSchema$1,instructions:string2().optional()}),InitializedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/initialized"),params:NotificationsParamsSchema$1.optional()}),PingRequestSchema$1=RequestSchema$1.extend({method:literal("ping"),params:BaseRequestParamsSchema$1.optional()}),ProgressSchema$1=object({progress:number2(),total:optional(number2()),message:optional(string2())}),ProgressNotificationParamsSchema$1=object({...NotificationsParamsSchema$1.shape,...ProgressSchema$1.shape,progressToken:ProgressTokenSchema$1}),ProgressNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/progress"),params:ProgressNotificationParamsSchema$1}),PaginatedRequestParamsSchema$1=BaseRequestParamsSchema$1.extend({cursor:CursorSchema$1.optional()}),PaginatedRequestSchema$1=RequestSchema$1.extend({params:PaginatedRequestParamsSchema$1.optional()}),PaginatedResultSchema$1=ResultSchema$1.extend({nextCursor:CursorSchema$1.optional()}),ResourceContentsSchema$1=object({uri:string2(),mimeType:optional(string2()),_meta:record(string2(),unknown()).optional()}),TextResourceContentsSchema$1=ResourceContentsSchema$1.extend({text:string2()}),Base64Schema2=string2().refine(val=>{try{return atob(val),!0}catch{return!1}},{message:"Invalid Base64 string"}),BlobResourceContentsSchema$1=ResourceContentsSchema$1.extend({blob:Base64Schema2}),RoleSchema$1=_enum(["user","assistant"]),AnnotationsSchema$1=object({audience:array(RoleSchema$1).optional(),priority:number2().min(0).max(1).optional(),lastModified:iso_exports.datetime({offset:!0}).optional()}),ResourceSchema$1=object({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,uri:string2(),description:optional(string2()),mimeType:optional(string2()),size:optional(number2()),annotations:AnnotationsSchema$1.optional(),_meta:optional(looseObject({}))}),ResourceTemplateSchema$1=object({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,uriTemplate:string2(),description:optional(string2()),mimeType:optional(string2()),annotations:AnnotationsSchema$1.optional(),_meta:optional(looseObject({}))}),ListResourcesRequestSchema$1=PaginatedRequestSchema$1.extend({method:literal("resources/list")}),ListResourcesResultSchema$1=PaginatedResultSchema$1.extend({resources:array(ResourceSchema$1)}),ListResourceTemplatesRequestSchema$1=PaginatedRequestSchema$1.extend({method:literal("resources/templates/list")}),ListResourceTemplatesResultSchema$1=PaginatedResultSchema$1.extend({resourceTemplates:array(ResourceTemplateSchema$1)}),ResourceRequestParamsSchema$1=BaseRequestParamsSchema$1.extend({uri:string2()}),ReadResourceRequestParamsSchema$1=ResourceRequestParamsSchema$1,ReadResourceRequestSchema$1=RequestSchema$1.extend({method:literal("resources/read"),params:ReadResourceRequestParamsSchema$1}),ReadResourceResultSchema$1=ResultSchema$1.extend({contents:array(union([TextResourceContentsSchema$1,BlobResourceContentsSchema$1]))}),ResourceListChangedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/resources/list_changed"),params:NotificationsParamsSchema$1.optional()}),SubscribeRequestParamsSchema$1=ResourceRequestParamsSchema$1,SubscribeRequestSchema$1=RequestSchema$1.extend({method:literal("resources/subscribe"),params:SubscribeRequestParamsSchema$1}),UnsubscribeRequestParamsSchema$1=ResourceRequestParamsSchema$1,UnsubscribeRequestSchema$1=RequestSchema$1.extend({method:literal("resources/unsubscribe"),params:UnsubscribeRequestParamsSchema$1}),ResourceUpdatedNotificationParamsSchema$1=NotificationsParamsSchema$1.extend({uri:string2()}),ResourceUpdatedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/resources/updated"),params:ResourceUpdatedNotificationParamsSchema$1}),PromptArgumentSchema$1=object({name:string2(),description:optional(string2()),required:optional(boolean2())}),PromptSchema$1=object({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,description:optional(string2()),arguments:optional(array(PromptArgumentSchema$1)),_meta:optional(looseObject({}))}),ListPromptsRequestSchema$1=PaginatedRequestSchema$1.extend({method:literal("prompts/list")}),ListPromptsResultSchema$1=PaginatedResultSchema$1.extend({prompts:array(PromptSchema$1)}),GetPromptRequestParamsSchema$1=BaseRequestParamsSchema$1.extend({name:string2(),arguments:record(string2(),string2()).optional()}),GetPromptRequestSchema$1=RequestSchema$1.extend({method:literal("prompts/get"),params:GetPromptRequestParamsSchema$1}),TextContentSchema$1=object({type:literal("text"),text:string2(),annotations:AnnotationsSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),ImageContentSchema$1=object({type:literal("image"),data:Base64Schema2,mimeType:string2(),annotations:AnnotationsSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),AudioContentSchema$1=object({type:literal("audio"),data:Base64Schema2,mimeType:string2(),annotations:AnnotationsSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),ToolUseContentSchema$1=object({type:literal("tool_use"),name:string2(),id:string2(),input:record(string2(),unknown()),_meta:record(string2(),unknown()).optional()}),EmbeddedResourceSchema$1=object({type:literal("resource"),resource:union([TextResourceContentsSchema$1,BlobResourceContentsSchema$1]),annotations:AnnotationsSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),ResourceLinkSchema$1=ResourceSchema$1.extend({type:literal("resource_link")}),ContentBlockSchema$1=union([TextContentSchema$1,ImageContentSchema$1,AudioContentSchema$1,ResourceLinkSchema$1,EmbeddedResourceSchema$1]),PromptMessageSchema$1=object({role:RoleSchema$1,content:ContentBlockSchema$1}),GetPromptResultSchema$1=ResultSchema$1.extend({description:string2().optional(),messages:array(PromptMessageSchema$1)}),PromptListChangedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/prompts/list_changed"),params:NotificationsParamsSchema$1.optional()}),ToolAnnotationsSchema$1=object({title:string2().optional(),readOnlyHint:boolean2().optional(),destructiveHint:boolean2().optional(),idempotentHint:boolean2().optional(),openWorldHint:boolean2().optional()}),ToolExecutionSchema$1=object({taskSupport:_enum(["required","optional","forbidden"]).optional()}),ToolSchema$1=object({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,description:string2().optional(),inputSchema:object({type:literal("object"),properties:record(string2(),JSONValueSchema$1).optional(),required:array(string2()).optional()}).catchall(unknown()),outputSchema:object({type:literal("object"),properties:record(string2(),JSONValueSchema$1).optional(),required:array(string2()).optional()}).catchall(unknown()).optional(),annotations:ToolAnnotationsSchema$1.optional(),execution:ToolExecutionSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),ListToolsRequestSchema$1=PaginatedRequestSchema$1.extend({method:literal("tools/list")}),ListToolsResultSchema$1=PaginatedResultSchema$1.extend({tools:array(ToolSchema$1)}),CallToolResultSchema$1=ResultSchema$1.extend({content:array(ContentBlockSchema$1),structuredContent:record(string2(),unknown()).optional(),isError:boolean2().optional()}),CallToolRequestParamsSchema$1=TaskAugmentedRequestParamsSchema$1.extend({name:string2(),arguments:record(string2(),unknown()).optional()}),CallToolRequestSchema$1=RequestSchema$1.extend({method:literal("tools/call"),params:CallToolRequestParamsSchema$1}),ToolListChangedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/tools/list_changed"),params:NotificationsParamsSchema$1.optional()}),LoggingLevelSchema$1=_enum(["debug","info","notice","warning","error","critical","alert","emergency"]),SetLevelRequestParamsSchema$1=BaseRequestParamsSchema$1.extend({level:LoggingLevelSchema$1}),SetLevelRequestSchema$1=RequestSchema$1.extend({method:literal("logging/setLevel"),params:SetLevelRequestParamsSchema$1}),LoggingMessageNotificationParamsSchema$1=NotificationsParamsSchema$1.extend({level:LoggingLevelSchema$1,logger:string2().optional(),data:unknown()}),LoggingMessageNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/message"),params:LoggingMessageNotificationParamsSchema$1}),ModelHintSchema$1=object({name:string2().optional()}),ModelPreferencesSchema$1=object({hints:array(ModelHintSchema$1).optional(),costPriority:number2().min(0).max(1).optional(),speedPriority:number2().min(0).max(1).optional(),intelligencePriority:number2().min(0).max(1).optional()}),ToolChoiceSchema$1=object({mode:_enum(["auto","required","none"]).optional()}),ToolResultContentSchema$1=object({type:literal("tool_result"),toolUseId:string2().describe("The unique identifier for the corresponding tool call."),content:array(ContentBlockSchema$1),structuredContent:object({}).loose().optional(),isError:boolean2().optional(),_meta:record(string2(),unknown()).optional()}),SamplingContentSchema$1=discriminatedUnion("type",[TextContentSchema$1,ImageContentSchema$1,AudioContentSchema$1]),SamplingMessageContentBlockSchema$1=discriminatedUnion("type",[TextContentSchema$1,ImageContentSchema$1,AudioContentSchema$1,ToolUseContentSchema$1,ToolResultContentSchema$1]),SamplingMessageSchema$1=object({role:RoleSchema$1,content:union([SamplingMessageContentBlockSchema$1,array(SamplingMessageContentBlockSchema$1)]),_meta:record(string2(),unknown()).optional()}),CreateMessageRequestParamsSchema$1=TaskAugmentedRequestParamsSchema$1.extend({messages:array(SamplingMessageSchema$1),modelPreferences:ModelPreferencesSchema$1.optional(),systemPrompt:string2().optional(),includeContext:_enum(["none","thisServer","allServers"]).optional(),temperature:number2().optional(),maxTokens:number2().int(),stopSequences:array(string2()).optional(),metadata:JSONObjectSchema$1.optional(),tools:array(ToolSchema$1).optional(),toolChoice:ToolChoiceSchema$1.optional()}),CreateMessageRequestSchema$1=RequestSchema$1.extend({method:literal("sampling/createMessage"),params:CreateMessageRequestParamsSchema$1}),CreateMessageResultSchema$1=ResultSchema$1.extend({model:string2(),stopReason:optional(_enum(["endTurn","stopSequence","maxTokens"]).or(string2())),role:RoleSchema$1,content:SamplingContentSchema$1}),CreateMessageResultWithToolsSchema$1=ResultSchema$1.extend({model:string2(),stopReason:optional(_enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(string2())),role:RoleSchema$1,content:union([SamplingMessageContentBlockSchema$1,array(SamplingMessageContentBlockSchema$1)])}),BooleanSchemaSchema$1=object({type:literal("boolean"),title:string2().optional(),description:string2().optional(),default:boolean2().optional()}),StringSchemaSchema$1=object({type:literal("string"),title:string2().optional(),description:string2().optional(),minLength:number2().optional(),maxLength:number2().optional(),format:_enum(["email","uri","date","date-time"]).optional(),default:string2().optional()}),NumberSchemaSchema$1=object({type:_enum(["number","integer"]),title:string2().optional(),description:string2().optional(),minimum:number2().optional(),maximum:number2().optional(),default:number2().optional()}),UntitledSingleSelectEnumSchemaSchema$1=object({type:literal("string"),title:string2().optional(),description:string2().optional(),enum:array(string2()),default:string2().optional()}),TitledSingleSelectEnumSchemaSchema$1=object({type:literal("string"),title:string2().optional(),description:string2().optional(),oneOf:array(object({const:string2(),title:string2()})),default:string2().optional()}),LegacyTitledEnumSchemaSchema$1=object({type:literal("string"),title:string2().optional(),description:string2().optional(),enum:array(string2()),enumNames:array(string2()).optional(),default:string2().optional()}),SingleSelectEnumSchemaSchema$1=union([UntitledSingleSelectEnumSchemaSchema$1,TitledSingleSelectEnumSchemaSchema$1]),UntitledMultiSelectEnumSchemaSchema$1=object({type:literal("array"),title:string2().optional(),description:string2().optional(),minItems:number2().optional(),maxItems:number2().optional(),items:object({type:literal("string"),enum:array(string2())}),default:array(string2()).optional()}),TitledMultiSelectEnumSchemaSchema$1=object({type:literal("array"),title:string2().optional(),description:string2().optional(),minItems:number2().optional(),maxItems:number2().optional(),items:object({anyOf:array(object({const:string2(),title:string2()}))}),default:array(string2()).optional()}),MultiSelectEnumSchemaSchema$1=union([UntitledMultiSelectEnumSchemaSchema$1,TitledMultiSelectEnumSchemaSchema$1]),EnumSchemaSchema$1=union([LegacyTitledEnumSchemaSchema$1,SingleSelectEnumSchemaSchema$1,MultiSelectEnumSchemaSchema$1]),PrimitiveSchemaDefinitionSchema$1=union([EnumSchemaSchema$1,BooleanSchemaSchema$1,StringSchemaSchema$1,NumberSchemaSchema$1]),ElicitRequestFormParamsSchema$1=TaskAugmentedRequestParamsSchema$1.extend({mode:literal("form").optional(),message:string2(),requestedSchema:object({type:literal("object"),properties:record(string2(),PrimitiveSchemaDefinitionSchema$1),required:array(string2()).optional()}).catchall(unknown())}),ElicitRequestURLParamsSchema$1=TaskAugmentedRequestParamsSchema$1.extend({mode:literal("url"),message:string2(),elicitationId:string2(),url:string2().url()}),ElicitRequestParamsSchema$1=union([ElicitRequestFormParamsSchema$1,ElicitRequestURLParamsSchema$1]),ElicitRequestSchema$1=RequestSchema$1.extend({method:literal("elicitation/create"),params:ElicitRequestParamsSchema$1}),ElicitationCompleteNotificationParamsSchema$1=NotificationsParamsSchema$1.extend({elicitationId:string2()}),ElicitationCompleteNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/elicitation/complete"),params:ElicitationCompleteNotificationParamsSchema$1}),ElicitResultSchema$1=ResultSchema$1.extend({action:_enum(["accept","decline","cancel"]),content:preprocess(val=>val===null?void 0:val,record(string2(),union([string2(),number2(),boolean2(),array(string2())])).optional())}),ResourceTemplateReferenceSchema$1=object({type:literal("ref/resource"),uri:string2()}),PromptReferenceSchema$1=object({type:literal("ref/prompt"),name:string2()}),CompleteRequestParamsSchema$1=BaseRequestParamsSchema$1.extend({ref:union([PromptReferenceSchema$1,ResourceTemplateReferenceSchema$1]),argument:object({name:string2(),value:string2()}),context:object({arguments:record(string2(),string2()).optional()}).optional()}),CompleteRequestSchema$1=RequestSchema$1.extend({method:literal("completion/complete"),params:CompleteRequestParamsSchema$1}),CompleteResultSchema$1=ResultSchema$1.extend({completion:looseObject({values:array(string2()).max(100),total:optional(number2().int()),hasMore:optional(boolean2())})}),RootSchema$1=object({uri:string2().startsWith("file://"),name:string2().optional(),_meta:record(string2(),unknown()).optional()}),ListRootsRequestSchema$1=RequestSchema$1.extend({method:literal("roots/list"),params:BaseRequestParamsSchema$1.optional()}),ListRootsResultSchema$1=ResultSchema$1.extend({roots:array(RootSchema$1)}),RootsListChangedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/roots/list_changed"),params:NotificationsParamsSchema$1.optional()}),TaskCreationParamsSchema$1=looseObject({ttl:number2().optional(),pollInterval:number2().optional()}),TaskStatusSchema$1=_enum(["working","input_required","completed","failed","cancelled"]),TaskSchema$1=object({taskId:string2(),status:TaskStatusSchema$1,ttl:union([number2(),_null3()]),createdAt:string2(),lastUpdatedAt:string2(),pollInterval:optional(number2()),statusMessage:optional(string2())}),CreateTaskResultSchema$1=ResultSchema$1.extend({task:TaskSchema$1}),TaskStatusNotificationParamsSchema$1=NotificationsParamsSchema$1.merge(TaskSchema$1),TaskStatusNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/tasks/status"),params:TaskStatusNotificationParamsSchema$1}),GetTaskRequestSchema$1=RequestSchema$1.extend({method:literal("tasks/get"),params:BaseRequestParamsSchema$1.extend({taskId:string2()})}),GetTaskResultSchema$1=ResultSchema$1.merge(TaskSchema$1),GetTaskPayloadRequestSchema$1=RequestSchema$1.extend({method:literal("tasks/result"),params:BaseRequestParamsSchema$1.extend({taskId:string2()})}),GetTaskPayloadResultSchema$1=ResultSchema$1.loose(),ListTasksRequestSchema$1=PaginatedRequestSchema$1.extend({method:literal("tasks/list")}),ListTasksResultSchema$1=PaginatedResultSchema$1.extend({tasks:array(TaskSchema$1)}),CancelTaskRequestSchema$1=RequestSchema$1.extend({method:literal("tasks/cancel"),params:BaseRequestParamsSchema$1.extend({taskId:string2()})});return{JSONValueSchema:JSONValueSchema$1,JSONObjectSchema:JSONObjectSchema$1,ProgressTokenSchema:ProgressTokenSchema$1,CursorSchema:CursorSchema$1,TaskMetadataSchema:TaskMetadataSchema$1,RelatedTaskMetadataSchema:RelatedTaskMetadataSchema$1,RequestMetaSchema:RequestMetaSchema$1,BaseRequestParamsSchema:BaseRequestParamsSchema$1,TaskAugmentedRequestParamsSchema:TaskAugmentedRequestParamsSchema$1,RequestSchema:RequestSchema$1,NotificationsParamsSchema:NotificationsParamsSchema$1,NotificationSchema:NotificationSchema$1,ResultSchema:ResultSchema$1,RequestIdSchema:RequestIdSchema$1,EmptyResultSchema:EmptyResultSchema$1,CancelledNotificationParamsSchema:CancelledNotificationParamsSchema$1,CancelledNotificationSchema:CancelledNotificationSchema$1,IconSchema:IconSchema$1,IconsSchema:IconsSchema$1,BaseMetadataSchema:BaseMetadataSchema$1,ImplementationSchema:ImplementationSchema$1,ClientTasksCapabilitySchema:ClientTasksCapabilitySchema$1,ServerTasksCapabilitySchema:ServerTasksCapabilitySchema$1,ClientCapabilitiesSchema:ClientCapabilitiesSchema$1,InitializeRequestParamsSchema:InitializeRequestParamsSchema$1,InitializeRequestSchema:InitializeRequestSchema$1,ServerCapabilitiesSchema:ServerCapabilitiesSchema$1,InitializeResultSchema:InitializeResultSchema$1,InitializedNotificationSchema:InitializedNotificationSchema$1,PingRequestSchema:PingRequestSchema$1,ProgressSchema:ProgressSchema$1,ProgressNotificationParamsSchema:ProgressNotificationParamsSchema$1,ProgressNotificationSchema:ProgressNotificationSchema$1,PaginatedRequestParamsSchema:PaginatedRequestParamsSchema$1,PaginatedRequestSchema:PaginatedRequestSchema$1,PaginatedResultSchema:PaginatedResultSchema$1,ResourceContentsSchema:ResourceContentsSchema$1,TextResourceContentsSchema:TextResourceContentsSchema$1,BlobResourceContentsSchema:BlobResourceContentsSchema$1,RoleSchema:RoleSchema$1,AnnotationsSchema:AnnotationsSchema$1,ResourceSchema:ResourceSchema$1,ResourceTemplateSchema:ResourceTemplateSchema$1,ListResourcesRequestSchema:ListResourcesRequestSchema$1,ListResourcesResultSchema:ListResourcesResultSchema$1,ListResourceTemplatesRequestSchema:ListResourceTemplatesRequestSchema$1,ListResourceTemplatesResultSchema:ListResourceTemplatesResultSchema$1,ResourceRequestParamsSchema:ResourceRequestParamsSchema$1,ReadResourceRequestParamsSchema:ReadResourceRequestParamsSchema$1,ReadResourceRequestSchema:ReadResourceRequestSchema$1,ReadResourceResultSchema:ReadResourceResultSchema$1,ResourceListChangedNotificationSchema:ResourceListChangedNotificationSchema$1,SubscribeRequestParamsSchema:SubscribeRequestParamsSchema$1,SubscribeRequestSchema:SubscribeRequestSchema$1,UnsubscribeRequestParamsSchema:UnsubscribeRequestParamsSchema$1,UnsubscribeRequestSchema:UnsubscribeRequestSchema$1,ResourceUpdatedNotificationParamsSchema:ResourceUpdatedNotificationParamsSchema$1,ResourceUpdatedNotificationSchema:ResourceUpdatedNotificationSchema$1,PromptArgumentSchema:PromptArgumentSchema$1,PromptSchema:PromptSchema$1,ListPromptsRequestSchema:ListPromptsRequestSchema$1,ListPromptsResultSchema:ListPromptsResultSchema$1,GetPromptRequestParamsSchema:GetPromptRequestParamsSchema$1,GetPromptRequestSchema:GetPromptRequestSchema$1,TextContentSchema:TextContentSchema$1,ImageContentSchema:ImageContentSchema$1,AudioContentSchema:AudioContentSchema$1,ToolUseContentSchema:ToolUseContentSchema$1,EmbeddedResourceSchema:EmbeddedResourceSchema$1,ResourceLinkSchema:ResourceLinkSchema$1,ContentBlockSchema:ContentBlockSchema$1,PromptMessageSchema:PromptMessageSchema$1,GetPromptResultSchema:GetPromptResultSchema$1,PromptListChangedNotificationSchema:PromptListChangedNotificationSchema$1,ToolAnnotationsSchema:ToolAnnotationsSchema$1,ToolExecutionSchema:ToolExecutionSchema$1,ToolSchema:ToolSchema$1,ListToolsRequestSchema:ListToolsRequestSchema$1,ListToolsResultSchema:ListToolsResultSchema$1,CallToolResultSchema:CallToolResultSchema$1,CallToolRequestParamsSchema:CallToolRequestParamsSchema$1,CallToolRequestSchema:CallToolRequestSchema$1,ToolListChangedNotificationSchema:ToolListChangedNotificationSchema$1,LoggingLevelSchema:LoggingLevelSchema$1,SetLevelRequestParamsSchema:SetLevelRequestParamsSchema$1,SetLevelRequestSchema:SetLevelRequestSchema$1,LoggingMessageNotificationParamsSchema:LoggingMessageNotificationParamsSchema$1,LoggingMessageNotificationSchema:LoggingMessageNotificationSchema$1,ModelHintSchema:ModelHintSchema$1,ModelPreferencesSchema:ModelPreferencesSchema$1,ToolChoiceSchema:ToolChoiceSchema$1,ToolResultContentSchema:ToolResultContentSchema$1,SamplingContentSchema:SamplingContentSchema$1,SamplingMessageContentBlockSchema:SamplingMessageContentBlockSchema$1,SamplingMessageSchema:SamplingMessageSchema$1,CreateMessageRequestParamsSchema:CreateMessageRequestParamsSchema$1,CreateMessageRequestSchema:CreateMessageRequestSchema$1,CreateMessageResultSchema:CreateMessageResultSchema$1,CreateMessageResultWithToolsSchema:CreateMessageResultWithToolsSchema$1,BooleanSchemaSchema:BooleanSchemaSchema$1,StringSchemaSchema:StringSchemaSchema$1,NumberSchemaSchema:NumberSchemaSchema$1,UntitledSingleSelectEnumSchemaSchema:UntitledSingleSelectEnumSchemaSchema$1,TitledSingleSelectEnumSchemaSchema:TitledSingleSelectEnumSchemaSchema$1,LegacyTitledEnumSchemaSchema:LegacyTitledEnumSchemaSchema$1,SingleSelectEnumSchemaSchema:SingleSelectEnumSchemaSchema$1,UntitledMultiSelectEnumSchemaSchema:UntitledMultiSelectEnumSchemaSchema$1,TitledMultiSelectEnumSchemaSchema:TitledMultiSelectEnumSchemaSchema$1,MultiSelectEnumSchemaSchema:MultiSelectEnumSchemaSchema$1,EnumSchemaSchema:EnumSchemaSchema$1,PrimitiveSchemaDefinitionSchema:PrimitiveSchemaDefinitionSchema$1,ElicitRequestFormParamsSchema:ElicitRequestFormParamsSchema$1,ElicitRequestURLParamsSchema:ElicitRequestURLParamsSchema$1,ElicitRequestParamsSchema:ElicitRequestParamsSchema$1,ElicitRequestSchema:ElicitRequestSchema$1,ElicitationCompleteNotificationParamsSchema:ElicitationCompleteNotificationParamsSchema$1,ElicitationCompleteNotificationSchema:ElicitationCompleteNotificationSchema$1,ElicitResultSchema:ElicitResultSchema$1,ResourceTemplateReferenceSchema:ResourceTemplateReferenceSchema$1,PromptReferenceSchema:PromptReferenceSchema$1,CompleteRequestParamsSchema:CompleteRequestParamsSchema$1,CompleteRequestSchema:CompleteRequestSchema$1,CompleteResultSchema:CompleteResultSchema$1,RootSchema:RootSchema$1,ListRootsRequestSchema:ListRootsRequestSchema$1,ListRootsResultSchema:ListRootsResultSchema$1,RootsListChangedNotificationSchema:RootsListChangedNotificationSchema$1,TaskCreationParamsSchema:TaskCreationParamsSchema$1,TaskStatusSchema:TaskStatusSchema$1,TaskSchema:TaskSchema$1,CreateTaskResultSchema:CreateTaskResultSchema$1,TaskStatusNotificationParamsSchema:TaskStatusNotificationParamsSchema$1,TaskStatusNotificationSchema:TaskStatusNotificationSchema$1,GetTaskRequestSchema:GetTaskRequestSchema$1,GetTaskResultSchema:GetTaskResultSchema$1,GetTaskPayloadRequestSchema:GetTaskPayloadRequestSchema$1,GetTaskPayloadResultSchema:GetTaskPayloadResultSchema$1,ListTasksRequestSchema:ListTasksRequestSchema$1,ListTasksResultSchema:ListTasksResultSchema$1,CancelTaskRequestSchema:CancelTaskRequestSchema$1,CancelTaskResultSchema:ResultSchema$1.merge(TaskSchema$1),ClientRequestSchema:union([PingRequestSchema$1,InitializeRequestSchema$1,CompleteRequestSchema$1,SetLevelRequestSchema$1,GetPromptRequestSchema$1,ListPromptsRequestSchema$1,ListResourcesRequestSchema$1,ListResourceTemplatesRequestSchema$1,ReadResourceRequestSchema$1,SubscribeRequestSchema$1,UnsubscribeRequestSchema$1,CallToolRequestSchema$1,ListToolsRequestSchema$1,GetTaskRequestSchema$1,GetTaskPayloadRequestSchema$1,ListTasksRequestSchema$1,CancelTaskRequestSchema$1]),ClientNotificationSchema:union([CancelledNotificationSchema$1,ProgressNotificationSchema$1,InitializedNotificationSchema$1,RootsListChangedNotificationSchema$1,TaskStatusNotificationSchema$1]),ClientResultSchema:union([EmptyResultSchema$1,CreateMessageResultSchema$1,CreateMessageResultWithToolsSchema$1,ElicitResultSchema$1,ListRootsResultSchema$1,GetTaskResultSchema$1,ListTasksResultSchema$1,CreateTaskResultSchema$1]),ServerRequestSchema:union([PingRequestSchema$1,CreateMessageRequestSchema$1,ElicitRequestSchema$1,ListRootsRequestSchema$1,GetTaskRequestSchema$1,GetTaskPayloadRequestSchema$1,ListTasksRequestSchema$1,CancelTaskRequestSchema$1]),ServerNotificationSchema:union([CancelledNotificationSchema$1,ProgressNotificationSchema$1,LoggingMessageNotificationSchema$1,ResourceUpdatedNotificationSchema$1,ResourceListChangedNotificationSchema$1,ToolListChangedNotificationSchema$1,PromptListChangedNotificationSchema$1,TaskStatusNotificationSchema$1,ElicitationCompleteNotificationSchema$1]),ServerResultSchema:union([EmptyResultSchema$1,InitializeResultSchema$1,CompleteResultSchema$1,GetPromptResultSchema$1,ListPromptsResultSchema$1,ListResourcesResultSchema$1,ListResourceTemplatesResultSchema$1,ReadResourceResultSchema$1,CallToolResultSchema$1,ListToolsResultSchema$1,GetTaskResultSchema$1,ListTasksResultSchema$1,CreateTaskResultSchema$1]),CallToolResultWireSchema:unknown().superRefine((value,ctx)=>{if(!(typeof value!="object"||value===null||Array.isArray(value)||value.content!==void 0)){for(let key of TOOL_RESULT_FOREIGN_FAMILY_KEYS)if(key in value){ctx.addIssue({code:"custom",message:`content is required when the body carries '${key}' \u2014 another result family cannot default into an empty tools/call success`});return}}}).transform(normalizeContentlessToolResult).pipe(CallToolResultSchema$1)}}function buildSchemas2025(){return memo$1??=build$1()}function isNonObjectJsonSchemaRoot(json){return json.type!=="object"}function establishesNewBase(id){return id!==void 0&&!(typeof id=="string"&&id.startsWith("#"))}function wrapOutputSchemaForLegacy(natural){let $schema=typeof natural.$schema=="string"?natural.$schema:void 0;if(establishesNewBase(natural.$id))return{...$schema!==void 0&&{$schema},type:"object",properties:{result:natural},required:["result"]};let convertRecursiveRefs=declares2019Dialect(natural.$schema)&&natural.$recursiveAnchor!==!0,rewriteRefs=(node,parentIsNameMap)=>{if(Array.isArray(node))return node.map(item=>rewriteRefs(item,!1));if(node===null||typeof node!="object"||!parentIsNameMap&&establishesNewBase(node.$id))return node;let out={},convertedRecursion=!1;for(let[k,v]of Object.entries(node))parentIsNameMap?out[k]=rewriteRefs(v,!1):(k==="$ref"||k==="$dynamicRef")&&typeof v=="string"?out[k]=v==="#"?"#/properties/result":v.startsWith("#/")?`#/properties/result${v.slice(1)}`:v:k==="$recursiveRef"&&v==="#"&&convertRecursiveRefs?convertedRecursion=!0:REF_REWRITE_DATA_POSITION_KEYS.has(k)?out[k]=v:REF_REWRITE_NAME_MAP_KEYS.has(k)?out[k]=rewriteRefs(v,!0):out[k]=rewriteRefs(v,!1);return convertedRecursion&&("$ref"in out?out.allOf=[...Array.isArray(out.allOf)?out.allOf:[],{$ref:"#/properties/result"}]:out.$ref="#/properties/result"),out};return{...$schema!==void 0&&{$schema},type:"object",properties:{result:rewriteRefs(natural,!1)},required:["result"]}}function registryMaps(){if(maps$1)return maps$1;let s=buildSchemas2025();return maps$1={requestSchemas:{ping:s.PingRequestSchema,initialize:s.InitializeRequestSchema,"completion/complete":s.CompleteRequestSchema,"logging/setLevel":s.SetLevelRequestSchema,"prompts/get":s.GetPromptRequestSchema,"prompts/list":s.ListPromptsRequestSchema,"resources/list":s.ListResourcesRequestSchema,"resources/templates/list":s.ListResourceTemplatesRequestSchema,"resources/read":s.ReadResourceRequestSchema,"resources/subscribe":s.SubscribeRequestSchema,"resources/unsubscribe":s.UnsubscribeRequestSchema,"tools/call":s.CallToolRequestSchema,"tools/list":s.ListToolsRequestSchema,"tasks/get":s.GetTaskRequestSchema,"tasks/result":s.GetTaskPayloadRequestSchema,"tasks/list":s.ListTasksRequestSchema,"tasks/cancel":s.CancelTaskRequestSchema,"sampling/createMessage":s.CreateMessageRequestSchema,"elicitation/create":s.ElicitRequestSchema,"roots/list":s.ListRootsRequestSchema},notificationSchemas:{"notifications/cancelled":s.CancelledNotificationSchema,"notifications/progress":s.ProgressNotificationSchema,"notifications/initialized":s.InitializedNotificationSchema,"notifications/roots/list_changed":s.RootsListChangedNotificationSchema,"notifications/tasks/status":s.TaskStatusNotificationSchema,"notifications/message":s.LoggingMessageNotificationSchema,"notifications/resources/updated":s.ResourceUpdatedNotificationSchema,"notifications/resources/list_changed":s.ResourceListChangedNotificationSchema,"notifications/tools/list_changed":s.ToolListChangedNotificationSchema,"notifications/prompts/list_changed":s.PromptListChangedNotificationSchema,"notifications/elicitation/complete":s.ElicitationCompleteNotificationSchema},resultSchemas:{ping:s.EmptyResultSchema,initialize:s.InitializeResultSchema,"completion/complete":s.CompleteResultSchema,"logging/setLevel":s.EmptyResultSchema,"prompts/get":s.GetPromptResultSchema,"prompts/list":s.ListPromptsResultSchema,"resources/list":s.ListResourcesResultSchema,"resources/templates/list":s.ListResourceTemplatesResultSchema,"resources/read":s.ReadResourceResultSchema,"resources/subscribe":s.EmptyResultSchema,"resources/unsubscribe":s.EmptyResultSchema,"tools/call":s.CallToolResultWireSchema,"tools/list":s.ListToolsResultSchema,"sampling/createMessage":s.CreateMessageResultWithToolsSchema,"elicitation/create":s.ElicitResultSchema,"roots/list":s.ListRootsResultSchema}},maps$1}function hasRequestMethod2025(method){return Object.prototype.hasOwnProperty.call(requestMethodKeys$1,method)}function hasNotificationMethod2025(method){return Object.prototype.hasOwnProperty.call(notificationMethodKeys$1,method)}function hasResultMethod(method){return Object.prototype.hasOwnProperty.call(resultMethodKeys,method)}function getResultSchema(method){return hasResultMethod(method)?registryMaps().resultSchemas[method]:void 0}function getRequestSchema(method){return hasRequestMethod2025(method)?registryMaps().requestSchemas[method]:void 0}function getNotificationSchema(method){return hasNotificationMethod2025(method)?registryMaps().notificationSchemas[method]:void 0}function isPlainObject$6(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function triState$1(schema2,raw2){if(schema2===void 0)return{ok:!1,reason:"not-in-era"};let parsed=schema2.safeParse(raw2);return parsed.success?{ok:!0,value:parsed.data}:{ok:!1,reason:"invalid",message:String(parsed.error)}}function toolNeedsLegacyWrap(t){return isPlainObject$6(t)&&isPlainObject$6(t.outputSchema)&&isNonObjectJsonSchemaRoot(t.outputSchema)}function build(){let JSONValueSchema$1=lazy(()=>union([string2(),number2(),boolean2(),_null3(),record(string2(),JSONValueSchema$1),array(JSONValueSchema$1)])),JSONObjectSchema$1=record(string2(),JSONValueSchema$1),ProgressTokenSchema$1=union([string2(),number2().int()]),CursorSchema$1=string2(),RequestIdSchema$1=union([string2(),number2().int()]),RoleSchema$1=_enum(["user","assistant"]),LoggingLevelSchema$1=_enum(["debug","info","notice","warning","error","critical","alert","emergency"]),Base64Schema2=string2().refine(val=>{try{return atob(val),!0}catch{return!1}},{message:"Invalid Base64 string"}),TaskMetadataSchema$1=object({ttl:number2().optional()}),RelatedTaskMetadataSchema$1=object({taskId:string2()}),RequestMetaSchema$1=looseObject({progressToken:ProgressTokenSchema$1.optional(),"io.modelcontextprotocol/related-task":RelatedTaskMetadataSchema$1.optional()}),BaseRequestParamsSchema$1=object({_meta:RequestMetaSchema$1.optional()}),TaskAugmentedRequestParamsSchema$1=BaseRequestParamsSchema$1.extend({task:TaskMetadataSchema$1.optional()}),NotificationsParamsSchema$1=object({_meta:RequestMetaSchema$1.optional()}),NotificationSchema$1=object({method:string2(),params:NotificationsParamsSchema$1.loose().optional()}),IconSchema$1=object({src:string2(),mimeType:string2().optional(),sizes:array(string2()).optional(),theme:_enum(["light","dark"]).optional()}),IconsSchema$1=object({icons:array(IconSchema$1).optional()}),BaseMetadataSchema$1=object({name:string2(),title:string2().optional()}),ImplementationSchema$1=BaseMetadataSchema$1.extend({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,version:string2(),websiteUrl:string2().optional(),description:string2().optional()}),FormElicitationCapabilitySchema2=intersection(object({applyDefaults:boolean2().optional()}),JSONObjectSchema$1),ElicitationCapabilitySchema2=preprocess(value=>value&&typeof value=="object"&&!Array.isArray(value)&&Object.keys(value).length===0?{form:{}}:value,intersection(object({form:FormElicitationCapabilitySchema2.optional(),url:JSONObjectSchema$1.optional()}),JSONObjectSchema$1.optional())),ClientTasksCapabilitySchema$1=looseObject({list:JSONObjectSchema$1.optional(),cancel:JSONObjectSchema$1.optional(),requests:looseObject({sampling:looseObject({createMessage:JSONObjectSchema$1.optional()}).optional(),elicitation:looseObject({create:JSONObjectSchema$1.optional()}).optional()}).optional()}),ServerTasksCapabilitySchema$1=looseObject({list:JSONObjectSchema$1.optional(),cancel:JSONObjectSchema$1.optional(),requests:looseObject({tools:looseObject({call:JSONObjectSchema$1.optional()}).optional()}).optional()}),ClientCapabilitiesSchema$1=object({experimental:record(string2(),JSONObjectSchema$1).optional(),sampling:object({context:JSONObjectSchema$1.optional(),tools:JSONObjectSchema$1.optional()}).optional(),elicitation:ElicitationCapabilitySchema2.optional(),roots:object({listChanged:boolean2().optional()}).optional(),tasks:ClientTasksCapabilitySchema$1.optional(),extensions:record(string2(),JSONObjectSchema$1).optional()}),ServerCapabilitiesSchema$1=object({experimental:record(string2(),JSONObjectSchema$1).optional(),logging:JSONObjectSchema$1.optional(),completions:JSONObjectSchema$1.optional(),prompts:object({listChanged:boolean2().optional()}).optional(),resources:object({subscribe:boolean2().optional(),listChanged:boolean2().optional()}).optional(),tools:object({listChanged:boolean2().optional()}).optional(),tasks:ServerTasksCapabilitySchema$1.optional(),extensions:record(string2(),JSONObjectSchema$1).optional()}),ProgressSchema$1=object({progress:number2(),total:optional(number2()),message:optional(string2())}),ProgressNotificationParamsSchema$1=object({...NotificationsParamsSchema$1.shape,...ProgressSchema$1.shape,progressToken:ProgressTokenSchema$1}),ProgressNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/progress"),params:ProgressNotificationParamsSchema$1}),LoggingMessageNotificationParamsSchema$1=NotificationsParamsSchema$1.extend({level:LoggingLevelSchema$1,logger:string2().optional(),data:unknown()}),LoggingMessageNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/message"),params:LoggingMessageNotificationParamsSchema$1}),ResourceContentsSchema$1=object({uri:string2(),mimeType:optional(string2()),_meta:record(string2(),unknown()).optional()}),TextResourceContentsSchema$1=ResourceContentsSchema$1.extend({text:string2()}),BlobResourceContentsSchema$1=ResourceContentsSchema$1.extend({blob:Base64Schema2}),AnnotationsSchema$1=object({audience:array(RoleSchema$1).optional(),priority:number2().min(0).max(1).optional(),lastModified:iso_exports.datetime({offset:!0}).optional()}),ResourceSchema$1=object({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,uri:string2(),description:optional(string2()),mimeType:optional(string2()),size:optional(number2()),annotations:AnnotationsSchema$1.optional(),_meta:optional(looseObject({}))}),ResourceTemplateSchema$1=object({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,uriTemplate:string2(),description:optional(string2()),mimeType:optional(string2()),annotations:AnnotationsSchema$1.optional(),_meta:optional(looseObject({}))}),ResourceListChangedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/resources/list_changed"),params:NotificationsParamsSchema$1.optional()}),ResourceUpdatedNotificationParamsSchema$1=NotificationsParamsSchema$1.extend({uri:string2()}),ResourceUpdatedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/resources/updated"),params:ResourceUpdatedNotificationParamsSchema$1}),PromptArgumentSchema$1=object({name:string2(),description:optional(string2()),required:optional(boolean2())}),PromptSchema$1=object({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,description:optional(string2()),arguments:optional(array(PromptArgumentSchema$1)),_meta:optional(looseObject({}))}),PromptListChangedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/prompts/list_changed"),params:NotificationsParamsSchema$1.optional()}),TextContentSchema$1=object({type:literal("text"),text:string2(),annotations:AnnotationsSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),ImageContentSchema$1=object({type:literal("image"),data:Base64Schema2,mimeType:string2(),annotations:AnnotationsSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),AudioContentSchema$1=object({type:literal("audio"),data:Base64Schema2,mimeType:string2(),annotations:AnnotationsSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),ToolUseContentSchema$1=object({type:literal("tool_use"),name:string2(),id:string2(),input:record(string2(),unknown()),_meta:record(string2(),unknown()).optional()}),EmbeddedResourceSchema$1=object({type:literal("resource"),resource:union([TextResourceContentsSchema$1,BlobResourceContentsSchema$1]),annotations:AnnotationsSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),ResourceLinkSchema$1=ResourceSchema$1.extend({type:literal("resource_link")}),ContentBlockSchema$1=union([TextContentSchema$1,ImageContentSchema$1,AudioContentSchema$1,ResourceLinkSchema$1,EmbeddedResourceSchema$1]),PromptMessageSchema$1=object({role:RoleSchema$1,content:ContentBlockSchema$1}),ToolAnnotationsSchema$1=object({title:string2().optional(),readOnlyHint:boolean2().optional(),destructiveHint:boolean2().optional(),idempotentHint:boolean2().optional(),openWorldHint:boolean2().optional()}),ToolListChangedNotificationSchema$1=NotificationSchema$1.extend({method:literal("notifications/tools/list_changed"),params:NotificationsParamsSchema$1.optional()}),ModelHintSchema$1=object({name:string2().optional()}),ModelPreferencesSchema$1=object({hints:array(ModelHintSchema$1).optional(),costPriority:number2().min(0).max(1).optional(),speedPriority:number2().min(0).max(1).optional(),intelligencePriority:number2().min(0).max(1).optional()}),ToolChoiceSchema$1=object({mode:_enum(["auto","required","none"]).optional()}),BooleanSchemaSchema$1=object({type:literal("boolean"),title:string2().optional(),description:string2().optional(),default:boolean2().optional()}),StringSchemaSchema$1=object({type:literal("string"),title:string2().optional(),description:string2().optional(),minLength:number2().optional(),maxLength:number2().optional(),format:_enum(["email","uri","date","date-time"]).optional(),default:string2().optional()}),NumberSchemaSchema$1=object({type:_enum(["number","integer"]),title:string2().optional(),description:string2().optional(),minimum:number2().optional(),maximum:number2().optional(),default:number2().optional()}),UntitledSingleSelectEnumSchemaSchema$1=object({type:literal("string"),title:string2().optional(),description:string2().optional(),enum:array(string2()),default:string2().optional()}),TitledSingleSelectEnumSchemaSchema$1=object({type:literal("string"),title:string2().optional(),description:string2().optional(),oneOf:array(object({const:string2(),title:string2()})),default:string2().optional()}),LegacyTitledEnumSchemaSchema$1=object({type:literal("string"),title:string2().optional(),description:string2().optional(),enum:array(string2()),enumNames:array(string2()).optional(),default:string2().optional()}),SingleSelectEnumSchemaSchema$1=union([UntitledSingleSelectEnumSchemaSchema$1,TitledSingleSelectEnumSchemaSchema$1]),UntitledMultiSelectEnumSchemaSchema$1=object({type:literal("array"),title:string2().optional(),description:string2().optional(),minItems:number2().optional(),maxItems:number2().optional(),items:object({type:literal("string"),enum:array(string2())}),default:array(string2()).optional()}),TitledMultiSelectEnumSchemaSchema$1=object({type:literal("array"),title:string2().optional(),description:string2().optional(),minItems:number2().optional(),maxItems:number2().optional(),items:object({anyOf:array(object({const:string2(),title:string2()}))}),default:array(string2()).optional()}),MultiSelectEnumSchemaSchema$1=union([UntitledMultiSelectEnumSchemaSchema$1,TitledMultiSelectEnumSchemaSchema$1]),EnumSchemaSchema$1=union([LegacyTitledEnumSchemaSchema$1,SingleSelectEnumSchemaSchema$1,MultiSelectEnumSchemaSchema$1]),PrimitiveSchemaDefinitionSchema$1=union([EnumSchemaSchema$1,BooleanSchemaSchema$1,StringSchemaSchema$1,NumberSchemaSchema$1]),ElicitRequestFormParamsSchema$1=TaskAugmentedRequestParamsSchema$1.extend({mode:literal("form").optional(),message:string2(),requestedSchema:object({type:literal("object"),properties:record(string2(),PrimitiveSchemaDefinitionSchema$1),required:array(string2()).optional()}).catchall(unknown())}),ResourceTemplateReferenceSchema$1=object({type:literal("ref/resource"),uri:string2()}),PromptReferenceSchema$1=object({type:literal("ref/prompt"),name:string2()}),RootSchema$1=object({uri:string2().startsWith("file://"),name:string2().optional(),_meta:record(string2(),unknown()).optional()}),sharedClientCapabilityShape=ClientCapabilitiesSchema$1.shape,ClientCapabilities2026Schema=object({experimental:sharedClientCapabilityShape.experimental,sampling:sharedClientCapabilityShape.sampling,elicitation:sharedClientCapabilityShape.elicitation,roots:sharedClientCapabilityShape.roots,extensions:sharedClientCapabilityShape.extensions}),sharedServerCapabilityShape=ServerCapabilitiesSchema$1.shape,ServerCapabilities2026Schema=object({experimental:sharedServerCapabilityShape.experimental,logging:sharedServerCapabilityShape.logging,completions:sharedServerCapabilityShape.completions,prompts:sharedServerCapabilityShape.prompts,resources:sharedServerCapabilityShape.resources,tools:sharedServerCapabilityShape.tools,extensions:sharedServerCapabilityShape.extensions}),RequestMetaEnvelopeSchema=looseObject({progressToken:ProgressTokenSchema$1.optional(),[PROTOCOL_VERSION_META_KEY]:string2(),[CLIENT_INFO_META_KEY]:ImplementationSchema$1.optional(),[CLIENT_CAPABILITIES_META_KEY]:ClientCapabilities2026Schema,[LOG_LEVEL_META_KEY]:LoggingLevelSchema$1.optional()}),ToolSchema$1=object({...BaseMetadataSchema$1.shape,...IconsSchema$1.shape,description:string2().optional(),inputSchema:looseObject({$schema:string2().optional(),type:literal("object")}),outputSchema:looseObject({$schema:string2().optional()}).optional(),annotations:ToolAnnotationsSchema$1.optional(),_meta:record(string2(),unknown()).optional()}),ToolResultContentSchema$1=object({type:literal("tool_result"),toolUseId:string2(),content:array(ContentBlockSchema$1),structuredContent:unknown().optional(),isError:boolean2().optional(),_meta:record(string2(),unknown()).optional()}),SamplingMessageContentBlockSchema$1=union([TextContentSchema$1,ImageContentSchema$1,AudioContentSchema$1,ToolUseContentSchema$1,ToolResultContentSchema$1]),SamplingMessageSchema$1=object({role:RoleSchema$1,content:union([SamplingMessageContentBlockSchema$1,array(SamplingMessageContentBlockSchema$1)]),_meta:record(string2(),unknown()).optional()}),ResultTypeSchema=string2(),ResultMetaSchema=looseObject({[SERVER_INFO_META_KEY]:ImplementationSchema$1.optional().catch(void 0)}),wireMeta=ResultMetaSchema.optional();function wireResult(shape){return looseObject({_meta:wireMeta,resultType:ResultTypeSchema.default("complete"),...shape})}let ResultSchema$1=wireResult({}),PaginatedResultSchema$1=wireResult({nextCursor:CursorSchema$1.optional()}),CallToolResultSchema$1=wireResult({content:array(ContentBlockSchema$1),structuredContent:unknown().optional(),isError:boolean2().optional()}),ListToolsResultSchema$1=wireResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),tools:array(ToolSchema$1),nextCursor:CursorSchema$1.optional()}),ListPromptsResultSchema$1=wireResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),prompts:array(PromptSchema$1),nextCursor:CursorSchema$1.optional()}),GetPromptResultSchema$1=wireResult({description:string2().optional(),messages:array(PromptMessageSchema$1)}),ListResourcesResultSchema$1=wireResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),resources:array(ResourceSchema$1),nextCursor:CursorSchema$1.optional()}),ListResourceTemplatesResultSchema$1=wireResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),resourceTemplates:array(ResourceTemplateSchema$1),nextCursor:CursorSchema$1.optional()}),ReadResourceResultSchema$1=wireResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),contents:array(union([TextResourceContentsSchema$1,BlobResourceContentsSchema$1]))}),CompleteResultSchema$1=wireResult({completion:object({values:array(string2()).max(100),total:number2().int().optional(),hasMore:boolean2().optional()}).loose()}),CacheableResultSchema=wireResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"])}),DiscoverResultSchema$1=wireResult({ttlMs:number2().int().min(0).catch(0),cacheScope:_enum(["public","private"]).catch("private"),supportedVersions:array(string2()),capabilities:ServerCapabilities2026Schema,instructions:string2().optional()}),CreateMessageRequestParamsSchema$1=object({messages:array(SamplingMessageSchema$1),modelPreferences:ModelPreferencesSchema$1.optional(),systemPrompt:string2().optional(),includeContext:_enum(["none","thisServer","allServers"]).optional(),temperature:number2().optional(),maxTokens:number2().int(),stopSequences:array(string2()).optional(),metadata:JSONObjectSchema$1.optional(),tools:array(ToolSchema$1).optional(),toolChoice:ToolChoiceSchema$1.optional()}),CreateMessageRequestSchema$1=object({method:literal("sampling/createMessage"),params:CreateMessageRequestParamsSchema$1}),ListRootsRequestSchema$1=object({method:literal("roots/list"),params:object({_meta:record(string2(),unknown()).optional()}).optional()}),CreateMessageResultSchema$1=object({...SamplingMessageSchema$1.shape,model:string2(),stopReason:string2().optional()}),ListRootsResultSchema$1=object({roots:array(RootSchema$1)}),ElicitResultSchema$1=object({action:_enum(["accept","decline","cancel"]),content:record(string2(),union([string2(),number2(),boolean2(),array(string2())])).optional()}),ElicitRequestURLParamsSchema$1=object({mode:literal("url"),message:string2(),url:string2().url()}),ElicitRequestParamsSchema$1=union([ElicitRequestFormParamsSchema$1,ElicitRequestURLParamsSchema$1]),ElicitRequestSchema$1=object({method:literal("elicitation/create"),params:ElicitRequestParamsSchema$1}),InputRequestSchema=union([CreateMessageRequestSchema$1,ListRootsRequestSchema$1,ElicitRequestSchema$1]),InputResponseSchema=union([CreateMessageResultSchema$1,ListRootsResultSchema$1,ElicitResultSchema$1]),InputRequestsSchema=record(string2(),InputRequestSchema),InputResponsesSchema=record(string2(),InputResponseSchema),InputRequiredResultSchema=wireResult({inputRequests:InputRequestsSchema.optional(),requestState:string2().optional()}),retryParamsShape={inputResponses:InputResponsesSchema.optional(),requestState:string2().optional()},InputResponseRequestParamsSchema=object({_meta:RequestMetaEnvelopeSchema,...retryParamsShape}),DispatchRequestMetaSchema=looseObject({progressToken:ProgressTokenSchema$1.optional()});function wireRequest(method,paramsShape){return object({method:literal(method),params:object({_meta:RequestMetaEnvelopeSchema,...paramsShape})})}function dispatchRequest(method,paramsShape){return object({method:literal(method),params:object({_meta:DispatchRequestMetaSchema.optional(),...paramsShape}).optional()})}let callToolParamsShape={name:string2(),arguments:record(string2(),unknown()).optional(),...retryParamsShape},paginatedParamsShape={cursor:CursorSchema$1.optional()},CallToolRequestSchema$1=wireRequest("tools/call",callToolParamsShape),ListToolsRequestSchema$1=wireRequest("tools/list",paginatedParamsShape),ListPromptsRequestSchema$1=wireRequest("prompts/list",paginatedParamsShape),GetPromptRequestSchema$1=wireRequest("prompts/get",{name:string2(),arguments:record(string2(),string2()).optional(),...retryParamsShape}),ListResourcesRequestSchema$1=wireRequest("resources/list",paginatedParamsShape),ListResourceTemplatesRequestSchema$1=wireRequest("resources/templates/list",paginatedParamsShape),ReadResourceRequestSchema$1=wireRequest("resources/read",{uri:string2(),...retryParamsShape}),completeParamsShape={ref:union([PromptReferenceSchema$1,ResourceTemplateReferenceSchema$1]),argument:object({name:string2(),value:string2()}),context:object({arguments:record(string2(),string2()).optional()}).optional()},CompleteRequestSchema$1=wireRequest("completion/complete",completeParamsShape),DiscoverRequestSchema$1=wireRequest("server/discover",{}),SubscriptionFilterSchema$1=object({toolsListChanged:boolean2().optional(),promptsListChanged:boolean2().optional(),resourcesListChanged:boolean2().optional(),resourceSubscriptions:array(string2()).optional()}),subscriptionsListenParamsShape={notifications:SubscriptionFilterSchema$1},SubscriptionsListenRequestSchema$1=wireRequest("subscriptions/listen",subscriptionsListenParamsShape),SubscriptionsListenResultMetaSchema$1=ResultMetaSchema.extend({"io.modelcontextprotocol/subscriptionId":RequestIdSchema$1}),SubscriptionsListenResultSchema$1=looseObject({_meta:SubscriptionsListenResultMetaSchema$1,resultType:ResultTypeSchema.default("complete")}),dispatchRequestSchemas={"tools/call":dispatchRequest("tools/call",callToolParamsShape),"tools/list":dispatchRequest("tools/list",paginatedParamsShape),"prompts/get":dispatchRequest("prompts/get",{name:string2(),arguments:record(string2(),string2()).optional()}),"prompts/list":dispatchRequest("prompts/list",paginatedParamsShape),"resources/list":dispatchRequest("resources/list",paginatedParamsShape),"resources/templates/list":dispatchRequest("resources/templates/list",paginatedParamsShape),"resources/read":dispatchRequest("resources/read",{uri:string2()}),"completion/complete":dispatchRequest("completion/complete",completeParamsShape),"server/discover":dispatchRequest("server/discover",{}),"subscriptions/listen":dispatchRequest("subscriptions/listen",subscriptionsListenParamsShape)};function liftedResult(shape){return looseObject({_meta:wireMeta,...shape})}let dispatchResultSchemas={"tools/call":liftedResult({content:array(ContentBlockSchema$1),structuredContent:unknown().optional(),isError:boolean2().optional()}),"tools/list":liftedResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),tools:array(ToolSchema$1),nextCursor:CursorSchema$1.optional()}),"prompts/get":liftedResult({description:string2().optional(),messages:array(PromptMessageSchema$1)}),"prompts/list":liftedResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),prompts:array(PromptSchema$1),nextCursor:CursorSchema$1.optional()}),"resources/list":liftedResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),resources:array(ResourceSchema$1),nextCursor:CursorSchema$1.optional()}),"resources/templates/list":liftedResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),resourceTemplates:array(ResourceTemplateSchema$1),nextCursor:CursorSchema$1.optional()}),"resources/read":liftedResult({ttlMs:number2().int().min(0),cacheScope:_enum(["public","private"]),contents:array(union([TextResourceContentsSchema$1,BlobResourceContentsSchema$1]))}),"completion/complete":liftedResult({completion:object({values:array(string2()).max(100),total:number2().int().optional(),hasMore:boolean2().optional()}).loose()}),"server/discover":liftedResult({ttlMs:number2().int().min(0).catch(0),cacheScope:_enum(["public","private"]).catch("private"),supportedVersions:array(string2()),capabilities:ServerCapabilities2026Schema,instructions:string2().optional()}),"subscriptions/listen":liftedResult({})},NotificationMetaSchema=looseObject({"io.modelcontextprotocol/subscriptionId":RequestIdSchema$1.optional()}),SubscriptionsAcknowledgedNotificationSchema$1=object({method:literal("notifications/subscriptions/acknowledged"),params:object({_meta:NotificationMetaSchema.optional(),notifications:SubscriptionFilterSchema$1})}),CancelledNotificationParamsSchema$1=object({_meta:NotificationMetaSchema.optional(),requestId:RequestIdSchema$1,reason:string2().optional()}),CancelledNotificationSchema$1=object({method:literal("notifications/cancelled"),params:CancelledNotificationParamsSchema$1}),notificationSchemas2026={"notifications/cancelled":CancelledNotificationSchema$1,"notifications/progress":ProgressNotificationSchema$1,"notifications/message":LoggingMessageNotificationSchema$1,"notifications/resources/updated":ResourceUpdatedNotificationSchema$1,"notifications/resources/list_changed":ResourceListChangedNotificationSchema$1,"notifications/tools/list_changed":ToolListChangedNotificationSchema$1,"notifications/prompts/list_changed":PromptListChangedNotificationSchema$1,"notifications/subscriptions/acknowledged":SubscriptionsAcknowledgedNotificationSchema$1},wireResultResponse=result=>object({jsonrpc:literal("2.0"),id:union([string2(),number2().int()]),result}).strict();return{JSONValueSchema:JSONValueSchema$1,JSONObjectSchema:JSONObjectSchema$1,ProgressTokenSchema:ProgressTokenSchema$1,CursorSchema:CursorSchema$1,RequestIdSchema:RequestIdSchema$1,RoleSchema:RoleSchema$1,LoggingLevelSchema:LoggingLevelSchema$1,TaskMetadataSchema:TaskMetadataSchema$1,RelatedTaskMetadataSchema:RelatedTaskMetadataSchema$1,RequestMetaSchema:RequestMetaSchema$1,BaseRequestParamsSchema:BaseRequestParamsSchema$1,TaskAugmentedRequestParamsSchema:TaskAugmentedRequestParamsSchema$1,NotificationsParamsSchema:NotificationsParamsSchema$1,NotificationSchema:NotificationSchema$1,IconSchema:IconSchema$1,IconsSchema:IconsSchema$1,BaseMetadataSchema:BaseMetadataSchema$1,ImplementationSchema:ImplementationSchema$1,ClientTasksCapabilitySchema:ClientTasksCapabilitySchema$1,ServerTasksCapabilitySchema:ServerTasksCapabilitySchema$1,ClientCapabilitiesSchema:ClientCapabilitiesSchema$1,ServerCapabilitiesSchema:ServerCapabilitiesSchema$1,ProgressSchema:ProgressSchema$1,ProgressNotificationParamsSchema:ProgressNotificationParamsSchema$1,ProgressNotificationSchema:ProgressNotificationSchema$1,LoggingMessageNotificationParamsSchema:LoggingMessageNotificationParamsSchema$1,LoggingMessageNotificationSchema:LoggingMessageNotificationSchema$1,ResourceContentsSchema:ResourceContentsSchema$1,TextResourceContentsSchema:TextResourceContentsSchema$1,BlobResourceContentsSchema:BlobResourceContentsSchema$1,AnnotationsSchema:AnnotationsSchema$1,ResourceSchema:ResourceSchema$1,ResourceTemplateSchema:ResourceTemplateSchema$1,ResourceListChangedNotificationSchema:ResourceListChangedNotificationSchema$1,ResourceUpdatedNotificationParamsSchema:ResourceUpdatedNotificationParamsSchema$1,ResourceUpdatedNotificationSchema:ResourceUpdatedNotificationSchema$1,PromptArgumentSchema:PromptArgumentSchema$1,PromptSchema:PromptSchema$1,PromptListChangedNotificationSchema:PromptListChangedNotificationSchema$1,TextContentSchema:TextContentSchema$1,ImageContentSchema:ImageContentSchema$1,AudioContentSchema:AudioContentSchema$1,ToolUseContentSchema:ToolUseContentSchema$1,EmbeddedResourceSchema:EmbeddedResourceSchema$1,ResourceLinkSchema:ResourceLinkSchema$1,ContentBlockSchema:ContentBlockSchema$1,PromptMessageSchema:PromptMessageSchema$1,ToolAnnotationsSchema:ToolAnnotationsSchema$1,ToolListChangedNotificationSchema:ToolListChangedNotificationSchema$1,ModelHintSchema:ModelHintSchema$1,ModelPreferencesSchema:ModelPreferencesSchema$1,ToolChoiceSchema:ToolChoiceSchema$1,BooleanSchemaSchema:BooleanSchemaSchema$1,StringSchemaSchema:StringSchemaSchema$1,NumberSchemaSchema:NumberSchemaSchema$1,UntitledSingleSelectEnumSchemaSchema:UntitledSingleSelectEnumSchemaSchema$1,TitledSingleSelectEnumSchemaSchema:TitledSingleSelectEnumSchemaSchema$1,LegacyTitledEnumSchemaSchema:LegacyTitledEnumSchemaSchema$1,SingleSelectEnumSchemaSchema:SingleSelectEnumSchemaSchema$1,UntitledMultiSelectEnumSchemaSchema:UntitledMultiSelectEnumSchemaSchema$1,TitledMultiSelectEnumSchemaSchema:TitledMultiSelectEnumSchemaSchema$1,MultiSelectEnumSchemaSchema:MultiSelectEnumSchemaSchema$1,EnumSchemaSchema:EnumSchemaSchema$1,PrimitiveSchemaDefinitionSchema:PrimitiveSchemaDefinitionSchema$1,ElicitRequestFormParamsSchema:ElicitRequestFormParamsSchema$1,ResourceTemplateReferenceSchema:ResourceTemplateReferenceSchema$1,PromptReferenceSchema:PromptReferenceSchema$1,RootSchema:RootSchema$1,ClientCapabilities2026Schema,ServerCapabilities2026Schema,RequestMetaEnvelopeSchema,ToolSchema:ToolSchema$1,ToolResultContentSchema:ToolResultContentSchema$1,SamplingMessageContentBlockSchema:SamplingMessageContentBlockSchema$1,SamplingMessageSchema:SamplingMessageSchema$1,ResultTypeSchema,ResultMetaSchema,ResultSchema:ResultSchema$1,PaginatedResultSchema:PaginatedResultSchema$1,CallToolResultSchema:CallToolResultSchema$1,ListToolsResultSchema:ListToolsResultSchema$1,ListPromptsResultSchema:ListPromptsResultSchema$1,GetPromptResultSchema:GetPromptResultSchema$1,ListResourcesResultSchema:ListResourcesResultSchema$1,ListResourceTemplatesResultSchema:ListResourceTemplatesResultSchema$1,ReadResourceResultSchema:ReadResourceResultSchema$1,CompleteResultSchema:CompleteResultSchema$1,CacheableResultSchema,DiscoverResultSchema:DiscoverResultSchema$1,CreateMessageRequestParamsSchema:CreateMessageRequestParamsSchema$1,CreateMessageRequestSchema:CreateMessageRequestSchema$1,ListRootsRequestSchema:ListRootsRequestSchema$1,CreateMessageResultSchema:CreateMessageResultSchema$1,ListRootsResultSchema:ListRootsResultSchema$1,ElicitResultSchema:ElicitResultSchema$1,ElicitRequestURLParamsSchema:ElicitRequestURLParamsSchema$1,ElicitRequestParamsSchema:ElicitRequestParamsSchema$1,ElicitRequestSchema:ElicitRequestSchema$1,InputRequestSchema,InputResponseSchema,InputRequestsSchema,InputResponsesSchema,InputRequiredResultSchema,InputResponseRequestParamsSchema,CallToolRequestSchema:CallToolRequestSchema$1,ListToolsRequestSchema:ListToolsRequestSchema$1,ListPromptsRequestSchema:ListPromptsRequestSchema$1,GetPromptRequestSchema:GetPromptRequestSchema$1,ListResourcesRequestSchema:ListResourcesRequestSchema$1,ListResourceTemplatesRequestSchema:ListResourceTemplatesRequestSchema$1,ReadResourceRequestSchema:ReadResourceRequestSchema$1,CompleteRequestSchema:CompleteRequestSchema$1,DiscoverRequestSchema:DiscoverRequestSchema$1,SubscriptionFilterSchema:SubscriptionFilterSchema$1,SubscriptionsListenRequestSchema:SubscriptionsListenRequestSchema$1,SubscriptionsListenResultMetaSchema:SubscriptionsListenResultMetaSchema$1,SubscriptionsListenResultSchema:SubscriptionsListenResultSchema$1,dispatchRequestSchemas,dispatchResultSchemas,NotificationMetaSchema,SubscriptionsAcknowledgedNotificationSchema:SubscriptionsAcknowledgedNotificationSchema$1,CancelledNotificationParamsSchema:CancelledNotificationParamsSchema$1,CancelledNotificationSchema:CancelledNotificationSchema$1,notificationSchemas2026,JSONRPCResultResponseSchema:wireResultResponse(ResultSchema$1),CallToolResultResponseSchema:wireResultResponse(union([CallToolResultSchema$1,InputRequiredResultSchema])),ListToolsResultResponseSchema:wireResultResponse(ListToolsResultSchema$1),ListPromptsResultResponseSchema:wireResultResponse(ListPromptsResultSchema$1),GetPromptResultResponseSchema:wireResultResponse(union([GetPromptResultSchema$1,InputRequiredResultSchema])),ListResourcesResultResponseSchema:wireResultResponse(ListResourcesResultSchema$1),ListResourceTemplatesResultResponseSchema:wireResultResponse(ListResourceTemplatesResultSchema$1),ReadResourceResultResponseSchema:wireResultResponse(union([ReadResourceResultSchema$1,InputRequiredResultSchema])),CompleteResultResponseSchema:wireResultResponse(CompleteResultSchema$1),DiscoverResultResponseSchema:wireResultResponse(DiscoverResultSchema$1)}}function buildSchemas2026(){return memo??=build()}function isCacheableResultMethod(method){return CACHEABLE_RESULT_METHODS.includes(method)}function attachCacheHintFallback(result,hint){if(hint===void 0)return result;let attached=result[RESULT_CACHE_HINT_FALLBACK];if(attached===void 0)return{...result,[RESULT_CACHE_HINT_FALLBACK]:hint};let merged={},ttlMs=attached.ttlMs??hint.ttlMs;ttlMs!==void 0&&(merged.ttlMs=ttlMs);let cacheScope=attached.cacheScope??hint.cacheScope;return cacheScope!==void 0&&(merged.cacheScope=cacheScope),{...result,[RESULT_CACHE_HINT_FALLBACK]:merged}}function cacheHintFallbackOf(result){return result[RESULT_CACHE_HINT_FALLBACK]}function isValidCacheTtlMs(value){return typeof value=="number"&&Number.isSafeInteger(value)&&value>=0}function isValidCacheScope(value){return value==="public"||value==="private"}function assertValidCacheHint(hint,context){if(hint.ttlMs!==void 0&&!isValidCacheTtlMs(hint.ttlMs))throw new RangeError(`Invalid cache hint for ${context}: ttlMs must be a non-negative safe integer (got ${String(hint.ttlMs)})`);if(hint.cacheScope!==void 0&&!isValidCacheScope(hint.cacheScope))throw new RangeError(`Invalid cache hint for ${context}: cacheScope must be 'public' or 'private' (got ${String(hint.cacheScope)})`)}function stampResultType(method,result){let provided=result.resultType;if(provided===void 0)return{...result,resultType:"complete"};if(provided==="complete"||EXTENDED_RESULT_TYPE_METHODS.includes(method))return result;throw new ProtocolError(ProtocolErrorCode.InternalError,`Handler for ${method} returned resultType '${String(provided)}', but results of ${method} only support 'complete' on protocol revision 2026-07-28`)}function fillCacheFields(method,result){let fallback=cacheHintFallbackOf(result);if(result.resultType!=="complete"||!isCacheableResultMethod(method))return fallback===void 0?result:stripCacheHintFallback(result);let provided=result,ttlMs=isValidCacheTtlMs(provided.ttlMs)?provided.ttlMs:resolveTtlMs(fallback),cacheScope=isValidCacheScope(provided.cacheScope)?provided.cacheScope:resolveCacheScope(fallback),filled={...provided,ttlMs,cacheScope};return delete filled[RESULT_CACHE_HINT_FALLBACK],filled}function isPlainObject$5(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function stampServerInfoMeta(result,serverInfo){if(serverInfo===void 0)return result;let meta2=result._meta;return meta2===void 0?{...result,_meta:{[SERVER_INFO_META_KEY]:serverInfo}}:!isPlainObject$5(meta2)||meta2[SERVER_INFO_META_KEY]!==void 0?result:{...result,_meta:{...meta2,[SERVER_INFO_META_KEY]:serverInfo}}}function resolveTtlMs(fallback){return fallback!==void 0&&isValidCacheTtlMs(fallback.ttlMs)?fallback.ttlMs:DEFAULT_CACHE_TTL_MS}function resolveCacheScope(fallback){return fallback!==void 0&&isValidCacheScope(fallback.cacheScope)?fallback.cacheScope:DEFAULT_CACHE_SCOPE}function stripCacheHintFallback(result){let copy={...result};return delete copy[RESULT_CACHE_HINT_FALLBACK],copy}function inputSchemaMaps(){if(maps)return maps;let s=buildSchemas2026();return maps={request:{"elicitation/create":object({method:literal("elicitation/create"),params:s.ElicitRequestParamsSchema}),"sampling/createMessage":object({method:literal("sampling/createMessage"),params:s.CreateMessageRequestParamsSchema}),"roots/list":object({method:literal("roots/list"),params:looseObject({}).optional()})},response:{"elicitation/create":s.ElicitResultSchema,"sampling/createMessage":s.CreateMessageResultSchema,"roots/list":s.ListRootsResultSchema}},maps}function isInputRequestMethod2026(method){return INPUT_REQUEST_METHODS_2026.includes(method)}function getInputRequestSchema2026(method){return isInputRequestMethod2026(method)?inputSchemaMaps().request[method]:void 0}function getInputResponseSchema2026(method){return isInputRequestMethod2026(method)?inputSchemaMaps().response[method]:void 0}function hasRequestMethod2026(method){return Object.prototype.hasOwnProperty.call(requestMethodKeys,method)}function hasNotificationMethod2026(method){return Object.prototype.hasOwnProperty.call(notificationMethodKeys,method)}function hasResultMethod2026(method){return Object.prototype.hasOwnProperty.call(requestMethodKeys,method)}function getRequestSchema2026(method){return hasRequestMethod2026(method)?buildSchemas2026().dispatchRequestSchemas[method]:void 0}function getResultSchema2026(method){return hasResultMethod2026(method)?buildSchemas2026().dispatchResultSchemas[method]:void 0}function getNotificationSchema2026(method){return hasNotificationMethod2026(method)?buildSchemas2026().notificationSchemas2026[method]:void 0}function isPlainObject$4(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function triState(schema2,raw2){if(schema2===void 0)return{ok:!1,reason:"not-in-era"};let parsed=schema2.safeParse(raw2);return parsed.success?{ok:!0,value:parsed.data}:{ok:!1,reason:"invalid",message:String(parsed.error)}}function enforceDeletedFields(method,result){let next=result,copied=!1,copy=()=>(copied||(next={...next},copied=!0),next),tools=result.tools;method==="tools/list"&&Array.isArray(tools)&&tools.some(tool=>isPlainObject$4(tool)&&"execution"in tool)&&(copy().tools=tools.map(tool=>{if(!isPlainObject$4(tool)||!("execution"in tool))return tool;let rest={...tool};return delete rest.execution,rest}));let capabilities=result.capabilities;if(isPlainObject$4(capabilities)&&"tasks"in capabilities){let rest={...capabilities};delete rest.tasks,copy().capabilities=rest}return next}function getWireResultSchemas(){if(wireResultSchemasMemo)return wireResultSchemasMemo;let s=buildSchemas2026();return wireResultSchemasMemo={"tools/call":s.CallToolResultSchema,"tools/list":s.ListToolsResultSchema,"prompts/get":s.GetPromptResultSchema,"prompts/list":s.ListPromptsResultSchema,"resources/list":s.ListResourcesResultSchema,"resources/templates/list":s.ListResourceTemplatesResultSchema,"resources/read":s.ReadResourceResultSchema,"completion/complete":s.CompleteResultSchema,"server/discover":s.DiscoverResultSchema},wireResultSchemasMemo}function codecForVersion(version2){return version2!==void 0&&isModernProtocolVersion(version2)?rev2026Codec:rev2025Codec}function classifiedWireEra(classification){return classification.revision!==void 0?codecForVersion(classification.revision).era:classification.era==="modern"?rev2026Codec.era:rev2025Codec.era}function isSpecRequestMethod(method){return ALL_CODECS.some(codec=>codec.hasRequestMethod(method))}function isSpecNotificationMethod(method){return ALL_CODECS.some(codec=>codec.hasNotificationMethod(method))}function isPlainObject$3(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function requestMetaOf(params){if(!isPlainObject$3(params))return;let meta2=params._meta;return isPlainObject$3(meta2)?meta2:void 0}function hasEnvelopeClaim(params){let meta2=requestMetaOf(params);return meta2!==void 0&&PROTOCOL_VERSION_META_KEY in meta2}function envelopeClaimVersion(params){let value=requestMetaOf(params)?.[PROTOCOL_VERSION_META_KEY];return typeof value=="string"?value:void 0}function validateEnvelopeMeta(meta2){return codecForVersion(MODERN_WIRE_REVISION).validateEnvelopeMeta(meta2)}function assertCompleteRequestPrompt(request){if(request.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`)}function assertCompleteRequestResourceTemplate(request){if(request.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`)}function scanXMcpHeaderDeclarations(inputSchema){let declarations=[],seenLower=new Map,visit=(node,path,reachable)=>{if(node===null||typeof node!="object")return;let schema2=node;if(X_MCP_HEADER_KEY in schema2){if(!reachable||path.length===0)return`${pathName(path)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;let raw2=schema2[X_MCP_HEADER_KEY];if(typeof raw2!="string"||raw2.length===0)return`${pathName(path)}: x-mcp-header MUST be a non-empty string`;if(!RFC9110_TOKEN.test(raw2))return`${pathName(path)}: x-mcp-header '${raw2}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;let type=typeof schema2.type=="string"?schema2.type:void 0;if(type===void 0||!PERMITTED_X_MCP_HEADER_TYPES.has(type))return`${pathName(path)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${type??"<none>"}`;let lower=raw2.toLowerCase(),prior=seenLower.get(lower);if(prior!==void 0)return`x-mcp-header '${raw2}' is not case-insensitively unique (also declared as '${prior}')`;seenLower.set(lower,raw2),declarations.push({path,headerName:raw2,type})}let properties=schema2.properties;if(properties!==null&&typeof properties=="object")for(let[key,child]of Object.entries(properties)){let fault$1=visit(child,[...path,key],reachable);if(fault$1!==void 0)return fault$1}for(let k of NON_REACHABLE_SUBSCHEMA_KEYWORDS){let sub=schema2[k];if(sub===void 0)continue;let branches=Array.isArray(sub)?sub:sub!==null&&typeof sub=="object"&&OBJECT_VALUED_SUBSCHEMA_KEYWORDS.has(k)?Object.values(sub):[sub];for(let branch of branches){let fault$1=visit(branch,[...path,`<${k}>`],!1);if(fault$1!==void 0)return fault$1}}},fault=visit(inputSchema,[],!0);return fault===void 0?{valid:!0,declarations}:{valid:!1,reason:fault}}function pathName(path){return path.length===0?"<root>":path.join(".")}function mcpParamPrimitiveToString(value){if(typeof value=="string")return value;if(typeof value=="boolean")return value?"true":"false";if(typeof value=="number")return!Number.isFinite(value)||Number.isInteger(value)&&!Number.isSafeInteger(value)?void 0:String(value)}function base64ToUtf8(b64){let bin=atob(b64),bytes=new Uint8Array(bin.length);for(let i=0;i<bin.length;i++)bytes[i]=bin.codePointAt(i);return new TextDecoder("utf-8",{fatal:!0}).decode(bytes)}function decodeMcpParamValue(value){if(!(value.startsWith(BASE64_SENTINEL_PREFIX)&&value.endsWith(BASE64_SENTINEL_SUFFIX)))return value;let b64=value.slice(9,value.length-2);if(BASE64_CANONICAL.test(b64))try{return base64ToUtf8(b64)}catch{return}}function valueAtPath(root,path){let node=root;for(let key of path){if(node===null||typeof node!="object")return;node=node[key]}return node}function validateMcpParamHeaders(declarations,args,headers){for(let decl of declarations){let headerKey=`${MCP_PARAM_HEADER_PREFIX}${decl.headerName}`,headerValue=headers.get(headerKey),bodyRaw=valueAtPath(args,decl.path);if(bodyRaw==null)continue;let bodyString=mcpParamPrimitiveToString(bodyRaw);if(bodyString===void 0)continue;if(headerValue===null)return paramHeaderMismatchRejection("param-header-missing",headerKey,`the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)} but the ${headerKey} header is absent`);let decoded=decodeMcpParamValue(headerValue);if(decoded===void 0)return paramHeaderMismatchRejection("param-header-invalid-encoding",headerKey,`the ${headerKey} header carries an invalid Base64 sentinel value`);if(!((decl.type==="integer"||decl.type==="number")&&CANONICAL_DECIMAL.test(decoded)&&typeof bodyRaw=="number"?Number(decoded)===bodyRaw:decoded===bodyString))return paramHeaderMismatchRejection("param-header-mismatch",headerKey,`the ${headerKey} header decodes to ${JSON.stringify(decoded)} but the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)}`)}}function paramHeaderMismatchRejection(cell,header,body){return{kind:"reject",rung:"param-header-validation",cell,httpStatus:400,code:HEADER_MISMATCH_ERROR_CODE,message:`Bad Request: the request headers and body disagree: ${body}`,data:{mismatch:{header,body}},settled:!0}}function httpStatusForErrorCode(code,origin){return origin==="in-band"?code===ProtocolErrorCode.MissingRequiredClientCapability?400:200:LADDER_ERROR_HTTP_STATUS[code]??400}function rejection(rung,cell,httpStatus,error3,settled){return{kind:"reject",rung,cell,httpStatus,code:error3.code,message:error3.message,...error3.data!==void 0&&{data:error3.data},settled}}function crossCheckMismatch(cell,header,body,rung="era-classification"){return rejection(rung,cell,400,new ProtocolError(HEADER_MISMATCH_ERROR_CODE,`Bad Request: the request headers and body disagree: ${body}`,{mismatch:{header,body}}),!0)}function stripHttpOws(value){let start=0;for(;start<value.length;){let code=value.codePointAt(start);if(code!==9&&code!==32)break;start+=1}let end=value.length;for(;end>start;){let code=value.codePointAt(end-1);if(code!==9&&code!==32)break;end-=1}return start===0&&end===value.length?value:value.slice(start,end)}function validateStandardRequestHeaders(request,route){if(route.messageKind!=="request")return;let method=route.message.method;if(request.mcpMethodHeader===void 0)return crossCheckMismatch("method-header-missing","(missing)",`the body names method ${method} but the required Mcp-Method header is absent`,"standard-header-validation");let sourceField=Object.hasOwn(MCP_NAME_HEADER_SOURCE,method)?MCP_NAME_HEADER_SOURCE[method]:void 0;if(sourceField===void 0)return;let sourceValue=route.message.params?.[sourceField],bodyValue=typeof sourceValue=="string"?sourceValue:void 0;if(request.mcpNameHeader===void 0)return bodyValue===void 0?void 0:crossCheckMismatch("name-header-missing","(missing)",`the body carries params.${sourceField}="${bodyValue}" but the required Mcp-Name header is absent`,"standard-header-validation");let normalizedNameHeader=stripHttpOws(request.mcpNameHeader),decoded=decodeMcpParamValue(normalizedNameHeader);if(decoded===void 0)return crossCheckMismatch("name-header-invalid-encoding",normalizedNameHeader,"the Mcp-Name header carries an invalid Base64 sentinel value","standard-header-validation");if(bodyValue!==void 0&&decoded!==bodyValue)return crossCheckMismatch("name-header-mismatch",normalizedNameHeader,`the body carries params.${sourceField}="${bodyValue}" but the Mcp-Name header names "${decoded}"`,"standard-header-validation")}function isPlainObject$2(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function classificationForClaim(claimedVersion){return claimedVersion===void 0?{era:"modern"}:{era:isModernProtocolVersion(claimedVersion)?"modern":"legacy",revision:claimedVersion}}function carriesValidModernEnvelopeClaim(params){if(!hasEnvelopeClaim(params))return!1;let claimedVersion=envelopeClaimVersion(params);if(claimedVersion===void 0||!isModernProtocolVersion(claimedVersion))return!1;let meta2=requestMetaOf(params);return meta2!==void 0&&validateEnvelopeMeta(meta2).length===0}function classifyBatch(body){if(body.length===0)return rejection("jsonrpc-shape","empty-batch",400,new ProtocolError(ProtocolErrorCode.InvalidRequest,"Bad Request: empty JSON-RPC batch"),!0);for(let element of body){if(hasEnvelopeClaim(isPlainObject$2(element)?element.params:void 0))return rejection("jsonrpc-shape","batch-with-modern-element",400,new ProtocolError(ProtocolErrorCode.InvalidRequest,"Bad Request: JSON-RPC batches may not contain requests for protocol revision 2026-07-28 or later"),!0);if(!(isJSONRPCRequest(element)||isJSONRPCNotification(element)||isJSONRPCResultResponse(element)||isJSONRPCErrorResponse(element)))return rejection("jsonrpc-shape","batch-with-invalid-element",400,new ProtocolError(ProtocolErrorCode.InvalidRequest,"Bad Request: JSON-RPC batch contains an invalid message"),!0)}return{kind:"legacy",reason:"batch"}}function classifyRequestBody(request,body){let params=body.params,method=body.method,headerVersion=request.protocolVersionHeader,headerNamesModern=headerVersion!==void 0&&isModernProtocolVersion(headerVersion);if(method==="initialize"&&!carriesValidModernEnvelopeClaim(params)){if(headerNamesModern)return crossCheckMismatch("initialize-with-modern-header",headerVersion,"an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header");let requestedVersion=isPlainObject$2(params)&&typeof params.protocolVersion=="string"?params.protocolVersion:void 0;return{kind:"legacy",reason:"initialize",...requestedVersion!==void 0&&{requestedVersion}}}if(hasEnvelopeClaim(params)){let meta2=requestMetaOf(params),firstIssue=(meta2===void 0?[]:validateEnvelopeMeta(meta2))[0];if(firstIssue!==void 0)return rejection("envelope","envelope-invalid",400,new ProtocolError(ProtocolErrorCode.InvalidParams,`Invalid _meta envelope for protocol revision 2026-07-28: ${firstIssue.key}: ${firstIssue.problem}`,{envelope:firstIssue}),!0);let claimedVersion=envelopeClaimVersion(params);return headerVersion!==void 0&&claimedVersion!==void 0&&headerVersion!==claimedVersion?crossCheckMismatch("header-body-version-mismatch",headerVersion,`the body envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`):request.mcpMethodHeader!==void 0&&request.mcpMethodHeader!==method?crossCheckMismatch("method-header-mismatch",request.mcpMethodHeader,`the body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`):{kind:"modern",messageKind:"request",message:body,classification:classificationForClaim(claimedVersion)}}if(headerNamesModern){let meta2=requestMetaOf(params),missingFromEnvelope=validateEnvelopeMeta(meta2??{}).filter(issue2=>issue2.problem==="missing").map(issue2=>issue2.key),missing=meta2===void 0?["_meta"]:missingFromEnvelope.length>0?missingFromEnvelope:[PROTOCOL_VERSION_META_KEY];return rejection("envelope","modern-header-without-claim",400,new ProtocolError(ProtocolErrorCode.InvalidParams,`Invalid params: the MCP-Protocol-Version header names protocol revision ${headerVersion}, but the request is missing the required per-request envelope key(s): ${missing.join(", ")}`,{envelope:{missing}}),!0)}return{kind:"legacy",reason:"no-claim",...headerVersion!==void 0&&{requestedVersion:headerVersion}}}function classifyNotificationBody(request,body){let params=body.params,method=body.method,headerVersion=request.protocolVersionHeader,headerNamesModern=headerVersion!==void 0&&isModernProtocolVersion(headerVersion);if(hasEnvelopeClaim(params)){let claimedVersion=envelopeClaimVersion(params);if(claimedVersion===void 0){let meta2=requestMetaOf(params),claimIssue=(meta2===void 0?[]:validateEnvelopeMeta(meta2)).find(issue2=>issue2.key===PROTOCOL_VERSION_META_KEY)??{key:PROTOCOL_VERSION_META_KEY,problem:"expected a protocol version string"};return rejection("envelope","notification-envelope-invalid",400,new ProtocolError(ProtocolErrorCode.InvalidParams,`Invalid _meta envelope for protocol revision 2026-07-28: ${claimIssue.key}: ${claimIssue.problem}`,{envelope:claimIssue}),!0)}if(headerVersion!==void 0&&headerVersion!==claimedVersion)return crossCheckMismatch("notification-header-body-version-mismatch",headerVersion,`the notification envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`);let classification=classificationForClaim(claimedVersion);return classification.era==="modern"&&request.mcpMethodHeader!==void 0&&request.mcpMethodHeader!==method?crossCheckMismatch("notification-method-header-mismatch",request.mcpMethodHeader,`the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`):{kind:"modern",messageKind:"notification",message:body,classification}}return headerNamesModern?request.mcpMethodHeader!==void 0&&request.mcpMethodHeader!==method?crossCheckMismatch("notification-method-header-mismatch",request.mcpMethodHeader,`the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`):{kind:"modern",messageKind:"notification",message:body,classification:{era:"modern",revision:headerVersion}}:{kind:"legacy",reason:"notification",...headerVersion!==void 0&&{requestedVersion:headerVersion}}}function classifyInboundRequest(request){if(request={...request,...request.protocolVersionHeader!==void 0&&{protocolVersionHeader:stripHttpOws(request.protocolVersionHeader)},...request.mcpMethodHeader!==void 0&&{mcpMethodHeader:stripHttpOws(request.mcpMethodHeader)},...request.mcpNameHeader!==void 0&&{mcpNameHeader:stripHttpOws(request.mcpNameHeader)}},request.httpMethod.toUpperCase()!=="POST")return{kind:"legacy",reason:"http-method"};let body=request.body;return Array.isArray(body)?classifyBatch(body):isJSONRPCResultResponse(body)||isJSONRPCErrorResponse(body)?{kind:"legacy",reason:"response"}:isPlainObject$2(body)&&isJSONRPCRequest(body)?classifyRequestBody(request,body):isPlainObject$2(body)&&isJSONRPCNotification(body)?classifyNotificationBody(request,body):rejection("jsonrpc-shape","invalid-json-rpc-body",400,new ProtocolError(ProtocolErrorCode.InvalidRequest,"Bad Request: the request body is not a valid JSON-RPC message"),!0)}function modernOnlyStrictRejection(route,supportedVersions){switch(route.reason){case"http-method":return rejection("http-method","modern-only-method-not-allowed",405,new ProtocolError(-32e3,"Method not allowed."),!0);case"batch":return rejection("jsonrpc-shape","modern-only-batch-not-supported",400,new ProtocolError(ProtocolErrorCode.InvalidRequest,"Bad Request: JSON-RPC batches are not supported by this endpoint"),!0);case"response":return rejection("jsonrpc-shape","modern-only-response-post",400,new ProtocolError(ProtocolErrorCode.InvalidRequest,"Bad Request: JSON-RPC responses cannot be posted to this endpoint"),!0);case"notification":return;case"initialize":case"no-claim":{let requested=route.requestedVersion;return rejection("era-classification","modern-only-missing-envelope",400,requested===void 0?new ProtocolError(ProtocolErrorCode.UnsupportedProtocolVersion,"Unsupported protocol version: the request did not name a protocol version",{supported:[...supportedVersions]}):new UnsupportedProtocolVersionError({supported:[...supportedVersions],requested}),!0)}}}function parseSchema(schema2,data){return safeParse2(schema2,data)}function shapeKeys(schemas){return new Set(schemas.flatMap(schema2=>Object.keys(schema2.shape)))}function isStandardSchema(schema2){if(schema2==null)return!1;let schemaType=typeof schema2;return schemaType!=="object"&&schemaType!=="function"||!("~standard"in schema2)?!1:typeof schema2["~standard"]?.validate=="function"}function standardSchemaToJsonSchema(schema2,io="input"){let std=schema2["~standard"],result;if(std.jsonSchema)result=std.jsonSchema[io]({target:JSON_SCHEMA_CONVERSION_TARGET});else if(std.vendor==="zod"){if(!("_zod"in schema2))throw new Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().");warnedZodFallback||(warnedZodFallback=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.")),result=toJSONSchema(schema2,{target:JSON_SCHEMA_CONVERSION_TARGET,io})}else throw new Error(`Schema library "${std.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(io==="output")return result.type!==void 0?result:isProvablyObjectShapedRoot(result)?{type:"object",...result}:result;if(result.type!==void 0&&result.type!=="object")throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(result.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:"object",...result}}function isProvablyObjectShapedRoot(schema2){if("properties"in schema2||"patternProperties"in schema2||"additionalProperties"in schema2||"required"in schema2)return!0;for(let key of["oneOf","anyOf","allOf"]){let members=schema2[key];if(Array.isArray(members)&&members.length>0)return members.every(m=>m!==null&&typeof m=="object"&&(m.type==="object"||isProvablyObjectShapedRoot(m)))}return!1}function formatIssue(issue2){return issue2.path?.length?`${issue2.path.map(p=>String(typeof p=="object"?p.key:p)).join(".")}: ${issue2.message}`:issue2.message}async function validateStandardSchema(schema2,data){let result=await schema2["~standard"].validate(data);return result.issues&&result.issues.length>0?{success:!1,error:result.issues.map(i=>formatIssue(i)).join(", ")}:{success:!0,data:result.value}}function zodEmittedPattern(schema2){let jsonSchema=toJSONSchema(schema2,{target:JSON_SCHEMA_CONVERSION_TARGET,io:"input"});return typeof jsonSchema.pattern=="string"?jsonSchema.pattern:void 0}function datetimeReferenceSchemas(pattern){let fractionDigits=DATETIME_FRACTION_DIGITS.exec(pattern),precisions=[void 0,-1,0];return fractionDigits&&precisions.push(Number(fractionDigits[1])),[!1,!0].flatMap(local=>[!1,!0].flatMap(offset=>precisions.map(precision=>iso_exports.datetime({local,offset,precision}))))}function referencePatternsForFormat(format,pattern){let referenceSchemas;switch(format){case"email":referenceSchemas=[email2()];break;case"uri":referenceSchemas=[url()];break;case"date":referenceSchemas=[iso_exports.date()];break;case"date-time":referenceSchemas=datetimeReferenceSchemas(pattern);break}return new Set(referenceSchemas.map(schema2=>zodEmittedPattern(schema2)).filter(emitted=>emitted!==void 0))}function isLibraryFormatPattern(format,pattern,vendor){return vendor!=="zod"?!0:referencePatternsForFormat(format,pattern).has(pattern)}function promptArgumentsFromStandardSchema(schema2){let jsonSchema=standardSchemaToJsonSchema(schema2,"input"),properties=jsonSchema.properties||{},required2=jsonSchema.required||[];return Object.entries(properties).map(([name,prop])=>({name,description:prop?.description,required:required2.includes(name)}))}function isJsonObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function convertStandardElicitationSchema(schema2){try{return standardSchemaToJsonSchema(schema2,"input")}catch(error3){let detail=error3 instanceof Error?error3.message:String(error3);throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${detail}`)}}function isAnnotationOnlyJsonSchemaKeyword(key){return ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS.has(key)||key.startsWith("x-")}function walkProperty(node,path,vendor,unsupported){if(!isJsonObject(node))return node;let allowedKeys=typeof node.type=="string"&&Object.hasOwn(PROPERTY_KEYS_BY_TYPE,node.type)?PROPERTY_KEYS_BY_TYPE[node.type]:void 0;if(allowedKeys===void 0)return node;let pruned={};for(let[key,value]of Object.entries(node))allowedKeys.has(key)||isAnnotationOnlyJsonSchemaKeyword(key)?pruned[key]=value:key==="pattern"&&node.type==="string"&&typeof node.format=="string"?SUPPORTED_STRING_FORMATS.has(node.format)?(typeof value!="string"||!isLibraryFormatPattern(node.format,value,vendor))&&unsupported.push(`${path}.${key}`):pruned[key]=value:unsupported.push(`${path}.${key}`);return pruned}function walkRequestedSchema(converted,vendor){let pruned={},unsupported=[];for(let[key,value]of Object.entries(converted))key==="properties"&&isJsonObject(value)?pruned[key]=Object.fromEntries(Object.entries(value).map(([name,node])=>[name,walkProperty(node,`properties.${name}`,vendor,unsupported)])):ROOT_KEYS.has(key)?pruned[key]=value:isAnnotationOnlyJsonSchemaKeyword(key)||unsupported.push(key);if(unsupported.length>0)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${unsupported.join(", ")}`);return pruned}function describeUnsupportedProperties(pruned,fallback){if(!isJsonObject(pruned.properties))return fallback;let offenders=Object.entries(pruned.properties).filter(([,node])=>!parseSchema(PrimitiveSchemaDefinitionSchema,node).success).map(([name])=>`properties.${name}`);return offenders.length>0?offenders.join(", "):fallback}function findDroppedConstraintPaths(original,parsed,path=""){return Array.isArray(original)&&Array.isArray(parsed)?original.flatMap((item,index)=>findDroppedConstraintPaths(item,parsed[index],`${path}[${index}]`)):!isJsonObject(original)||!isJsonObject(parsed)?[]:Object.entries(original).flatMap(([key,value])=>{let childPath=path?`${path}.${key}`:key;return Object.prototype.hasOwnProperty.call(parsed,key)?findDroppedConstraintPaths(value,parsed[key],childPath):isAnnotationOnlyJsonSchemaKeyword(key)?[]:[childPath]})}function normalizeElicitInputParams(input){if(!isStandardSchema(input.requestedSchema))return{...input,mode:"form",requestedSchema:input.requestedSchema};let vendor=input.requestedSchema["~standard"].vendor,pruned=walkRequestedSchema(convertStandardElicitationSchema(input.requestedSchema),vendor),parsed=parseSchema(ElicitRequestFormParamsSchema.shape.requestedSchema,pruned);if(!parsed.success)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${describeUnsupportedProperties(pruned,parsed.error.message)}`);let droppedConstraints=findDroppedConstraintPaths(pruned,parsed.data);if(droppedConstraints.length>0)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${droppedConstraints.join(", ")}`);let danglingRequired=(parsed.data.required??[]).filter(key=>!Object.prototype.hasOwnProperty.call(parsed.data.properties,key));if(danglingRequired.length>0)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${danglingRequired.join(", ")}`);return{...input,mode:"form",requestedSchema:parsed.data}}function buildInputRequired(spec){let hasInputRequests=spec.inputRequests!==void 0&&Object.keys(spec.inputRequests).length>0,hasRequestState=typeof spec.requestState=="string";if(!hasInputRequests&&!hasRequestState)throw new TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)");return{resultType:"input_required",...spec.inputRequests!==void 0&&{inputRequests:spec.inputRequests},...spec.requestState!==void 0&&{requestState:spec.requestState}}}function acceptedContent(responses,key,schema2){let view=inputResponse(responses,key);if(view.kind!=="elicit"||view.action!=="accept"||view.content===void 0)return;if(schema2===void 0)return view.content;let outcome=schema2["~standard"].validate(view.content);if(outcome instanceof Promise)throw new TypeError("acceptedContent(responses, key, schema) requires a synchronously-validating schema");return outcome.issues===void 0?outcome.value:void 0}function inputResponse(responses,key){if(responses===void 0||typeof responses!="object"||responses===null)return{kind:"missing"};let entry=responses[key];if(entry===null||typeof entry!="object"||Array.isArray(entry))return{kind:"missing"};let candidate=entry;if(candidate.action==="accept"||candidate.action==="decline"||candidate.action==="cancel"){let content=candidate.content;return{kind:"elicit",action:candidate.action,...content!==null&&typeof content=="object"&&!Array.isArray(content)&&{content}}}return Array.isArray(candidate.roots)?{kind:"roots",roots:candidate.roots}:typeof candidate.role=="string"&&candidate.content!==void 0?{kind:"sampling",result:candidate}:{kind:"missing"}}function inputRequiredRoundsExceededMessage(method,maxRounds){return`Multi-round-trip request '${method}' still required input after ${maxRounds} rounds (inputRequired.maxRounds)`}function sleep(ms,signal){return new Promise((resolve,reject)=>{if(signal?.aborted){reject(signal.reason instanceof SdkError?signal.reason:new SdkError(SdkErrorCode.RequestTimeout,String(signal.reason)));return}let timer=setTimeout(()=>{signal?.removeEventListener("abort",onAbort),resolve()},ms),onAbort=()=>{clearTimeout(timer),reject(signal?.reason instanceof SdkError?signal.reason:new SdkError(SdkErrorCode.RequestTimeout,String(signal?.reason)))};signal?.addEventListener("abort",onAbort,{once:!0})})}function linkedRoundAbort(outer){let controller=new AbortController,onOuterAbort=()=>controller.abort(outer?.reason);return outer?.addEventListener("abort",onOuterAbort,{once:!0}),outer?.aborted&&controller.abort(outer.reason),{signal:controller.signal,abort:reason=>controller.abort(reason),dispose:()=>outer?.removeEventListener("abort",onOuterAbort)}}function register(key,schema2){let name=key.slice(0,-6);_specTypeSchemas[name]=schema2,_isSpecType[name]=v=>schema2.safeParse(v).success}function bootstrapOutboundCodec(method){switch(method){case"initialize":case"notifications/initialized":return codecForVersion(void 0);case"server/discover":return codecForVersion(MODERN_WIRE_REVISION);default:return}}function liftWireOnlyMaterial(message,kind){let params=message.params;if(!isPlainObject$1(params))return{message,lifted:{}};let meta2=params._meta,envelopeKeys=isPlainObject$1(meta2)?RESERVED_ENVELOPE_META_KEYS.filter(key=>key in meta2):[],retryKeys=kind==="request"?RETRY_PARAMS_KEYS.filter(key=>key in params):[];if(envelopeKeys.length===0&&retryKeys.length===0)return{message,lifted:{}};let lifted={},nextParams={...params};if(envelopeKeys.length>0&&isPlainObject$1(meta2)){let envelope={},nextMeta={...meta2};for(let key of envelopeKeys)envelope[key]=meta2[key],delete nextMeta[key];lifted.envelope=envelope,Object.keys(nextMeta).length>0?nextParams._meta=nextMeta:delete nextParams._meta}for(let key of retryKeys)key==="inputResponses"&&(lifted.inputResponses=nextParams[key]),key==="requestState"&&(lifted.requestState=nextParams[key]),delete nextParams[key];return{message:{...message,params:nextParams},lifted}}function codecResultValidator(codec,method){let probe=codec.validateResult(method,void 0);if(!(!probe.ok&&probe.reason==="not-in-era"))return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(value){let outcome=codec.validateResult(method,value);return outcome.ok?{value:outcome.value}:{issues:[{message:outcome.reason==="invalid"?outcome.message:`not-in-era: ${method}`}]}}}}}function requestStateAccessor(value){return()=>value}function withRequestStateValue(ctx,value){return{...ctx,mcpReq:{...ctx.mcpReq,requestState:requestStateAccessor(value)}}}function setNegotiatedProtocolVersion(instance,version2){writeNegotiatedProtocolVersion(instance,version2)}function isPlainObject$1(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function mergeCapabilities(base,additional){let result={...base};for(let key in additional){let k=key,addValue=additional[k];if(addValue===void 0)continue;let baseValue=result[k];result[k]=isPlainObject$1(baseValue)&&isPlainObject$1(addValue)?{...baseValue,...addValue}:addValue}return result}function isPlainObject2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function partitionInputResponses(inputResponses){let accepted={},droppedKeys=[];if(!isPlainObject2(inputResponses))return{accepted,droppedKeys};for(let[key,entry]of Object.entries(inputResponses)){if(!isPlainObject2(entry)||"method"in entry||"result"in entry){droppedKeys.push(key);continue}accepted[key]=entry}return{accepted,droppedKeys}}function manualInputRequiredValue(decoded){return{resultType:"input_required",inputRequests:decoded.inputRequests,...decoded.requestState!==void 0&&{requestState:decoded.requestState}}}function mediaTypeEssence(header){if(header)try{return import_content_type.parse(header).type}catch{let essence=(header.split(";",1)[0]??"").trim().toLowerCase();return essence===""||header.slice(essence.length).includes(",")?void 0:essence}}function isJsonContentType(header){return header==="application/json"?!0:mediaTypeEssence(header)==="application/json"}function validateToolName(name){let warnings=[];if(name.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(name.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${name.length})`]};if(name.includes(" ")&&warnings.push("Tool name contains spaces, which may cause parsing issues"),name.includes(",")&&warnings.push("Tool name contains commas, which may cause parsing issues"),(name.startsWith("-")||name.endsWith("-"))&&warnings.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(name.startsWith(".")||name.endsWith("."))&&warnings.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!TOOL_NAME_REGEX.test(name)){let invalidChars=[...name].filter(char=>!/[A-Za-z0-9._-]/.test(char)).filter((char,index,arr)=>arr.indexOf(char)===index);return warnings.push(`Tool name contains invalid characters: ${invalidChars.map(c=>`"${c}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings}}return{isValid:!0,warnings}}function issueToolNameWarning(name,warnings){if(warnings.length>0){console.warn(`Tool name validation warning for "${name}":`);for(let warning of warnings)console.warn(` - ${warning}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function validateAndWarnToolName(name){let result=validateToolName(name);return issueToolNameWarning(name,result.warnings),result.isValid}function isZodV4Schema(v){return typeof v=="object"&&v!==null&&"_zod"in v}function looksLikeZodV3(v){return typeof v=="object"&&v!==null&&!("_zod"in v)&&"_def"in v&&typeof v._def?.typeName=="string"}function isZodRawShape(obj){if(typeof obj!="object"||obj===null||isStandardSchema(obj))return!1;let proto=Object.getPrototypeOf(obj);return proto!==Object.prototype&&proto!==null?!1:Object.values(obj).every(v=>isZodV4Schema(v))}function normalizeRawShapeSchema(schema2){if(schema2!==void 0){if(isZodRawShape(schema2))return object(schema2);if(typeof schema2=="object"&&schema2!==null&&!isStandardSchema(schema2)&&Object.values(schema2).some(v=>looksLikeZodV3(v)))throw new TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself.");if(!isStandardSchema(schema2))throw new TypeError("inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() }).");return schema2}}function fromJsonSchema(schema2,validator){let check=validator.getValidator(schema2);return{"~standard":{version:1,vendor:"mcp",jsonSchema:{input:()=>schema2,output:()=>schema2},validate:data=>{let result=check(data);return result.valid?{value:result.data}:{issues:[{message:result.errorMessage}]}}}}}var BRANDS,OAuthErrorCode,OAuthError,SdkErrorCode,SdkError,SdkHttpError,REQUIRED_CLIENT_CAPABILITIES_BY_METHOD,FIRST_MODERN_PROTOCOL_VERSION,SUPPORTED_MODERN_PROTOCOL_VERSIONS,TOOL_RESULT_FOREIGN_FAMILY_KEYS,memo$1,REF_REWRITE_DATA_POSITION_KEYS,REF_REWRITE_NAME_MAP_KEYS,requestMethodKeys$1,notificationMethodKeys$1,resultMethodKeys,maps$1,rev2025RequestMethods,rev2025NotificationMethods,NOT_IN_ERA$1,rev2025Codec,memo,CACHEABLE_RESULT_METHODS,RESULT_CACHE_HINT_FALLBACK,ProtocolErrorCode,ProtocolError,ResourceNotFoundError,UrlElicitationRequiredError,UnsupportedProtocolVersionError,MissingRequiredClientCapabilityError,DEFAULT_CACHE_TTL_MS,DEFAULT_CACHE_SCOPE,EXTENDED_RESULT_TYPE_METHODS,INPUT_REQUEST_METHODS_2026,maps,requestMethodKeys,notificationMethodKeys,rev2026RequestMethods,rev2026NotificationMethods,NOT_IN_ERA,REQUIRED_ENVELOPE_KEYS,rev2026Codec,wireResultSchemasMemo,MODERN_WIRE_REVISION,ALL_CODECS,schemas_exports2,isJSONRPCRequest,isJSONRPCNotification,isJSONRPCResultResponse,isJSONRPCErrorResponse,isInputRequiredResult,isInitializeRequest,MCP_PARAM_HEADER_PREFIX,X_MCP_HEADER_KEY,RFC9110_TOKEN,PERMITTED_X_MCP_HEADER_TYPES,NON_REACHABLE_SUBSCHEMA_KEYWORDS,OBJECT_VALUED_SUBSCHEMA_KEYWORDS,BASE64_SENTINEL_PREFIX,BASE64_SENTINEL_SUFFIX,BASE64_CANONICAL,CANONICAL_DECIMAL,HEADER_MISMATCH_ERROR_CODE,INBOUND_VALIDATION_LADDER,LADDER_ERROR_HTTP_STATUS,MCP_NAME_HEADER_SOURCE,warnedZodFallback,JSON_SCHEMA_CONVERSION_TARGET,DATETIME_FRACTION_DIGITS,ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS,ROOT_KEYS,PROPERTY_KEYS_BY_TYPE,SUPPORTED_STRING_FORMATS,inputRequired,REQUEST_STATE_ONLY_LEG_PACING_MS,SPEC_SCHEMA_KEYS,authSchemas,_specTypeSchemas,_isSpecType,specTypeSchemas,isSpecType,DEFAULT_REQUEST_TIMEOUT_MSEC,RESERVED_ENVELOPE_META_KEYS,RETRY_PARAMS_KEYS,NO_REQUEST_STATE,writeNegotiatedProtocolVersion,Protocol,require_content_type,import_content_type,STDIO_DEFAULT_MAX_BUFFER_SIZE,TOOL_NAME_REGEX,MAX_TEMPLATE_LENGTH,MAX_VARIABLE_LENGTH,MAX_TEMPLATE_EXPRESSIONS,MAX_REGEX_LENGTH,UriTemplate,init_src_CX2iR2pK=__esm({"../../node_modules/.pnpm/@modelcontextprotocol+server@2.0.0_patch_hash=2a5f5402571efdc40802e9603a3dd09e22588b4aacad710814c204d79568091e/node_modules/@modelcontextprotocol/server/dist/src-CX2iR2pK.mjs"(){"use strict";init_chunk_Br0eD_fh();init_dialects_DoSzNhcb();init_internal();init_v4();BRANDS=Symbol.for("mcp.sdk.errorBrands");OAuthErrorCode=(function(OAuthErrorCode$1){return OAuthErrorCode$1.InvalidRequest="invalid_request",OAuthErrorCode$1.InvalidClient="invalid_client",OAuthErrorCode$1.InvalidGrant="invalid_grant",OAuthErrorCode$1.UnauthorizedClient="unauthorized_client",OAuthErrorCode$1.UnsupportedGrantType="unsupported_grant_type",OAuthErrorCode$1.InvalidScope="invalid_scope",OAuthErrorCode$1.AccessDenied="access_denied",OAuthErrorCode$1.ServerError="server_error",OAuthErrorCode$1.TemporarilyUnavailable="temporarily_unavailable",OAuthErrorCode$1.UnsupportedResponseType="unsupported_response_type",OAuthErrorCode$1.UnsupportedTokenType="unsupported_token_type",OAuthErrorCode$1.InvalidToken="invalid_token",OAuthErrorCode$1.MethodNotAllowed="method_not_allowed",OAuthErrorCode$1.TooManyRequests="too_many_requests",OAuthErrorCode$1.InvalidClientMetadata="invalid_client_metadata",OAuthErrorCode$1.InvalidRedirectUri="invalid_redirect_uri",OAuthErrorCode$1.InsufficientScope="insufficient_scope",OAuthErrorCode$1.InvalidTarget="invalid_target",OAuthErrorCode$1})({}),OAuthError=class OAuthError2 extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](value){return brandedHasInstance(this,value)}static isInstance(value){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return brandedHasInstance(this,value)}constructor(code,message,errorUri){super(message),this.code=code,this.errorUri=errorUri,this.name="OAuthError",stampErrorBrands(this,new.target)}toResponseObject(){let response={error:this.code,error_description:this.message};return this.errorUri&&(response.error_uri=this.errorUri),response}static fromResponse(response){return new OAuthError2(response.error,response.error_description??response.error,response.error_uri)}},SdkErrorCode=(function(SdkErrorCode$1){return SdkErrorCode$1.NotConnected="NOT_CONNECTED",SdkErrorCode$1.AlreadyConnected="ALREADY_CONNECTED",SdkErrorCode$1.NotInitialized="NOT_INITIALIZED",SdkErrorCode$1.CapabilityNotSupported="CAPABILITY_NOT_SUPPORTED",SdkErrorCode$1.RequestTimeout="REQUEST_TIMEOUT",SdkErrorCode$1.ConnectionClosed="CONNECTION_CLOSED",SdkErrorCode$1.SendFailed="SEND_FAILED",SdkErrorCode$1.InvalidResult="INVALID_RESULT",SdkErrorCode$1.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",SdkErrorCode$1.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",SdkErrorCode$1.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",SdkErrorCode$1.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",SdkErrorCode$1.EraNegotiationFailed="ERA_NEGOTIATION_FAILED",SdkErrorCode$1.ClientHttpNotImplemented="CLIENT_HTTP_NOT_IMPLEMENTED",SdkErrorCode$1.ClientHttpAuthentication="CLIENT_HTTP_AUTHENTICATION",SdkErrorCode$1.ClientHttpForbidden="CLIENT_HTTP_FORBIDDEN",SdkErrorCode$1.ClientHttpUnexpectedContent="CLIENT_HTTP_UNEXPECTED_CONTENT",SdkErrorCode$1.ClientHttpFailedToOpenStream="CLIENT_HTTP_FAILED_TO_OPEN_STREAM",SdkErrorCode$1.ClientHttpFailedToTerminateSession="CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION",SdkErrorCode$1})({}),SdkError=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](value){return brandedHasInstance(this,value)}static isInstance(value){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return brandedHasInstance(this,value)}constructor(code,message,data){super(message),this.code=code,this.data=data,this.name="SdkError",stampErrorBrands(this,new.target)}},SdkHttpError=class extends SdkError{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor(code,message,data){super(code,message,data),this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}},REQUIRED_CLIENT_CAPABILITIES_BY_METHOD={};FIRST_MODERN_PROTOCOL_VERSION="2026-07-28",SUPPORTED_MODERN_PROTOCOL_VERSIONS=[FIRST_MODERN_PROTOCOL_VERSION];TOOL_RESULT_FOREIGN_FAMILY_KEYS=["task","inputRequests","requestState"];REF_REWRITE_DATA_POSITION_KEYS=new Set(["const","enum","default","examples"]),REF_REWRITE_NAME_MAP_KEYS=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);requestMethodKeys$1={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},notificationMethodKeys$1={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},resultMethodKeys={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null};rev2025RequestMethods=Object.keys(requestMethodKeys$1),rev2025NotificationMethods=Object.keys(notificationMethodKeys$1);NOT_IN_ERA$1={ok:!1,reason:"not-in-era"};rev2025Codec={era:"2025-11-25",hasRequestMethod:hasRequestMethod2025,hasNotificationMethod:hasNotificationMethod2025,validateRequest:(method,raw2)=>triState$1(getRequestSchema(method),raw2),validateResult:(method,raw2)=>triState$1(getResultSchema(method),raw2),validateNotification:(method,raw2)=>triState$1(getNotificationSchema(method),raw2),hasInputRequestMethod:()=>!1,validateInputRequest:()=>NOT_IN_ERA$1,validateInputResponse:()=>NOT_IN_ERA$1,samplingResultVariant:((hasTools,raw2)=>{let s=buildSchemas2025();return triState$1(hasTools?s.CreateMessageResultWithToolsSchema:s.CreateMessageResultSchema,raw2)}),outboundEnvelope:_material=>{},validateEnvelopeMeta:_meta=>[],projectCallToolResult(result,advertisedOutputSchema){let withText=appendTextFallbackForNonObject(result),sc=withText.structuredContent;if(sc===void 0)return withText;let valueIsNonObject=typeof sc!="object"||sc===null||Array.isArray(sc),schemaWrapped=advertisedOutputSchema!==void 0&&isNonObjectJsonSchemaRoot(advertisedOutputSchema);return!valueIsNonObject&&!schemaWrapped?withText:{...withText,structuredContent:{result:sc}}},decodeResult(_method,raw2){if(isPlainObject$6(raw2)&&"resultType"in raw2){let stripped={...raw2};return delete stripped.resultType,{kind:"complete",result:stripped}}return{kind:"complete",result:raw2}},encodeResult(method,result){if(method!=="tools/list")return result;let tools=result.tools;return!Array.isArray(tools)||!tools.some(t=>toolNeedsLegacyWrap(t))?result:{...result,tools:tools.map(t=>toolNeedsLegacyWrap(t)?{...t,outputSchema:wrapOutputSchemaForLegacy(t.outputSchema)}:t)}},encodeErrorCode:code=>code===-32002?-32602:code,checkInboundEnvelope:_material=>{}};CACHEABLE_RESULT_METHODS=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];RESULT_CACHE_HINT_FALLBACK=Symbol("modelcontextprotocol.resultCacheHintFallback");ProtocolErrorCode=(function(ProtocolErrorCode$1){return ProtocolErrorCode$1[ProtocolErrorCode$1.ParseError=-32700]="ParseError",ProtocolErrorCode$1[ProtocolErrorCode$1.InvalidRequest=-32600]="InvalidRequest",ProtocolErrorCode$1[ProtocolErrorCode$1.MethodNotFound=-32601]="MethodNotFound",ProtocolErrorCode$1[ProtocolErrorCode$1.InvalidParams=-32602]="InvalidParams",ProtocolErrorCode$1[ProtocolErrorCode$1.InternalError=-32603]="InternalError",ProtocolErrorCode$1[ProtocolErrorCode$1.ResourceNotFound=-32002]="ResourceNotFound",ProtocolErrorCode$1[ProtocolErrorCode$1.MissingRequiredClientCapability=-32021]="MissingRequiredClientCapability",ProtocolErrorCode$1[ProtocolErrorCode$1.UnsupportedProtocolVersion=-32022]="UnsupportedProtocolVersion",ProtocolErrorCode$1[ProtocolErrorCode$1.UrlElicitationRequired=-32042]="UrlElicitationRequired",ProtocolErrorCode$1})({}),ProtocolError=class ProtocolError2 extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](value){return brandedHasInstance(this,value)}static isInstance(value){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return brandedHasInstance(this,value)}constructor(code,message,data){super(message),this.code=code,this.data=data,this.name="ProtocolError",stampErrorBrands(this,new.target)}static fromError(code,message,data){if(code===ProtocolErrorCode.UrlElicitationRequired&&data){let errorData=data;if(errorData.elicitations)return new UrlElicitationRequiredError(errorData.elicitations,message)}if(code===ProtocolErrorCode.UnsupportedProtocolVersion&&data){let errorData=data;if(Array.isArray(errorData.supported)&&typeof errorData.requested=="string")return new UnsupportedProtocolVersionError({supported:errorData.supported,requested:errorData.requested},message)}if(code===ProtocolErrorCode.InvalidParams||code===ProtocolErrorCode.ResourceNotFound){let errorData=data;if(typeof errorData?.uri=="string"&&(code===ProtocolErrorCode.ResourceNotFound||Object.keys(errorData).length===1))return new ResourceNotFoundError(errorData.uri,message)}if(code===ProtocolErrorCode.MissingRequiredClientCapability&&data){let errorData=data;if(errorData.requiredCapabilities!==null&&typeof errorData.requiredCapabilities=="object"&&!Array.isArray(errorData.requiredCapabilities))return new MissingRequiredClientCapabilityError({requiredCapabilities:errorData.requiredCapabilities},message)}return new ProtocolError2(code,message,data)}},ResourceNotFoundError=class extends ProtocolError{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(uri,message=`Resource not found: ${uri}`){super(ProtocolErrorCode.InvalidParams,message,{uri})}get uri(){return this.data.uri}},UrlElicitationRequiredError=class extends ProtocolError{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(elicitations,message=`URL elicitation${elicitations.length>1?"s":""} required`){super(ProtocolErrorCode.UrlElicitationRequired,message,{elicitations})}get elicitations(){return this.data?.elicitations??[]}},UnsupportedProtocolVersionError=class extends ProtocolError{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(data,message=`Unsupported protocol version: ${data.requested}`){super(ProtocolErrorCode.UnsupportedProtocolVersion,message,data)}get supported(){return this.data.supported}get requested(){return this.data.requested}},MissingRequiredClientCapabilityError=class extends ProtocolError{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"})}constructor(data,message=`Missing required client capabilities: ${Object.keys(data.requiredCapabilities).join(", ")}`){super(ProtocolErrorCode.MissingRequiredClientCapability,message,data)}get requiredCapabilities(){return this.data.requiredCapabilities}},DEFAULT_CACHE_TTL_MS=0,DEFAULT_CACHE_SCOPE="private",EXTENDED_RESULT_TYPE_METHODS=["tools/call","prompts/get","resources/read"];INPUT_REQUEST_METHODS_2026=["elicitation/create","sampling/createMessage","roots/list"];requestMethodKeys={"tools/call":null,"tools/list":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"completion/complete":null,"server/discover":null,"subscriptions/listen":null},notificationMethodKeys={"notifications/cancelled":null,"notifications/progress":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/subscriptions/acknowledged":null};rev2026RequestMethods=Object.keys(requestMethodKeys),rev2026NotificationMethods=Object.keys(notificationMethodKeys);NOT_IN_ERA={ok:!1,reason:"not-in-era"},REQUIRED_ENVELOPE_KEYS=[PROTOCOL_VERSION_META_KEY,CLIENT_CAPABILITIES_META_KEY];rev2026Codec={era:"2026-07-28",hasRequestMethod:hasRequestMethod2026,hasNotificationMethod:hasNotificationMethod2026,hasInputRequestMethod:method=>getInputRequestSchema2026(method)!==void 0,validateRequest:(method,raw2)=>triState(getRequestSchema2026(method),raw2),validateResult:(method,raw2)=>triState(getResultSchema2026(method),raw2),validateNotification:(method,raw2)=>triState(getNotificationSchema2026(method),raw2),validateInputRequest:(method,raw2)=>triState(getInputRequestSchema2026(method),raw2),validateInputResponse:(method,raw2)=>triState(getInputResponseSchema2026(method),raw2),samplingResultVariant:()=>NOT_IN_ERA,outboundEnvelope(material){return{[PROTOCOL_VERSION_META_KEY]:material.protocolVersion,[CLIENT_INFO_META_KEY]:material.clientInfo,[CLIENT_CAPABILITIES_META_KEY]:material.clientCapabilities,...material.logLevel!==void 0&&{[LOG_LEVEL_META_KEY]:material.logLevel}}},validateEnvelopeMeta(meta2){let issues=[];for(let key of REQUIRED_ENVELOPE_KEYS)key in meta2||issues.push({key,problem:"missing"});let parsed=buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(meta2);if(!parsed.success)for(let issue2 of parsed.error.issues){let path=issue2.path.map(String),key=path.length>0?path.join("."):"_meta";path.length===1&&issues.some(existing=>existing.key===key&&existing.problem==="missing")||issues.push({key,problem:issue2.message})}return issues},projectCallToolResult:result=>appendTextFallbackForNonObject(result),inputRequestSchema:getInputRequestSchema2026,decodeResult(method,raw2){if(!isPlainObject$4(raw2))return{kind:"invalid",error:new SdkError(SdkErrorCode.InvalidResult,`Invalid result for ${method}: not an object`,{method})};let rawResultType=raw2.resultType;if(rawResultType===void 0)return{kind:"invalid",error:new SdkError(SdkErrorCode.InvalidResult,`Invalid result for ${method}: missing required resultType \u2014 servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,{method,violation:"missing-resultType"})};if(typeof rawResultType!="string")return{kind:"invalid",error:new SdkError(SdkErrorCode.InvalidResult,`Invalid result for ${method}: non-string resultType`,{method,resultType:rawResultType})};if(rawResultType==="input_required"){let rawInputRequests=raw2.inputRequests,inputRequests=isPlainObject$4(rawInputRequests)?rawInputRequests:{},requestState=raw2.requestState;return Object.keys(inputRequests).length===0&&typeof requestState!="string"?{kind:"invalid",error:new SdkError(SdkErrorCode.InvalidResult,`Invalid result for ${method}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method,violation:"input-required-missing-both"})}:{kind:"input_required",inputRequests,...typeof requestState=="string"&&{requestState}}}if(rawResultType!=="complete")return{kind:"invalid",error:new SdkError(SdkErrorCode.UnsupportedResultType,`Unsupported result type '${rawResultType}' for ${method}`,{resultType:rawResultType,method})};let wireResultSchemas=getWireResultSchemas(),wireSchema=Object.hasOwn(wireResultSchemas,method)?wireResultSchemas[method]:void 0;if(wireSchema!==void 0){let parsed=wireSchema.safeParse(raw2);if(!parsed.success)return{kind:"invalid",error:new SdkError(SdkErrorCode.InvalidResult,`Invalid result for ${method}: ${parsed.error}`,{method})}}let lifted={...raw2};return delete lifted.resultType,{kind:"complete",result:lifted}},encodeResult(method,result,serverInfo){return stampServerInfoMeta(fillCacheFields(method,stampResultType(method,enforceDeletedFields(method,result))),serverInfo)},encodeErrorCode:code=>code===-32002?-32602:code,checkInboundEnvelope(material){if(material.envelope===void 0)return"Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)";let parsed=buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(material.envelope);if(!parsed.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${parsed.error.issues.map(issue2=>issue2.message).join("; ")}`}};MODERN_WIRE_REVISION="2026-07-28";ALL_CODECS=[rev2025Codec,rev2026Codec];schemas_exports2=__exportAll({AnnotationsSchema:()=>AnnotationsSchema,AudioContentSchema:()=>AudioContentSchema,BaseMetadataSchema:()=>BaseMetadataSchema,BaseRequestParamsSchema:()=>BaseRequestParamsSchema,BlobResourceContentsSchema:()=>BlobResourceContentsSchema,BooleanSchemaSchema:()=>BooleanSchemaSchema,CallToolRequestParamsSchema:()=>CallToolRequestParamsSchema,CallToolRequestSchema:()=>CallToolRequestSchema,CallToolResultSchema:()=>CallToolResultSchema,CancelTaskRequestSchema:()=>CancelTaskRequestSchema,CancelTaskResultSchema:()=>CancelTaskResultSchema,CancelledNotificationParamsSchema:()=>CancelledNotificationParamsSchema,CancelledNotificationSchema:()=>CancelledNotificationSchema,ClientCapabilitiesSchema:()=>ClientCapabilitiesSchema,ClientNotificationSchema:()=>ClientNotificationSchema,ClientRequestSchema:()=>ClientRequestSchema,ClientResultSchema:()=>ClientResultSchema,ClientTasksCapabilitySchema:()=>ClientTasksCapabilitySchema,CompatibilityCallToolResultSchema:()=>CompatibilityCallToolResultSchema,CompleteRequestParamsSchema:()=>CompleteRequestParamsSchema,CompleteRequestSchema:()=>CompleteRequestSchema,CompleteResultSchema:()=>CompleteResultSchema,ContentBlockSchema:()=>ContentBlockSchema,CreateMessageRequestParamsSchema:()=>CreateMessageRequestParamsSchema,CreateMessageRequestSchema:()=>CreateMessageRequestSchema,CreateMessageResultSchema:()=>CreateMessageResultSchema,CreateMessageResultWithToolsSchema:()=>CreateMessageResultWithToolsSchema,CreateTaskResultSchema:()=>CreateTaskResultSchema,CursorSchema:()=>CursorSchema,DiscoverRequestSchema:()=>DiscoverRequestSchema,DiscoverResultSchema:()=>DiscoverResultSchema,ElicitRequestFormParamsSchema:()=>ElicitRequestFormParamsSchema,ElicitRequestParamsSchema:()=>ElicitRequestParamsSchema,ElicitRequestSchema:()=>ElicitRequestSchema,ElicitRequestURLParamsSchema:()=>ElicitRequestURLParamsSchema,ElicitResultSchema:()=>ElicitResultSchema,ElicitationCompleteNotificationParamsSchema:()=>ElicitationCompleteNotificationParamsSchema,ElicitationCompleteNotificationSchema:()=>ElicitationCompleteNotificationSchema,EmbeddedResourceSchema:()=>EmbeddedResourceSchema,EmptyResultSchema:()=>EmptyResultSchema,EnumSchemaSchema:()=>EnumSchemaSchema,GetPromptRequestParamsSchema:()=>GetPromptRequestParamsSchema,GetPromptRequestSchema:()=>GetPromptRequestSchema,GetPromptResultSchema:()=>GetPromptResultSchema,GetTaskPayloadRequestSchema:()=>GetTaskPayloadRequestSchema,GetTaskPayloadResultSchema:()=>GetTaskPayloadResultSchema,GetTaskRequestSchema:()=>GetTaskRequestSchema,GetTaskResultSchema:()=>GetTaskResultSchema,IconSchema:()=>IconSchema,IconsSchema:()=>IconsSchema,ImageContentSchema:()=>ImageContentSchema,ImplementationSchema:()=>ImplementationSchema,InitializeRequestParamsSchema:()=>InitializeRequestParamsSchema,InitializeRequestSchema:()=>InitializeRequestSchema,InitializeResultSchema:()=>InitializeResultSchema,InitializedNotificationSchema:()=>InitializedNotificationSchema,JSONArraySchema:()=>JSONArraySchema,JSONObjectSchema:()=>JSONObjectSchema,JSONRPCErrorResponseSchema:()=>JSONRPCErrorResponseSchema,JSONRPCMessageSchema:()=>JSONRPCMessageSchema,JSONRPCNotificationSchema:()=>JSONRPCNotificationSchema,JSONRPCRequestSchema:()=>JSONRPCRequestSchema,JSONRPCResponseSchema:()=>JSONRPCResponseSchema,JSONRPCResultResponseSchema:()=>JSONRPCResultResponseSchema,JSONValueSchema:()=>JSONValueSchema,LegacyTitledEnumSchemaSchema:()=>LegacyTitledEnumSchemaSchema,ListChangedOptionsBaseSchema:()=>ListChangedOptionsBaseSchema,ListPromptsRequestSchema:()=>ListPromptsRequestSchema,ListPromptsResultSchema:()=>ListPromptsResultSchema,ListResourceTemplatesRequestSchema:()=>ListResourceTemplatesRequestSchema,ListResourceTemplatesResultSchema:()=>ListResourceTemplatesResultSchema,ListResourcesRequestSchema:()=>ListResourcesRequestSchema,ListResourcesResultSchema:()=>ListResourcesResultSchema,ListRootsRequestSchema:()=>ListRootsRequestSchema,ListRootsResultSchema:()=>ListRootsResultSchema,ListTasksRequestSchema:()=>ListTasksRequestSchema,ListTasksResultSchema:()=>ListTasksResultSchema,ListToolsRequestSchema:()=>ListToolsRequestSchema,ListToolsResultSchema:()=>ListToolsResultSchema,LoggingLevelSchema:()=>LoggingLevelSchema,LoggingMessageNotificationParamsSchema:()=>LoggingMessageNotificationParamsSchema,LoggingMessageNotificationSchema:()=>LoggingMessageNotificationSchema,ModelHintSchema:()=>ModelHintSchema,ModelPreferencesSchema:()=>ModelPreferencesSchema,MultiSelectEnumSchemaSchema:()=>MultiSelectEnumSchemaSchema,NotificationSchema:()=>NotificationSchema,NotificationsParamsSchema:()=>NotificationsParamsSchema,NumberSchemaSchema:()=>NumberSchemaSchema,PaginatedRequestParamsSchema:()=>PaginatedRequestParamsSchema,PaginatedRequestSchema:()=>PaginatedRequestSchema,PaginatedResultSchema:()=>PaginatedResultSchema,PingRequestSchema:()=>PingRequestSchema,PrimitiveSchemaDefinitionSchema:()=>PrimitiveSchemaDefinitionSchema,ProgressNotificationParamsSchema:()=>ProgressNotificationParamsSchema,ProgressNotificationSchema:()=>ProgressNotificationSchema,ProgressSchema:()=>ProgressSchema,ProgressTokenSchema:()=>ProgressTokenSchema,PromptArgumentSchema:()=>PromptArgumentSchema,PromptListChangedNotificationSchema:()=>PromptListChangedNotificationSchema,PromptMessageSchema:()=>PromptMessageSchema,PromptReferenceSchema:()=>PromptReferenceSchema,PromptSchema:()=>PromptSchema,ReadResourceRequestParamsSchema:()=>ReadResourceRequestParamsSchema,ReadResourceRequestSchema:()=>ReadResourceRequestSchema,ReadResourceResultSchema:()=>ReadResourceResultSchema,RelatedTaskMetadataSchema:()=>RelatedTaskMetadataSchema,RequestIdSchema:()=>RequestIdSchema,RequestMetaSchema:()=>RequestMetaSchema,RequestSchema:()=>RequestSchema,ResourceContentsSchema:()=>ResourceContentsSchema,ResourceLinkSchema:()=>ResourceLinkSchema,ResourceListChangedNotificationSchema:()=>ResourceListChangedNotificationSchema,ResourceRequestParamsSchema:()=>ResourceRequestParamsSchema,ResourceSchema:()=>ResourceSchema,ResourceTemplateReferenceSchema:()=>ResourceTemplateReferenceSchema,ResourceTemplateSchema:()=>ResourceTemplateSchema,ResourceUpdatedNotificationParamsSchema:()=>ResourceUpdatedNotificationParamsSchema,ResourceUpdatedNotificationSchema:()=>ResourceUpdatedNotificationSchema,ResultMetaObjectSchema:()=>ResultMetaObjectSchema,ResultSchema:()=>ResultSchema,RoleSchema:()=>RoleSchema,RootSchema:()=>RootSchema,RootsListChangedNotificationSchema:()=>RootsListChangedNotificationSchema,SamplingContentSchema:()=>SamplingContentSchema,SamplingMessageContentBlockSchema:()=>SamplingMessageContentBlockSchema,SamplingMessageSchema:()=>SamplingMessageSchema,ServerCapabilitiesSchema:()=>ServerCapabilitiesSchema,ServerNotificationSchema:()=>ServerNotificationSchema,ServerRequestSchema:()=>ServerRequestSchema,ServerResultSchema:()=>ServerResultSchema,ServerTasksCapabilitySchema:()=>ServerTasksCapabilitySchema,SetLevelRequestParamsSchema:()=>SetLevelRequestParamsSchema,SetLevelRequestSchema:()=>SetLevelRequestSchema,SingleSelectEnumSchemaSchema:()=>SingleSelectEnumSchemaSchema,StringSchemaSchema:()=>StringSchemaSchema,SubscribeRequestParamsSchema:()=>SubscribeRequestParamsSchema,SubscribeRequestSchema:()=>SubscribeRequestSchema,SubscriptionFilterSchema:()=>SubscriptionFilterSchema,SubscriptionsAcknowledgedNotificationParamsSchema:()=>SubscriptionsAcknowledgedNotificationParamsSchema,SubscriptionsAcknowledgedNotificationSchema:()=>SubscriptionsAcknowledgedNotificationSchema,SubscriptionsListenRequestParamsSchema:()=>SubscriptionsListenRequestParamsSchema,SubscriptionsListenRequestSchema:()=>SubscriptionsListenRequestSchema,SubscriptionsListenResultMetaSchema:()=>SubscriptionsListenResultMetaSchema,SubscriptionsListenResultSchema:()=>SubscriptionsListenResultSchema,TaskAugmentedRequestParamsSchema:()=>TaskAugmentedRequestParamsSchema,TaskCreationParamsSchema:()=>TaskCreationParamsSchema,TaskMetadataSchema:()=>TaskMetadataSchema,TaskSchema:()=>TaskSchema,TaskStatusNotificationParamsSchema:()=>TaskStatusNotificationParamsSchema,TaskStatusNotificationSchema:()=>TaskStatusNotificationSchema,TaskStatusSchema:()=>TaskStatusSchema,TextContentSchema:()=>TextContentSchema,TextResourceContentsSchema:()=>TextResourceContentsSchema,TitledMultiSelectEnumSchemaSchema:()=>TitledMultiSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema:()=>TitledSingleSelectEnumSchemaSchema,ToolAnnotationsSchema:()=>ToolAnnotationsSchema,ToolChoiceSchema:()=>ToolChoiceSchema,ToolExecutionSchema:()=>ToolExecutionSchema,ToolListChangedNotificationSchema:()=>ToolListChangedNotificationSchema,ToolResultContentSchema:()=>ToolResultContentSchema,ToolSchema:()=>ToolSchema,ToolUseContentSchema:()=>ToolUseContentSchema,UnsubscribeRequestParamsSchema:()=>UnsubscribeRequestParamsSchema,UnsubscribeRequestSchema:()=>UnsubscribeRequestSchema,UntitledMultiSelectEnumSchemaSchema:()=>UntitledMultiSelectEnumSchemaSchema,UntitledSingleSelectEnumSchemaSchema:()=>UntitledSingleSelectEnumSchemaSchema}),isJSONRPCRequest=value=>JSONRPCRequestSchema.safeParse(value).success,isJSONRPCNotification=value=>JSONRPCNotificationSchema.safeParse(value).success,isJSONRPCResultResponse=value=>typeof value=="object"&&value!==null&&Object.hasOwn(value,"result")&&JSONRPCResultResponseSchema.safeParse(value).success,isJSONRPCErrorResponse=value=>typeof value=="object"&&value!==null&&Object.hasOwn(value,"error")&&JSONRPCErrorResponseSchema.safeParse(value).success,isInputRequiredResult=value=>typeof value=="object"&&value!==null&&!Array.isArray(value)&&value.resultType==="input_required",isInitializeRequest=value=>InitializeRequestSchema.safeParse(value).success;MCP_PARAM_HEADER_PREFIX="Mcp-Param-",X_MCP_HEADER_KEY="x-mcp-header",RFC9110_TOKEN=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,PERMITTED_X_MCP_HEADER_TYPES=new Set(["string","integer","boolean","number"]);NON_REACHABLE_SUBSCHEMA_KEYWORDS=["items","prefixItems","contains","additionalProperties","unevaluatedProperties","unevaluatedItems","propertyNames","patternProperties","dependentSchemas","oneOf","anyOf","allOf","not","if","then","else","$defs","definitions"],OBJECT_VALUED_SUBSCHEMA_KEYWORDS=new Set(["patternProperties","dependentSchemas","$defs","definitions"]);BASE64_SENTINEL_PREFIX="=?base64?",BASE64_SENTINEL_SUFFIX="?=",BASE64_CANONICAL=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,CANONICAL_DECIMAL=/^-?\d+(\.\d+)?$/;HEADER_MISMATCH_ERROR_CODE=-32020,INBOUND_VALIDATION_LADDER=[{rung:"http-method",order:1,evaluatedAt:"edge",codes:[-32e3],conformance:[],rationale:"The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read."},{rung:"jsonrpc-shape",order:2,evaluatedAt:"edge",codes:[ProtocolErrorCode.InvalidRequest],conformance:["server-stateless"],rationale:"The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic."},{rung:"era-classification",order:3,evaluatedAt:"edge",codes:[HEADER_MISMATCH_ERROR_CODE,ProtocolErrorCode.UnsupportedProtocolVersion],conformance:["server-stateless","http-header-validation","http-custom-header-server-validation"],rationale:"Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions."},{rung:"envelope",order:4,evaluatedAt:"edge",codes:[ProtocolErrorCode.InvalidParams],conformance:["server-stateless"],rationale:"A present envelope claim with a malformed envelope \u2014 and a missing envelope on a request whose protocol-version header names a modern revision \u2014 is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400."},{rung:"method-registry",order:5,evaluatedAt:"dispatch",codes:[ProtocolErrorCode.MethodNotFound],conformance:["server-stateless"],rationale:"Method existence outranks parameter validity: a method absent from the negotiated revision\u2019s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at."},{rung:"request-params",order:6,evaluatedAt:"dispatch",codes:[ProtocolErrorCode.InvalidParams],conformance:[],rationale:"Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table."},{rung:"standard-header-validation",order:7,evaluatedAt:"pre-dispatch",codes:[HEADER_MISMATCH_ERROR_CODE],conformance:["http-header-validation"],rationale:"SEP-2243 standard `Mcp-Method` / `Mcp-Name` headers \u2014 presence, sentinel decoding, and `Mcp-Name` \u2194 body cross-check \u2014 are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The classifier\u2019s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5\u20136) are consulted."},{rung:"client-capabilities",order:8,evaluatedAt:"pre-dispatch",codes:[ProtocolErrorCode.MissingRequiredClientCapability],conformance:["server-stateless"],rationale:"The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced \u2014 pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable."},{rung:"param-header-validation",order:9,evaluatedAt:"pre-dispatch",codes:[HEADER_MISMATCH_ERROR_CODE],conformance:["http-custom-header-server-validation"],rationale:"SEP-2243 `Mcp-Param-*` headers are validated against the named tool\u2019s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung."}],LADDER_ERROR_HTTP_STATUS={[ProtocolErrorCode.ParseError]:400,[ProtocolErrorCode.InvalidRequest]:400,[ProtocolErrorCode.MethodNotFound]:404,[ProtocolErrorCode.UnsupportedProtocolVersion]:400,[ProtocolErrorCode.MissingRequiredClientCapability]:400,[HEADER_MISMATCH_ERROR_CODE]:400};MCP_NAME_HEADER_SOURCE={"tools/call":"name","prompts/get":"name","resources/read":"uri"};warnedZodFallback=!1,JSON_SCHEMA_CONVERSION_TARGET="draft-2020-12";DATETIME_FRACTION_DIGITS=/\\\.\\d\{(\d+)\}/;ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);ROOT_KEYS=new Set(["$schema",...Object.keys(ElicitRequestFormParamsSchema.shape.requestedSchema.shape)]),PROPERTY_KEYS_BY_TYPE={string:shapeKeys([StringSchemaSchema,UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema,LegacyTitledEnumSchemaSchema]),number:shapeKeys([NumberSchemaSchema]),integer:shapeKeys([NumberSchemaSchema]),boolean:shapeKeys([BooleanSchemaSchema]),array:shapeKeys([UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema])},SUPPORTED_STRING_FORMATS=new Set(StringSchemaSchema.shape.format.unwrap().options);inputRequired=Object.assign(buildInputRequired,{elicit(params){try{return{method:"elicitation/create",params:normalizeElicitInputParams(params)}}catch(error3){throw error3 instanceof ProtocolError?new TypeError(error3.message,{cause:error3}):error3}},elicitUrl(params){return{method:"elicitation/create",params:{...params,mode:"url"}}},createMessage(params){return{method:"sampling/createMessage",params}},listRoots(){return{method:"roots/list"}}});REQUEST_STATE_ONLY_LEG_PACING_MS=250;SPEC_SCHEMA_KEYS=["AnnotationsSchema","AudioContentSchema","BaseMetadataSchema","BlobResourceContentsSchema","BooleanSchemaSchema","CallToolRequestSchema","CallToolRequestParamsSchema","CallToolResultSchema","CancelledNotificationSchema","CancelledNotificationParamsSchema","CancelTaskRequestSchema","CancelTaskResultSchema","ClientCapabilitiesSchema","ClientNotificationSchema","ClientRequestSchema","ClientResultSchema","CompatibilityCallToolResultSchema","CompleteRequestSchema","CompleteRequestParamsSchema","CompleteResultSchema","ContentBlockSchema","CreateMessageRequestSchema","CreateMessageRequestParamsSchema","CreateMessageResultSchema","CreateMessageResultWithToolsSchema","CreateTaskResultSchema","CursorSchema","DiscoverRequestSchema","DiscoverResultSchema","ElicitationCompleteNotificationSchema","ElicitationCompleteNotificationParamsSchema","ElicitRequestSchema","ElicitRequestFormParamsSchema","ElicitRequestParamsSchema","ElicitRequestURLParamsSchema","ElicitResultSchema","EmbeddedResourceSchema","EmptyResultSchema","EnumSchemaSchema","GetPromptRequestSchema","GetPromptRequestParamsSchema","GetPromptResultSchema","GetTaskPayloadRequestSchema","GetTaskPayloadResultSchema","GetTaskRequestSchema","GetTaskResultSchema","IconSchema","IconsSchema","ImageContentSchema","ImplementationSchema","InitializedNotificationSchema","InitializeRequestSchema","InitializeRequestParamsSchema","InitializeResultSchema","JSONArraySchema","JSONObjectSchema","JSONRPCErrorResponseSchema","JSONRPCMessageSchema","JSONRPCNotificationSchema","JSONRPCRequestSchema","JSONRPCResponseSchema","JSONRPCResultResponseSchema","JSONValueSchema","LegacyTitledEnumSchemaSchema","ListPromptsRequestSchema","ListPromptsResultSchema","ListResourcesRequestSchema","ListResourcesResultSchema","ListResourceTemplatesRequestSchema","ListResourceTemplatesResultSchema","ListRootsRequestSchema","ListRootsResultSchema","ListTasksRequestSchema","ListTasksResultSchema","ListToolsRequestSchema","ListToolsResultSchema","LoggingLevelSchema","LoggingMessageNotificationSchema","LoggingMessageNotificationParamsSchema","ModelHintSchema","ModelPreferencesSchema","MultiSelectEnumSchemaSchema","NotificationSchema","NumberSchemaSchema","PaginatedRequestSchema","PaginatedRequestParamsSchema","PaginatedResultSchema","PingRequestSchema","PrimitiveSchemaDefinitionSchema","ProgressSchema","ProgressNotificationSchema","ProgressNotificationParamsSchema","ProgressTokenSchema","PromptSchema","PromptArgumentSchema","PromptListChangedNotificationSchema","PromptMessageSchema","PromptReferenceSchema","ReadResourceRequestSchema","ReadResourceRequestParamsSchema","ReadResourceResultSchema","RelatedTaskMetadataSchema","RequestSchema","RequestIdSchema","RequestMetaSchema","ResourceSchema","ResourceContentsSchema","ResourceLinkSchema","ResourceListChangedNotificationSchema","ResourceRequestParamsSchema","ResourceTemplateSchema","ResourceTemplateReferenceSchema","ResourceUpdatedNotificationSchema","ResourceUpdatedNotificationParamsSchema","ResultMetaObjectSchema","ResultSchema","RoleSchema","RootSchema","RootsListChangedNotificationSchema","SamplingContentSchema","SamplingMessageSchema","SamplingMessageContentBlockSchema","ServerCapabilitiesSchema","ServerNotificationSchema","ServerRequestSchema","ServerResultSchema","SetLevelRequestSchema","SetLevelRequestParamsSchema","SingleSelectEnumSchemaSchema","StringSchemaSchema","SubscribeRequestSchema","SubscribeRequestParamsSchema","SubscriptionFilterSchema","SubscriptionsAcknowledgedNotificationSchema","SubscriptionsAcknowledgedNotificationParamsSchema","SubscriptionsListenRequestSchema","SubscriptionsListenRequestParamsSchema","SubscriptionsListenResultSchema","SubscriptionsListenResultMetaSchema","TaskAugmentedRequestParamsSchema","TaskCreationParamsSchema","TaskMetadataSchema","TaskSchema","TaskStatusSchema","TaskStatusNotificationSchema","TaskStatusNotificationParamsSchema","TextContentSchema","TextResourceContentsSchema","TitledMultiSelectEnumSchemaSchema","TitledSingleSelectEnumSchemaSchema","ToolSchema","ToolAnnotationsSchema","ToolChoiceSchema","ToolExecutionSchema","ToolListChangedNotificationSchema","ToolResultContentSchema","ToolUseContentSchema","UnsubscribeRequestSchema","UnsubscribeRequestParamsSchema","UntitledMultiSelectEnumSchemaSchema","UntitledSingleSelectEnumSchemaSchema"],authSchemas={IdJagTokenExchangeResponseSchema,OAuthClientInformationFullSchema,OAuthClientInformationSchema,OAuthClientMetadataSchema,OAuthClientRegistrationErrorSchema,OAuthErrorResponseSchema,OAuthMetadataSchema,OAuthProtectedResourceMetadataSchema,OAuthTokenRevocationRequestSchema,OAuthTokensSchema,OpenIdProviderDiscoveryMetadataSchema,OpenIdProviderMetadataSchema},_specTypeSchemas={},_isSpecType={};for(let key of SPEC_SCHEMA_KEYS)register(key,schemas_exports2[key]);for(let[key,schema2]of Object.entries(authSchemas))register(key,schema2);specTypeSchemas=Object.freeze(_specTypeSchemas),isSpecType=Object.freeze(_isSpecType);DEFAULT_REQUEST_TIMEOUT_MSEC=6e4,RESERVED_ENVELOPE_META_KEYS=[PROTOCOL_VERSION_META_KEY,CLIENT_INFO_META_KEY,CLIENT_CAPABILITIES_META_KEY,LOG_LEVEL_META_KEY],RETRY_PARAMS_KEYS=["inputResponses","requestState"];NO_REQUEST_STATE=requestStateAccessor(void 0);Protocol=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{writeNegotiatedProtocolVersion=(instance,version2)=>{instance._negotiatedProtocolVersion=version2}}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(_options){this._options=_options,this._supportedProtocolVersions=_options?.supportedProtocolVersions??SUPPORTED_PROTOCOL_VERSIONS,this.setNotificationHandler("notifications/cancelled",notification=>{this._oncancel(notification)}),this.setNotificationHandler("notifications/progress",notification=>{this._onprogress(notification)}),this.setRequestHandler("ping",_request=>({}))}_shouldDropInbound(_message){}_outboundMetaEnvelope(){}_envelopeOutbound(message){let envelope=this._outboundMetaEnvelope();if(envelope===void 0)return message;let params=message.params??{};return{...message,params:{...params,_meta:{...envelope,...params._meta}}}}_resolveNonCompleteResult(decoded,flow){return Promise.reject(new SdkError(SdkErrorCode.UnsupportedResultType,`Unsupported result type '${decoded.kind}' for ${flow.request.method}`,{resultType:decoded.kind,method:flow.request.method}))}_getRequestHandler(method){return this._requestHandlers.get(method)}async _oncancel(notification){notification.params.requestId&&this._requestHandlerAbortControllers.get(notification.params.requestId)?.abort(notification.params.reason)}_setupTimeout(messageId,timeout,maxTotalTimeout,onTimeout,resetTimeoutOnProgress=!1){this._timeoutInfo.set(messageId,{timeoutId:setTimeout(onTimeout,timeout),startTime:Date.now(),timeout,maxTotalTimeout,resetTimeoutOnProgress,onTimeout})}_resetTimeout(messageId){let info=this._timeoutInfo.get(messageId);if(!info)return!1;let totalElapsed=Date.now()-info.startTime;if(info.maxTotalTimeout&&totalElapsed>=info.maxTotalTimeout)throw this._timeoutInfo.delete(messageId),new SdkError(SdkErrorCode.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:info.maxTotalTimeout,totalElapsed});return clearTimeout(info.timeoutId),info.timeoutId=setTimeout(info.onTimeout,info.timeout),!0}_cleanupTimeout(messageId){let info=this._timeoutInfo.get(messageId);info&&(clearTimeout(info.timeoutId),this._timeoutInfo.delete(messageId))}async connect(transport){this._transport=transport;let _onclose=this.transport?.onclose;this._transport.onclose=()=>{try{_onclose?.()}finally{this._onclose()}};let _onerror=this.transport?.onerror;this._transport.onerror=error3=>{_onerror?.(error3),this._onerror(error3)};let _onmessage=this._transport?.onmessage;this._transport.onmessage=(message,extra)=>{_onmessage?.(message,extra),isJSONRPCResultResponse(message)||isJSONRPCErrorResponse(message)?this._onresponse(message):isJSONRPCRequest(message)?this._onrequest(message,extra):isJSONRPCNotification(message)?this._onnotification(message,extra):this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`))},transport.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let responseHandlers=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(let info of this._timeoutInfo.values())clearTimeout(info.timeoutId);this._timeoutInfo.clear();let requestHandlerAbortControllers=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let error3=new SdkError(SdkErrorCode.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(let handler of responseHandlers.values())handler(error3);for(let controller of requestHandlerAbortControllers.values())controller.abort(error3)}}_onerror(error3){this.onerror?.(error3)}_onnotification(rawNotification,extra){let{message:notification}=liftWireOnlyMaterial(rawNotification,"notification"),codec=this._negotiatedWireCodec();if(extra?.classification===void 0&&this._shouldDropInbound(rawNotification)==="drop")return;if(extra?.classification!==void 0){let classified=classifiedWireEra(extra.classification);if(classified!==codec.era){this._onerror(new Error(`Era mismatch on inbound notification '${notification.method}': classified as ${classified} but this instance serves ${codec.era}`));return}}if(isSpecNotificationMethod(notification.method)&&!codec.hasNotificationMethod(notification.method))return;let handler=this._notificationHandlers.get(notification.method),fallback=this.fallbackNotificationHandler;handler===void 0&&fallback===void 0||Promise.resolve().then(()=>handler===void 0?fallback(notification):handler(notification,codec)).catch(error3=>this._onerror(new Error(`Uncaught error in notification handler: ${error3}`)))}_onrequest(rawRequest,extra){let{message:request,lifted}=liftWireOnlyMaterial(rawRequest,"request"),codec=this._negotiatedWireCodec();if(extra?.classification===void 0&&this._shouldDropInbound(rawRequest)==="drop"){this._onerror(new Error(`Dropped inbound request '${rawRequest.method}': not servable on this connection's protocol era`));return}let capturedTransport=this._transport,sendErrorResponse=(code,message,data)=>{let errorResponse={jsonrpc:"2.0",id:request.id,error:{code,message,...data!==void 0&&{data}}};capturedTransport?.send(errorResponse).catch(error3=>this._onerror(new Error(`Failed to send an error response: ${error3}`)))};if(extra?.classification!==void 0){let classified=classifiedWireEra(extra.classification);if(classified!==codec.era){this._onerror(new Error(`Era mismatch on inbound request '${request.method}': classified as ${classified} but this instance serves ${codec.era}`));let requested=extra.classification.revision??classified;sendErrorResponse(ProtocolErrorCode.UnsupportedProtocolVersion,`Unsupported protocol version: ${requested}`,{supported:this._supportedProtocolVersions,requested});return}}if(isSpecRequestMethod(request.method)&&!codec.hasRequestMethod(request.method)){sendErrorResponse(ProtocolErrorCode.MethodNotFound,"Method not found");return}let handler=this._requestHandlers.get(request.method)??this.fallbackRequestHandler;if(handler===void 0){sendErrorResponse(ProtocolErrorCode.MethodNotFound,"Method not found");return}let envelopeError=codec.checkInboundEnvelope(lifted);if(envelopeError!==void 0){sendErrorResponse(ProtocolErrorCode.InvalidParams,envelopeError);return}let sendNotification=(notification,options)=>this._notificationViaCodec(this._resolveOutboundCodec(notification.method),notification,{...options,relatedRequestId:request.id}),sendRequest=(r,resultSchema,options)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(r.method),r,resultSchema,{...options,relatedRequestId:request.id}),abortController=new AbortController;this._requestHandlerAbortControllers.set(request.id,abortController);let partitionedInputResponses=lifted.inputResponses===void 0?void 0:partitionInputResponses(lifted.inputResponses),baseCtx={sessionId:capturedTransport?.sessionId,mcpReq:{id:request.id,method:request.method,_meta:request.params?._meta,...lifted.envelope!==void 0&&{envelope:lifted.envelope},...partitionedInputResponses!==void 0&&{inputResponses:partitionedInputResponses.accepted},...partitionedInputResponses!==void 0&&partitionedInputResponses.droppedKeys.length>0&&{droppedInputResponseKeys:partitionedInputResponses.droppedKeys},requestState:lifted.requestState===void 0?NO_REQUEST_STATE:requestStateAccessor(lifted.requestState),signal:abortController.signal,send:((r,schemaOrOptions,maybeOptions)=>{let sendCodec=this._resolveOutboundCodec(r.method);if(this._assertOutboundRequestInEra(sendCodec,r.method),isStandardSchema(schemaOrOptions))return sendRequest(r,schemaOrOptions,maybeOptions);let validate=codecResultValidator(sendCodec,r.method);if(validate===void 0)throw new TypeError(`'${r.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return sendRequest(r,validate,schemaOrOptions)}),notify:sendNotification},http:extra?.authInfo?{authInfo:extra.authInfo}:void 0},ctx=this.buildContext(baseCtx,extra);Promise.resolve().then(()=>handler(request,ctx)).then(async result=>{if(abortController.signal.aborted)return;let encoded;try{encoded=codec.encodeResult(request.method,result,this._outboundServerInfo())}catch(error3){this._onerror(new Error(`Failed to encode result for ${request.method}: ${error3}`)),sendErrorResponse(ProtocolErrorCode.InternalError,"Internal error");return}let response={result:encoded,jsonrpc:"2.0",id:request.id};await capturedTransport?.send(response)},async error3=>{if(abortController.signal.aborted)return;let thrownCode=Number.isSafeInteger(error3.code)?error3.code:ProtocolErrorCode.InternalError,errorResponse={jsonrpc:"2.0",id:request.id,error:{code:codec.encodeErrorCode(thrownCode),message:error3.message??"Internal error",...error3.data!==void 0&&{data:error3.data}}};await capturedTransport?.send(errorResponse)}).catch(error3=>this._onerror(new Error(`Failed to send response: ${error3}`))).finally(()=>{this._requestHandlerAbortControllers.get(request.id)===abortController&&this._requestHandlerAbortControllers.delete(request.id)})}_onprogress(notification){let{progressToken,...params}=notification.params,messageId=Number(progressToken),handler=this._progressHandlers.get(messageId);if(!handler){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));return}let responseHandler=this._responseHandlers.get(messageId),timeoutInfo=this._timeoutInfo.get(messageId);if(timeoutInfo&&responseHandler&&timeoutInfo.resetTimeoutOnProgress)try{this._resetTimeout(messageId)}catch(error3){this._responseHandlers.delete(messageId),this._progressHandlers.delete(messageId),this._cleanupTimeout(messageId),responseHandler(error3);return}handler(params)}_onresponse(response){let messageId=Number(response.id),handler=this._responseHandlers.get(messageId);if(handler===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));return}this._responseHandlers.delete(messageId),this._cleanupTimeout(messageId),this._progressHandlers.delete(messageId),isJSONRPCResultResponse(response)?handler(response):handler(ProtocolError.fromError(response.error.code,response.error.message,response.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(request,schemaOrOptions,maybeOptions){let codec=this._resolveOutboundCodec(request.method);if(this._assertOutboundRequestInEra(codec,request.method),isStandardSchema(schemaOrOptions))return this._requestWithSchemaViaCodec(codec,request,schemaOrOptions,maybeOptions);let validate=codecResultValidator(codec,request.method);if(validate===void 0)throw new TypeError(`'${request.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(codec,request,validate,schemaOrOptions)}_negotiatedWireCodec(){return codecForVersion(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(method){if(this._negotiatedProtocolVersion===void 0){let pinned=bootstrapOutboundCodec(method);if(pinned)return pinned}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(codec,method){if(isSpecRequestMethod(method)&&!codec.hasRequestMethod(method))throw new SdkError(SdkErrorCode.MethodNotSupportedByProtocolVersion,`Method '${method}' is not supported by the negotiated protocol version (wire era ${codec.era})`,{method,era:codec.era})}_requestWithSchema(request,resultSchema,options){let codec=this._resolveOutboundCodec(request.method);return this._assertOutboundRequestInEra(codec,request.method),this._requestWithSchemaViaCodec(codec,request,resultSchema,options)}_requestWithSchemaViaCodec(codec,request,resultSchema,options){let{relatedRequestId,resumptionToken,onresumptiontoken,headers}=options??{},flowStartedAt=Date.now(),onAbort,cleanupMessageId;return new Promise((resolve,reject)=>{let earlyReject=error3=>{reject(error3)};if(!this._transport){earlyReject(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(request.method)}catch(error3){earlyReject(error3);return}if(options?.signal?.aborted){let reason=options.signal.reason;throw reason instanceof SdkError?reason:new SdkError(SdkErrorCode.RequestTimeout,String(reason))}let requestAbort=codec.era===MODERN_WIRE_REVISION&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,messageId=this._requestMessageId++;cleanupMessageId=messageId;let jsonrpcRequest={...request,jsonrpc:"2.0",id:messageId};options?.onprogress&&(this._progressHandlers.set(messageId,options.onprogress),jsonrpcRequest.params={...request.params,_meta:{...request.params?._meta,progressToken:messageId}});let outbound=this._envelopeOutbound(jsonrpcRequest),responseReceived=!1,cancel=reason=>{responseReceived||(this._progressHandlers.delete(messageId),requestAbort===void 0?this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:messageId,reason:String(reason)}}),{relatedRequestId,resumptionToken,onresumptiontoken}).catch(error3=>this._onerror(new Error(`Failed to send cancellation: ${error3}`))):requestAbort.abort(),reject(reason instanceof SdkError?reason:new SdkError(SdkErrorCode.RequestTimeout,String(reason))))};this._responseHandlers.set(messageId,response=>{if(options?.signal?.aborted)return;if(responseReceived=!0,response instanceof Error)return reject(response);let decoded;try{decoded=codec.decodeResult(request.method,response.result)}catch(error3){return reject(error3 instanceof Error?error3:new Error(String(error3)))}if(decoded.kind==="invalid")return reject(decoded.error);if(decoded.kind==="input_required"){if(options?.allowInputRequired===!0)return resolve(manualInputRequiredValue(decoded));let flow={codec,request,resultSchema,options,flowStartedAt,retry:(params,legOptions)=>this._requestWithSchemaViaCodec(codec,params===void 0?{method:request.method}:{method:request.method,params},resultSchema,legOptions)};return resolve(this._resolveNonCompleteResult(decoded,flow))}let result=decoded.result;validateStandardSchema(resultSchema,result).then(parseResult=>{parseResult.success?resolve(parseResult.data):reject(new SdkError(SdkErrorCode.InvalidResult,`Invalid result for ${request.method}: ${parseResult.error}`))},reject)}),onAbort=()=>cancel(options?.signal?.reason),options?.signal?.addEventListener("abort",onAbort,{once:!0});let timeout=options?.timeout??DEFAULT_REQUEST_TIMEOUT_MSEC,timeoutHandler=()=>cancel(new SdkError(SdkErrorCode.RequestTimeout,"Request timed out",{timeout}));this._setupTimeout(messageId,timeout,options?.maxTotalTimeout,timeoutHandler,options?.resetTimeoutOnProgress??!1),this._transport.send(outbound,{relatedRequestId,resumptionToken,onresumptiontoken,headers,requestSignal:requestAbort?.signal}).catch(error3=>{this._progressHandlers.delete(messageId),reject(error3)})}).finally(()=>{onAbort&&options?.signal?.removeEventListener("abort",onAbort),cleanupMessageId!==void 0&&(this._responseHandlers.delete(cleanupMessageId),this._cleanupTimeout(cleanupMessageId))})}async notification(notification,options){return this._notificationViaCodec(this._resolveOutboundCodec(notification.method),notification,options)}async _notificationViaCodec(codec,notification,options){if(!this._transport)throw new SdkError(SdkErrorCode.NotConnected,"Not connected");if(isSpecNotificationMethod(notification.method)&&!codec.hasNotificationMethod(notification.method))throw new SdkError(SdkErrorCode.MethodNotSupportedByProtocolVersion,`Notification '${notification.method}' is not supported by the negotiated protocol version (wire era ${codec.era})`,{method:notification.method,era:codec.era});this.assertNotificationCapability(notification.method);let jsonrpcNotification=this._envelopeOutbound({jsonrpc:"2.0",...notification});if((this._options?.debouncedNotificationMethods??[]).includes(notification.method)&&!notification.params&&!options?.relatedRequestId){if(this._pendingDebouncedNotifications.has(notification.method))return;this._pendingDebouncedNotifications.add(notification.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(notification.method),this._transport&&this._transport?.send(jsonrpcNotification,options).catch(error3=>this._onerror(error3))});return}await this._transport.send(jsonrpcNotification,options)}setRequestHandler(method,schemasOrHandler,maybeHandler){this.assertRequestHandlerCapability(method);let stored;if(typeof schemasOrHandler=="function"){if(!isSpecRequestMethod(method))throw new TypeError(`'${method}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);stored=(request,ctx)=>{let dispatchCodec=this._negotiatedWireCodec(),outcome=dispatchCodec.validateRequest(method,request);if(!outcome.ok&&outcome.reason==="not-in-era"&&(outcome=dispatchCodec.validateInputRequest(method,request)),!outcome.ok)throw outcome.reason==="not-in-era"?new ProtocolError(ProtocolErrorCode.InternalError,`No wire schema for ${method} in the resolved era`):new Error(outcome.message);return Promise.resolve(schemasOrHandler(outcome.value,ctx))}}else if(maybeHandler)stored=async(request,ctx)=>{let parsed=await validateStandardSchema(schemasOrHandler.params,{...request.params});if(!parsed.success)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Invalid params for ${method}: ${parsed.error}`);return maybeHandler(parsed.data,ctx)};else throw new TypeError("setRequestHandler: handler is required");this._requestHandlers.set(method,this._wrapHandler(method,stored))}_wrapHandler(_method,handler){return handler}_outboundServerInfo(){}removeRequestHandler(method){this._requestHandlers.delete(method)}assertCanSetRequestHandler(method){if(this._requestHandlers.has(method))throw new Error(`A request handler for ${method} already exists, which would be overridden`)}setNotificationHandler(method,schemasOrHandler,maybeHandler){if(typeof schemasOrHandler=="function"){if(!isSpecNotificationMethod(method))throw new TypeError(`'${method}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(method,(notification,codec)=>{let outcome=codec.validateNotification(method,notification);if(!outcome.ok)throw outcome.reason==="not-in-era"?new ProtocolError(ProtocolErrorCode.InternalError,`No wire schema for ${method} in the resolved era`):new Error(outcome.message);return Promise.resolve(schemasOrHandler(outcome.value))});return}if(!maybeHandler)throw new TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(method,async notification=>{let parsed=await validateStandardSchema(schemasOrHandler.params,{...notification.params});if(!parsed.success)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Invalid params for notification ${method}: ${parsed.error}`);await maybeHandler(parsed.data,notification)})}removeNotificationHandler(method){this._notificationHandlers.delete(method)}};require_content_type=__commonJSMin((exports=>{var PARAM_REGEXP=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,QESC_REGEXP=/\\([\u000b\u0020-\u00ff])/g,TYPE_REGEXP=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;exports.parse=parse3;function parse3(string4){if(!string4)throw new TypeError("argument string is required");var header=typeof string4=="object"?getcontenttype(string4):string4;if(typeof header!="string")throw new TypeError("argument string is required to be a string");var index=header.indexOf(";"),type=index!==-1?header.slice(0,index).trim():header.trim();if(!TYPE_REGEXP.test(type))throw new TypeError("invalid media type");var obj=new ContentType(type.toLowerCase());if(index!==-1){var key,match2,value;for(PARAM_REGEXP.lastIndex=index;match2=PARAM_REGEXP.exec(header);){if(match2.index!==index)throw new TypeError("invalid parameter format");index+=match2[0].length,key=match2[1].toLowerCase(),value=match2[2],value.charCodeAt(0)===34&&(value=value.slice(1,-1),value.indexOf("\\")!==-1&&(value=value.replace(QESC_REGEXP,"$1"))),obj.parameters[key]=value}if(index!==header.length)throw new TypeError("invalid parameter format")}return obj}function getcontenttype(obj){var header;if(typeof obj.getHeader=="function"?header=obj.getHeader("content-type"):typeof obj.headers=="object"&&(header=obj.headers&&obj.headers["content-type"]),typeof header!="string")throw new TypeError("content-type header is missing from object");return header}function ContentType(type){this.parameters=Object.create(null),this.type=type}})),import_content_type=__toESM(require_content_type(),1);STDIO_DEFAULT_MAX_BUFFER_SIZE=10*1024*1024,TOOL_NAME_REGEX=/^[A-Za-z0-9._-]{1,128}$/;MAX_TEMPLATE_LENGTH=1e6,MAX_VARIABLE_LENGTH=1e6,MAX_TEMPLATE_EXPRESSIONS=1e4,MAX_REGEX_LENGTH=1e6,UriTemplate=class UriTemplate2{static isTemplate(str){return/\{[^}\s]+\}/.test(str)}static validateLength(str,max,context){if(str.length>max)throw new Error(`${context} exceeds maximum length of ${max} characters (got ${str.length})`)}template;parts;get variableNames(){return this.parts.flatMap(part=>typeof part=="string"?[]:part.names)}constructor(template){UriTemplate2.validateLength(template,MAX_TEMPLATE_LENGTH,"Template"),this.template=template,this.parts=this.parse(template)}toString(){return this.template}parse(template){let parts=[],currentText="",i=0,expressionCount=0;for(;i<template.length;)if(template[i]==="{"){currentText&&(parts.push(currentText),currentText="");let end=template.indexOf("}",i);if(end===-1)throw new Error("Unclosed template expression");if(expressionCount++,expressionCount>MAX_TEMPLATE_EXPRESSIONS)throw new Error(`Template contains too many expressions (max ${MAX_TEMPLATE_EXPRESSIONS})`);let expr=template.slice(i+1,end),operator=this.getOperator(expr),exploded=expr.includes("*"),names=this.getNames(expr),name=names[0];for(let name$1 of names)UriTemplate2.validateLength(name$1,MAX_VARIABLE_LENGTH,"Variable name");parts.push({name,operator,names,exploded}),i=end+1}else currentText+=template[i],i++;return currentText&&parts.push(currentText),parts}getOperator(expr){return["+","#",".","/","?","&"].find(op=>expr.startsWith(op))||""}getNames(expr){let operator=this.getOperator(expr);return expr.slice(operator.length).split(",").map(name=>name.replace("*","").trim()).filter(name=>name.length>0)}encodeValue(value,operator){return UriTemplate2.validateLength(value,MAX_VARIABLE_LENGTH,"Variable value"),operator==="+"||operator==="#"?encodeURI(value):encodeURIComponent(value)}expandPart(part,variables){if(part.operator==="?"||part.operator==="&"){let pairs=part.names.map(name=>{let value$1=variables[name];return value$1===void 0?"":`${name}=${Array.isArray(value$1)?value$1.map(v=>this.encodeValue(v,part.operator)).join(","):this.encodeValue(value$1.toString(),part.operator)}`}).filter(pair=>pair.length>0);return pairs.length===0?"":(part.operator==="?"?"?":"&")+pairs.join("&")}if(part.names.length>1){let values=part.names.map(name=>variables[name]).filter(v=>v!==void 0);return values.length===0?"":values.map(v=>Array.isArray(v)?v[0]:v).join(",")}let value=variables[part.name];if(value===void 0)return"";let encoded=(Array.isArray(value)?value:[value]).map(v=>this.encodeValue(v,part.operator));switch(part.operator){case"":return encoded.join(",");case"+":return encoded.join(",");case"#":return"#"+encoded.join(",");case".":return"."+encoded.join(".");case"/":return"/"+encoded.join("/");default:return encoded.join(",")}}expand(variables){let result="",hasQueryParam=!1;for(let part of this.parts){if(typeof part=="string"){result+=part;continue}let expanded=this.expandPart(part,variables);expanded&&(result+=(part.operator==="?"||part.operator==="&")&&hasQueryParam?expanded.replace("?","&"):expanded,(part.operator==="?"||part.operator==="&")&&(hasQueryParam=!0))}return result}escapeRegExp(str){return str.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`)}partToRegExp(part){let patterns=[];for(let name$1 of part.names)UriTemplate2.validateLength(name$1,MAX_VARIABLE_LENGTH,"Variable name");if(part.operator==="?"||part.operator==="&"){for(let i=0;i<part.names.length;i++){let name$1=part.names[i],prefix=i===0?"\\"+part.operator:"&";patterns.push({pattern:prefix+this.escapeRegExp(name$1)+"=([^&]+)",name:name$1})}return patterns}let pattern,name=part.name;switch(part.operator){case"":pattern=part.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)";break;case"+":case"#":pattern="(.+)";break;case".":pattern=String.raw`\.([^/,]+)`;break;case"/":pattern="/"+(part.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)");break;default:pattern="([^/]+)"}return patterns.push({pattern,name}),patterns}match(uri){UriTemplate2.validateLength(uri,MAX_TEMPLATE_LENGTH,"URI");let pattern="^",names=[];for(let part of this.parts)if(typeof part=="string")pattern+=this.escapeRegExp(part);else{let patterns=this.partToRegExp(part);for(let{pattern:partPattern,name}of patterns)pattern+=partPattern,names.push({name,exploded:part.exploded})}pattern+="$",UriTemplate2.validateLength(pattern,MAX_REGEX_LENGTH,"Generated regex pattern");let regex=new RegExp(pattern),match2=uri.match(regex);if(!match2)return null;let result={};for(let[i,name_]of names.entries()){let{name,exploded}=name_,value=match2[i+1],cleanName=name.replace("*","");result[cleanName]=exploded&&value.includes(",")?value.split(","):value}return result}}}});function createDefaultAjvInstance(engineClass){let ajv=new engineClass({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return addFormats(ajv),ajv}var require_code$1,require_scope,require_codegen,require_util,require_names,require_errors,require_boolSchema,require_rules,require_applicability,require_dataType,require_defaults,require_code,require_keyword,require_subschema,require_fast_deep_equal,require_json_schema_traverse,require_resolve,require_validate,require_validation_error,require_ref_error,require_compile,require_data,require_utils,require_schemes,require_fast_uri,require_uri,require_core$3,require_id,require_ref,require_core$2,require_limitNumber,require_multipleOf,require_ucs2length,require_limitLength,require_pattern,require_limitProperties,require_required,require_limitItems,require_equal,require_uniqueItems,require_const,require_enum,require_validation$2,require_additionalItems,require_items,require_prefixItems,require_items2020,require_contains,require_dependencies,require_propertyNames,require_additionalProperties,require_properties,require_patternProperties,require_not,require_anyOf,require_oneOf,require_allOf,require_if,require_thenElse,require_applicator$2,require_format$2,require_format$1,require_metadata,require_draft7,require_types,require_discriminator,require_json_schema_draft_07,require_ajv,require_dynamicAnchor,require_dynamicRef,require_recursiveAnchor,require_recursiveRef,require_dynamic,require_dependentRequired,require_dependentSchemas,require_limitContains,require_next,require_unevaluatedProperties,require_unevaluatedItems,require_unevaluated$1,require_schema$1,require_applicator$1,require_content$1,require_core$1,require_format,require_meta_data$1,require_validation$1,require_json_schema_2019_09,require__2019,require_draft2020,require_schema,require_applicator,require_unevaluated,require_content,require_core,require_format_annotation,require_meta_data,require_validation,require_json_schema_2020_12,require__2020,require_formats,require_limit,require_dist,import_ajv,import__2019,import__2020,import_dist,addFormats,AjvJsonSchemaValidator,Ajv,init_ajvProvider_CEoC_sr=__esm({"../../node_modules/.pnpm/@modelcontextprotocol+server@2.0.0_patch_hash=2a5f5402571efdc40802e9603a3dd09e22588b4aacad710814c204d79568091e/node_modules/@modelcontextprotocol/server/dist/ajvProvider-CEoC__sr.mjs"(){"use strict";init_chunk_Br0eD_fh();init_dialects_DoSzNhcb();require_code$1=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.regexpCode=exports.getEsmExportName=exports.getProperty=exports.safeStringify=exports.stringify=exports.strConcat=exports.addCodeArg=exports.str=exports._=exports.nil=exports._Code=exports.Name=exports.IDENTIFIER=exports._CodeOrName=void 0;var _CodeOrName=class{};exports._CodeOrName=_CodeOrName,exports.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Name=class extends _CodeOrName{constructor(s){if(super(),!exports.IDENTIFIER.test(s))throw new Error("CodeGen: name must be a valid identifier");this.str=s}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};exports.Name=Name;var _Code=class extends _CodeOrName{constructor(code){super(),this._items=typeof code=="string"?[code]:code}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let item=this._items[0];return item===""||item==='""'}get str(){var _a3;return(_a3=this._str)!==null&&_a3!==void 0?_a3:this._str=this._items.reduce((s,c)=>`${s}${c}`,"")}get names(){var _a3;return(_a3=this._names)!==null&&_a3!==void 0?_a3:this._names=this._items.reduce((names,c)=>(c instanceof Name&&(names[c.str]=(names[c.str]||0)+1),names),{})}};exports._Code=_Code,exports.nil=new _Code("");function _(strs,...args){let code=[strs[0]],i=0;for(;i<args.length;)addCodeArg(code,args[i]),code.push(strs[++i]);return new _Code(code)}exports._=_;let plus=new _Code("+");function str(strs,...args){let expr=[safeStringify(strs[0])],i=0;for(;i<args.length;)expr.push(plus),addCodeArg(expr,args[i]),expr.push(plus,safeStringify(strs[++i]));return optimize(expr),new _Code(expr)}exports.str=str;function addCodeArg(code,arg){arg instanceof _Code?code.push(...arg._items):arg instanceof Name?code.push(arg):code.push(interpolate(arg))}exports.addCodeArg=addCodeArg;function optimize(expr){let i=1;for(;i<expr.length-1;){if(expr[i]===plus){let res=mergeExprItems(expr[i-1],expr[i+1]);if(res!==void 0){expr.splice(i-1,3,res);continue}expr[i++]="+"}i++}}function mergeExprItems(a,b){if(b==='""')return a;if(a==='""')return b;if(typeof a=="string")return b instanceof Name||a[a.length-1]!=='"'?void 0:typeof b!="string"?`${a.slice(0,-1)}${b}"`:b[0]==='"'?a.slice(0,-1)+b.slice(1):void 0;if(typeof b=="string"&&b[0]==='"'&&!(a instanceof Name))return`"${a}${b.slice(1)}`}function strConcat(c1,c2){return c2.emptyStr()?c1:c1.emptyStr()?c2:str`${c1}${c2}`}exports.strConcat=strConcat;function interpolate(x){return typeof x=="number"||typeof x=="boolean"||x===null?x:safeStringify(Array.isArray(x)?x.join(","):x)}function stringify(x){return new _Code(safeStringify(x))}exports.stringify=stringify;function safeStringify(x){return JSON.stringify(x).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}exports.safeStringify=safeStringify;function getProperty(key){return typeof key=="string"&&exports.IDENTIFIER.test(key)?new _Code(`.${key}`):_`[${key}]`}exports.getProperty=getProperty;function getEsmExportName(key){if(typeof key=="string"&&exports.IDENTIFIER.test(key))return new _Code(`${key}`);throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`)}exports.getEsmExportName=getEsmExportName;function regexpCode(rx){return new _Code(rx.toString())}exports.regexpCode=regexpCode})),require_scope=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.ValueScope=exports.ValueScopeName=exports.Scope=exports.varKinds=exports.UsedValueState=void 0;let code_1=require_code$1();var ValueError=class extends Error{constructor(name){super(`CodeGen: "code" for ${name} not defined`),this.value=name.value}},UsedValueState;(function(UsedValueState2){UsedValueState2[UsedValueState2.Started=0]="Started",UsedValueState2[UsedValueState2.Completed=1]="Completed"})(UsedValueState||(exports.UsedValueState=UsedValueState={})),exports.varKinds={const:new code_1.Name("const"),let:new code_1.Name("let"),var:new code_1.Name("var")};var Scope=class{constructor({prefixes,parent}={}){this._names={},this._prefixes=prefixes,this._parent=parent}toName(nameOrPrefix){return nameOrPrefix instanceof code_1.Name?nameOrPrefix:this.name(nameOrPrefix)}name(prefix){return new code_1.Name(this._newName(prefix))}_newName(prefix){let ng=this._names[prefix]||this._nameGroup(prefix);return`${prefix}${ng.index++}`}_nameGroup(prefix){var _a3,_b;if(!((_b=(_a3=this._parent)===null||_a3===void 0?void 0:_a3._prefixes)===null||_b===void 0)&&_b.has(prefix)||this._prefixes&&!this._prefixes.has(prefix))throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`);return this._names[prefix]={prefix,index:0}}};exports.Scope=Scope;var ValueScopeName=class extends code_1.Name{constructor(prefix,nameStr){super(nameStr),this.prefix=prefix}setValue(value,{property,itemIndex}){this.value=value,this.scopePath=(0,code_1._)`.${new code_1.Name(property)}[${itemIndex}]`}};exports.ValueScopeName=ValueScopeName;let line=(0,code_1._)`\n`;var ValueScope=class extends Scope{constructor(opts){super(opts),this._values={},this._scope=opts.scope,this.opts={...opts,_n:opts.lines?line:code_1.nil}}get(){return this._scope}name(prefix){return new ValueScopeName(prefix,this._newName(prefix))}value(nameOrPrefix,value){var _a3;if(value.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let name=this.toName(nameOrPrefix),{prefix}=name,valueKey=(_a3=value.key)!==null&&_a3!==void 0?_a3:value.ref,vs=this._values[prefix];if(vs){let _name=vs.get(valueKey);if(_name)return _name}else vs=this._values[prefix]=new Map;vs.set(valueKey,name);let s=this._scope[prefix]||(this._scope[prefix]=[]),itemIndex=s.length;return s[itemIndex]=value.ref,name.setValue(value,{property:prefix,itemIndex}),name}getValue(prefix,keyOrRef){let vs=this._values[prefix];if(vs)return vs.get(keyOrRef)}scopeRefs(scopeName,values=this._values){return this._reduceValues(values,name=>{if(name.scopePath===void 0)throw new Error(`CodeGen: name "${name}" has no value`);return(0,code_1._)`${scopeName}${name.scopePath}`})}scopeCode(values=this._values,usedValues,getCode){return this._reduceValues(values,name=>{if(name.value===void 0)throw new Error(`CodeGen: name "${name}" has no value`);return name.value.code},usedValues,getCode)}_reduceValues(values,valueCode,usedValues={},getCode){let code=code_1.nil;for(let prefix in values){let vs=values[prefix];if(!vs)continue;let nameSet=usedValues[prefix]=usedValues[prefix]||new Map;vs.forEach(name=>{if(nameSet.has(name))return;nameSet.set(name,UsedValueState.Started);let c=valueCode(name);if(c){let def=this.opts.es5?exports.varKinds.var:exports.varKinds.const;code=(0,code_1._)`${code}${def} ${name} = ${c};${this.opts._n}`}else if(c=getCode?.(name))code=(0,code_1._)`${code}${c}${this.opts._n}`;else throw new ValueError(name);nameSet.set(name,UsedValueState.Completed)})}return code}};exports.ValueScope=ValueScope})),require_codegen=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.or=exports.and=exports.not=exports.CodeGen=exports.operators=exports.varKinds=exports.ValueScopeName=exports.ValueScope=exports.Scope=exports.Name=exports.regexpCode=exports.stringify=exports.getProperty=exports.nil=exports.strConcat=exports.str=exports._=void 0;let code_1=require_code$1(),scope_1=require_scope();var code_2=require_code$1();Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return code_2._}}),Object.defineProperty(exports,"str",{enumerable:!0,get:function(){return code_2.str}}),Object.defineProperty(exports,"strConcat",{enumerable:!0,get:function(){return code_2.strConcat}}),Object.defineProperty(exports,"nil",{enumerable:!0,get:function(){return code_2.nil}}),Object.defineProperty(exports,"getProperty",{enumerable:!0,get:function(){return code_2.getProperty}}),Object.defineProperty(exports,"stringify",{enumerable:!0,get:function(){return code_2.stringify}}),Object.defineProperty(exports,"regexpCode",{enumerable:!0,get:function(){return code_2.regexpCode}}),Object.defineProperty(exports,"Name",{enumerable:!0,get:function(){return code_2.Name}});var scope_2=require_scope();Object.defineProperty(exports,"Scope",{enumerable:!0,get:function(){return scope_2.Scope}}),Object.defineProperty(exports,"ValueScope",{enumerable:!0,get:function(){return scope_2.ValueScope}}),Object.defineProperty(exports,"ValueScopeName",{enumerable:!0,get:function(){return scope_2.ValueScopeName}}),Object.defineProperty(exports,"varKinds",{enumerable:!0,get:function(){return scope_2.varKinds}}),exports.operators={GT:new code_1._Code(">"),GTE:new code_1._Code(">="),LT:new code_1._Code("<"),LTE:new code_1._Code("<="),EQ:new code_1._Code("==="),NEQ:new code_1._Code("!=="),NOT:new code_1._Code("!"),OR:new code_1._Code("||"),AND:new code_1._Code("&&"),ADD:new code_1._Code("+")};var Node5=class{optimizeNodes(){return this}optimizeNames(_names,_constants){return this}},Def=class extends Node5{constructor(varKind,name,rhs){super(),this.varKind=varKind,this.name=name,this.rhs=rhs}render({es5,_n}){let varKind=es5?scope_1.varKinds.var:this.varKind,rhs=this.rhs===void 0?"":` = ${this.rhs}`;return`${varKind} ${this.name}${rhs};`+_n}optimizeNames(names,constants){if(names[this.name.str])return this.rhs&&(this.rhs=optimizeExpr(this.rhs,names,constants)),this}get names(){return this.rhs instanceof code_1._CodeOrName?this.rhs.names:{}}},Assign=class extends Node5{constructor(lhs,rhs,sideEffects){super(),this.lhs=lhs,this.rhs=rhs,this.sideEffects=sideEffects}render({_n}){return`${this.lhs} = ${this.rhs};`+_n}optimizeNames(names,constants){if(!(this.lhs instanceof code_1.Name&&!names[this.lhs.str]&&!this.sideEffects))return this.rhs=optimizeExpr(this.rhs,names,constants),this}get names(){return addExprNames(this.lhs instanceof code_1.Name?{}:{...this.lhs.names},this.rhs)}},AssignOp=class extends Assign{constructor(lhs,op,rhs,sideEffects){super(lhs,rhs,sideEffects),this.op=op}render({_n}){return`${this.lhs} ${this.op}= ${this.rhs};`+_n}},Label=class extends Node5{constructor(label){super(),this.label=label,this.names={}}render({_n}){return`${this.label}:`+_n}},Break=class extends Node5{constructor(label){super(),this.label=label,this.names={}}render({_n}){return`break${this.label?` ${this.label}`:""};`+_n}},Throw=class extends Node5{constructor(error3){super(),this.error=error3}render({_n}){return`throw ${this.error};`+_n}get names(){return this.error.names}},AnyCode=class extends Node5{constructor(code){super(),this.code=code}render({_n}){return`${this.code};`+_n}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(names,constants){return this.code=optimizeExpr(this.code,names,constants),this}get names(){return this.code instanceof code_1._CodeOrName?this.code.names:{}}},ParentNode=class extends Node5{constructor(nodes=[]){super(),this.nodes=nodes}render(opts){return this.nodes.reduce((code,n)=>code+n.render(opts),"")}optimizeNodes(){let{nodes}=this,i=nodes.length;for(;i--;){let n=nodes[i].optimizeNodes();Array.isArray(n)?nodes.splice(i,1,...n):n?nodes[i]=n:nodes.splice(i,1)}return nodes.length>0?this:void 0}optimizeNames(names,constants){let{nodes}=this,i=nodes.length;for(;i--;){let n=nodes[i];n.optimizeNames(names,constants)||(subtractNames(names,n.names),nodes.splice(i,1))}return nodes.length>0?this:void 0}get names(){return this.nodes.reduce((names,n)=>addNames(names,n.names),{})}},BlockNode=class extends ParentNode{render(opts){return"{"+opts._n+super.render(opts)+"}"+opts._n}},Root=class extends ParentNode{},Else=class extends BlockNode{};Else.kind="else";var If=class If2 extends BlockNode{constructor(condition,nodes){super(nodes),this.condition=condition}render(opts){let code=`if(${this.condition})`+super.render(opts);return this.else&&(code+="else "+this.else.render(opts)),code}optimizeNodes(){super.optimizeNodes();let cond=this.condition;if(cond===!0)return this.nodes;let e=this.else;if(e){let ns=e.optimizeNodes();e=this.else=Array.isArray(ns)?new Else(ns):ns}if(e)return cond===!1?e instanceof If2?e:e.nodes:this.nodes.length?this:new If2(not(cond),e instanceof If2?[e]:e.nodes);if(!(cond===!1||!this.nodes.length))return this}optimizeNames(names,constants){var _a3;if(this.else=(_a3=this.else)===null||_a3===void 0?void 0:_a3.optimizeNames(names,constants),!!(super.optimizeNames(names,constants)||this.else))return this.condition=optimizeExpr(this.condition,names,constants),this}get names(){let names=super.names;return addExprNames(names,this.condition),this.else&&addNames(names,this.else.names),names}};If.kind="if";var For=class extends BlockNode{};For.kind="for";var ForLoop=class extends For{constructor(iteration){super(),this.iteration=iteration}render(opts){return`for(${this.iteration})`+super.render(opts)}optimizeNames(names,constants){if(super.optimizeNames(names,constants))return this.iteration=optimizeExpr(this.iteration,names,constants),this}get names(){return addNames(super.names,this.iteration.names)}},ForRange=class extends For{constructor(varKind,name,from,to){super(),this.varKind=varKind,this.name=name,this.from=from,this.to=to}render(opts){let varKind=opts.es5?scope_1.varKinds.var:this.varKind,{name,from,to}=this;return`for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)`+super.render(opts)}get names(){return addExprNames(addExprNames(super.names,this.from),this.to)}},ForIter=class extends For{constructor(loop,varKind,name,iterable){super(),this.loop=loop,this.varKind=varKind,this.name=name,this.iterable=iterable}render(opts){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(opts)}optimizeNames(names,constants){if(super.optimizeNames(names,constants))return this.iterable=optimizeExpr(this.iterable,names,constants),this}get names(){return addNames(super.names,this.iterable.names)}},Func=class extends BlockNode{constructor(name,args,async){super(),this.name=name,this.args=args,this.async=async}render(opts){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(opts)}};Func.kind="func";var Return=class extends ParentNode{render(opts){return"return "+super.render(opts)}};Return.kind="return";var Try=class extends BlockNode{render(opts){let code="try"+super.render(opts);return this.catch&&(code+=this.catch.render(opts)),this.finally&&(code+=this.finally.render(opts)),code}optimizeNodes(){var _a3,_b;return super.optimizeNodes(),(_a3=this.catch)===null||_a3===void 0||_a3.optimizeNodes(),(_b=this.finally)===null||_b===void 0||_b.optimizeNodes(),this}optimizeNames(names,constants){var _a3,_b;return super.optimizeNames(names,constants),(_a3=this.catch)===null||_a3===void 0||_a3.optimizeNames(names,constants),(_b=this.finally)===null||_b===void 0||_b.optimizeNames(names,constants),this}get names(){let names=super.names;return this.catch&&addNames(names,this.catch.names),this.finally&&addNames(names,this.finally.names),names}},Catch=class extends BlockNode{constructor(error3){super(),this.error=error3}render(opts){return`catch(${this.error})`+super.render(opts)}};Catch.kind="catch";var Finally=class extends BlockNode{render(opts){return"finally"+super.render(opts)}};Finally.kind="finally";var CodeGen=class{constructor(extScope,opts={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...opts,_n:opts.lines?`
65
65
  `:""},this._extScope=extScope,this._scope=new scope_1.Scope({parent:extScope}),this._nodes=[new Root]}toString(){return this._root.render(this.opts)}name(prefix){return this._scope.name(prefix)}scopeName(prefix){return this._extScope.name(prefix)}scopeValue(prefixOrName,value){let name=this._extScope.value(prefixOrName,value);return(this._values[name.prefix]||(this._values[name.prefix]=new Set)).add(name),name}getScopeValue(prefix,keyOrRef){return this._extScope.getValue(prefix,keyOrRef)}scopeRefs(scopeName){return this._extScope.scopeRefs(scopeName,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(varKind,nameOrPrefix,rhs,constant){let name=this._scope.toName(nameOrPrefix);return rhs!==void 0&&constant&&(this._constants[name.str]=rhs),this._leafNode(new Def(varKind,name,rhs)),name}const(nameOrPrefix,rhs,_constant){return this._def(scope_1.varKinds.const,nameOrPrefix,rhs,_constant)}let(nameOrPrefix,rhs,_constant){return this._def(scope_1.varKinds.let,nameOrPrefix,rhs,_constant)}var(nameOrPrefix,rhs,_constant){return this._def(scope_1.varKinds.var,nameOrPrefix,rhs,_constant)}assign(lhs,rhs,sideEffects){return this._leafNode(new Assign(lhs,rhs,sideEffects))}add(lhs,rhs){return this._leafNode(new AssignOp(lhs,exports.operators.ADD,rhs))}code(c){return typeof c=="function"?c():c!==code_1.nil&&this._leafNode(new AnyCode(c)),this}object(...keyValues){let code=["{"];for(let[key,value]of keyValues)code.length>1&&code.push(","),code.push(key),(key!==value||this.opts.es5)&&(code.push(":"),(0,code_1.addCodeArg)(code,value));return code.push("}"),new code_1._Code(code)}if(condition,thenBody,elseBody){if(this._blockNode(new If(condition)),thenBody&&elseBody)this.code(thenBody).else().code(elseBody).endIf();else if(thenBody)this.code(thenBody).endIf();else if(elseBody)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(condition){return this._elseNode(new If(condition))}else(){return this._elseNode(new Else)}endIf(){return this._endBlockNode(If,Else)}_for(node,forBody){return this._blockNode(node),forBody&&this.code(forBody).endFor(),this}for(iteration,forBody){return this._for(new ForLoop(iteration),forBody)}forRange(nameOrPrefix,from,to,forBody,varKind=this.opts.es5?scope_1.varKinds.var:scope_1.varKinds.let){let name=this._scope.toName(nameOrPrefix);return this._for(new ForRange(varKind,name,from,to),()=>forBody(name))}forOf(nameOrPrefix,iterable,forBody,varKind=scope_1.varKinds.const){let name=this._scope.toName(nameOrPrefix);if(this.opts.es5){let arr=iterable instanceof code_1.Name?iterable:this.var("_arr",iterable);return this.forRange("_i",0,(0,code_1._)`${arr}.length`,i=>{this.var(name,(0,code_1._)`${arr}[${i}]`),forBody(name)})}return this._for(new ForIter("of",varKind,name,iterable),()=>forBody(name))}forIn(nameOrPrefix,obj,forBody,varKind=this.opts.es5?scope_1.varKinds.var:scope_1.varKinds.const){if(this.opts.ownProperties)return this.forOf(nameOrPrefix,(0,code_1._)`Object.keys(${obj})`,forBody);let name=this._scope.toName(nameOrPrefix);return this._for(new ForIter("in",varKind,name,obj),()=>forBody(name))}endFor(){return this._endBlockNode(For)}label(label){return this._leafNode(new Label(label))}break(label){return this._leafNode(new Break(label))}return(value){let node=new Return;if(this._blockNode(node),this.code(value),node.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Return)}try(tryBody,catchCode,finallyCode){if(!catchCode&&!finallyCode)throw new Error('CodeGen: "try" without "catch" and "finally"');let node=new Try;if(this._blockNode(node),this.code(tryBody),catchCode){let error3=this.name("e");this._currNode=node.catch=new Catch(error3),catchCode(error3)}return finallyCode&&(this._currNode=node.finally=new Finally,this.code(finallyCode)),this._endBlockNode(Catch,Finally)}throw(error3){return this._leafNode(new Throw(error3))}block(body,nodeCount){return this._blockStarts.push(this._nodes.length),body&&this.code(body).endBlock(nodeCount),this}endBlock(nodeCount){let len=this._blockStarts.pop();if(len===void 0)throw new Error("CodeGen: not in self-balancing block");let toClose=this._nodes.length-len;if(toClose<0||nodeCount!==void 0&&toClose!==nodeCount)throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`);return this._nodes.length=len,this}func(name,args=code_1.nil,async,funcBody){return this._blockNode(new Func(name,args,async)),funcBody&&this.code(funcBody).endFunc(),this}endFunc(){return this._endBlockNode(Func)}optimize(n=1){for(;n-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(node){return this._currNode.nodes.push(node),this}_blockNode(node){this._currNode.nodes.push(node),this._nodes.push(node)}_endBlockNode(N1,N2){let n=this._currNode;if(n instanceof N1||N2&&n instanceof N2)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${N2?`${N1.kind}/${N2.kind}`:N1.kind}"`)}_elseNode(node){let n=this._currNode;if(!(n instanceof If))throw new Error('CodeGen: "else" without "if"');return this._currNode=n.else=node,this}get _root(){return this._nodes[0]}get _currNode(){let ns=this._nodes;return ns[ns.length-1]}set _currNode(node){let ns=this._nodes;ns[ns.length-1]=node}};exports.CodeGen=CodeGen;function addNames(names,from){for(let n in from)names[n]=(names[n]||0)+(from[n]||0);return names}function addExprNames(names,from){return from instanceof code_1._CodeOrName?addNames(names,from.names):names}function optimizeExpr(expr,names,constants){if(expr instanceof code_1.Name)return replaceName(expr);if(!canOptimize(expr))return expr;return new code_1._Code(expr._items.reduce((items,c)=>(c instanceof code_1.Name&&(c=replaceName(c)),c instanceof code_1._Code?items.push(...c._items):items.push(c),items),[]));function replaceName(n){let c=constants[n.str];return c===void 0||names[n.str]!==1?n:(delete names[n.str],c)}function canOptimize(e){return e instanceof code_1._Code&&e._items.some(c=>c instanceof code_1.Name&&names[c.str]===1&&constants[c.str]!==void 0)}}function subtractNames(names,from){for(let n in from)names[n]=(names[n]||0)-(from[n]||0)}function not(x){return typeof x=="boolean"||typeof x=="number"||x===null?!x:(0,code_1._)`!${par(x)}`}exports.not=not;let andCode=mappend(exports.operators.AND);function and(...args){return args.reduce(andCode)}exports.and=and;let orCode=mappend(exports.operators.OR);function or(...args){return args.reduce(orCode)}exports.or=or;function mappend(op){return(x,y)=>x===code_1.nil?y:y===code_1.nil?x:(0,code_1._)`${par(x)} ${op} ${par(y)}`}function par(x){return x instanceof code_1.Name?x:(0,code_1._)`(${x})`}})),require_util=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.checkStrictMode=exports.getErrorPath=exports.Type=exports.useFunc=exports.setEvaluated=exports.evaluatedPropsToName=exports.mergeEvaluated=exports.eachItem=exports.unescapeJsonPointer=exports.escapeJsonPointer=exports.escapeFragment=exports.unescapeFragment=exports.schemaRefOrVal=exports.schemaHasRulesButRef=exports.schemaHasRules=exports.checkUnknownRules=exports.alwaysValidSchema=exports.toHash=void 0;let codegen_1=require_codegen(),code_1=require_code$1();function toHash(arr){let hash={};for(let item of arr)hash[item]=!0;return hash}exports.toHash=toHash;function alwaysValidSchema(it,schema2){return typeof schema2=="boolean"?schema2:Object.keys(schema2).length===0?!0:(checkUnknownRules(it,schema2),!schemaHasRules(schema2,it.self.RULES.all))}exports.alwaysValidSchema=alwaysValidSchema;function checkUnknownRules(it,schema2=it.schema){let{opts,self}=it;if(!opts.strictSchema||typeof schema2=="boolean")return;let rules=self.RULES.keywords;for(let key in schema2)rules[key]||checkStrictMode(it,`unknown keyword: "${key}"`)}exports.checkUnknownRules=checkUnknownRules;function schemaHasRules(schema2,rules){if(typeof schema2=="boolean")return!schema2;for(let key in schema2)if(rules[key])return!0;return!1}exports.schemaHasRules=schemaHasRules;function schemaHasRulesButRef(schema2,RULES){if(typeof schema2=="boolean")return!schema2;for(let key in schema2)if(key!=="$ref"&&RULES.all[key])return!0;return!1}exports.schemaHasRulesButRef=schemaHasRulesButRef;function schemaRefOrVal({topSchemaRef,schemaPath},schema2,keyword,$data){if(!$data){if(typeof schema2=="number"||typeof schema2=="boolean")return schema2;if(typeof schema2=="string")return(0,codegen_1._)`${schema2}`}return(0,codegen_1._)`${topSchemaRef}${schemaPath}${(0,codegen_1.getProperty)(keyword)}`}exports.schemaRefOrVal=schemaRefOrVal;function unescapeFragment(str){return unescapeJsonPointer(decodeURIComponent(str))}exports.unescapeFragment=unescapeFragment;function escapeFragment(str){return encodeURIComponent(escapeJsonPointer(str))}exports.escapeFragment=escapeFragment;function escapeJsonPointer(str){return typeof str=="number"?`${str}`:str.replace(/~/g,"~0").replace(/\//g,"~1")}exports.escapeJsonPointer=escapeJsonPointer;function unescapeJsonPointer(str){return str.replace(/~1/g,"/").replace(/~0/g,"~")}exports.unescapeJsonPointer=unescapeJsonPointer;function eachItem(xs,f){if(Array.isArray(xs))for(let x of xs)f(x);else f(xs)}exports.eachItem=eachItem;function makeMergeEvaluated({mergeNames,mergeToName,mergeValues:mergeValues2,resultToName}){return(gen,from,to,toName)=>{let res=to===void 0?from:to instanceof codegen_1.Name?(from instanceof codegen_1.Name?mergeNames(gen,from,to):mergeToName(gen,from,to),to):from instanceof codegen_1.Name?(mergeToName(gen,to,from),from):mergeValues2(from,to);return toName===codegen_1.Name&&!(res instanceof codegen_1.Name)?resultToName(gen,res):res}}exports.mergeEvaluated={props:makeMergeEvaluated({mergeNames:(gen,from,to)=>gen.if((0,codegen_1._)`${to} !== true && ${from} !== undefined`,()=>{gen.if((0,codegen_1._)`${from} === true`,()=>gen.assign(to,!0),()=>gen.assign(to,(0,codegen_1._)`${to} || {}`).code((0,codegen_1._)`Object.assign(${to}, ${from})`))}),mergeToName:(gen,from,to)=>gen.if((0,codegen_1._)`${to} !== true`,()=>{from===!0?gen.assign(to,!0):(gen.assign(to,(0,codegen_1._)`${to} || {}`),setEvaluated(gen,to,from))}),mergeValues:(from,to)=>from===!0?!0:{...from,...to},resultToName:evaluatedPropsToName}),items:makeMergeEvaluated({mergeNames:(gen,from,to)=>gen.if((0,codegen_1._)`${to} !== true && ${from} !== undefined`,()=>gen.assign(to,(0,codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)),mergeToName:(gen,from,to)=>gen.if((0,codegen_1._)`${to} !== true`,()=>gen.assign(to,from===!0?!0:(0,codegen_1._)`${to} > ${from} ? ${to} : ${from}`)),mergeValues:(from,to)=>from===!0?!0:Math.max(from,to),resultToName:(gen,items)=>gen.var("items",items)})};function evaluatedPropsToName(gen,ps){if(ps===!0)return gen.var("props",!0);let props=gen.var("props",(0,codegen_1._)`{}`);return ps!==void 0&&setEvaluated(gen,props,ps),props}exports.evaluatedPropsToName=evaluatedPropsToName;function setEvaluated(gen,props,ps){Object.keys(ps).forEach(p=>gen.assign((0,codegen_1._)`${props}${(0,codegen_1.getProperty)(p)}`,!0))}exports.setEvaluated=setEvaluated;let snippets={};function useFunc(gen,f){return gen.scopeValue("func",{ref:f,code:snippets[f.code]||(snippets[f.code]=new code_1._Code(f.code))})}exports.useFunc=useFunc;var Type;(function(Type2){Type2[Type2.Num=0]="Num",Type2[Type2.Str=1]="Str"})(Type||(exports.Type=Type={}));function getErrorPath(dataProp,dataPropType,jsPropertySyntax){if(dataProp instanceof codegen_1.Name){let isNumber=dataPropType===Type.Num;return jsPropertySyntax?isNumber?(0,codegen_1._)`"[" + ${dataProp} + "]"`:(0,codegen_1._)`"['" + ${dataProp} + "']"`:isNumber?(0,codegen_1._)`"/" + ${dataProp}`:(0,codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return jsPropertySyntax?(0,codegen_1.getProperty)(dataProp).toString():"/"+escapeJsonPointer(dataProp)}exports.getErrorPath=getErrorPath;function checkStrictMode(it,msg,mode=it.opts.strictSchema){if(mode){if(msg=`strict mode: ${msg}`,mode===!0)throw new Error(msg);it.self.logger.warn(msg)}}exports.checkStrictMode=checkStrictMode})),require_names=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0});let codegen_1=require_codegen(),names={data:new codegen_1.Name("data"),valCxt:new codegen_1.Name("valCxt"),instancePath:new codegen_1.Name("instancePath"),parentData:new codegen_1.Name("parentData"),parentDataProperty:new codegen_1.Name("parentDataProperty"),rootData:new codegen_1.Name("rootData"),dynamicAnchors:new codegen_1.Name("dynamicAnchors"),vErrors:new codegen_1.Name("vErrors"),errors:new codegen_1.Name("errors"),this:new codegen_1.Name("this"),self:new codegen_1.Name("self"),scope:new codegen_1.Name("scope"),json:new codegen_1.Name("json"),jsonPos:new codegen_1.Name("jsonPos"),jsonLen:new codegen_1.Name("jsonLen"),jsonPart:new codegen_1.Name("jsonPart")};exports.default=names})),require_errors=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.extendErrors=exports.resetErrorsCount=exports.reportExtraError=exports.reportError=exports.keyword$DataError=exports.keywordError=void 0;let codegen_1=require_codegen(),util_1=require_util(),names_1=require_names();exports.keywordError={message:({keyword})=>(0,codegen_1.str)`must pass "${keyword}" keyword validation`},exports.keyword$DataError={message:({keyword,schemaType})=>schemaType?(0,codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)`:(0,codegen_1.str)`"${keyword}" keyword is invalid ($data)`};function reportError(cxt,error3=exports.keywordError,errorPaths,overrideAllErrors){let{it}=cxt,{gen,compositeRule,allErrors}=it,errObj=errorObjectCode(cxt,error3,errorPaths);overrideAllErrors??(compositeRule||allErrors)?addError(gen,errObj):returnErrors(it,(0,codegen_1._)`[${errObj}]`)}exports.reportError=reportError;function reportExtraError(cxt,error3=exports.keywordError,errorPaths){let{it}=cxt,{gen,compositeRule,allErrors}=it;addError(gen,errorObjectCode(cxt,error3,errorPaths)),compositeRule||allErrors||returnErrors(it,names_1.default.vErrors)}exports.reportExtraError=reportExtraError;function resetErrorsCount(gen,errsCount){gen.assign(names_1.default.errors,errsCount),gen.if((0,codegen_1._)`${names_1.default.vErrors} !== null`,()=>gen.if(errsCount,()=>gen.assign((0,codegen_1._)`${names_1.default.vErrors}.length`,errsCount),()=>gen.assign(names_1.default.vErrors,null)))}exports.resetErrorsCount=resetErrorsCount;function extendErrors({gen,keyword,schemaValue,data,errsCount,it}){if(errsCount===void 0)throw new Error("ajv implementation error");let err=gen.name("err");gen.forRange("i",errsCount,names_1.default.errors,i=>{gen.const(err,(0,codegen_1._)`${names_1.default.vErrors}[${i}]`),gen.if((0,codegen_1._)`${err}.instancePath === undefined`,()=>gen.assign((0,codegen_1._)`${err}.instancePath`,(0,codegen_1.strConcat)(names_1.default.instancePath,it.errorPath))),gen.assign((0,codegen_1._)`${err}.schemaPath`,(0,codegen_1.str)`${it.errSchemaPath}/${keyword}`),it.opts.verbose&&(gen.assign((0,codegen_1._)`${err}.schema`,schemaValue),gen.assign((0,codegen_1._)`${err}.data`,data))})}exports.extendErrors=extendErrors;function addError(gen,errObj){let err=gen.const("err",errObj);gen.if((0,codegen_1._)`${names_1.default.vErrors} === null`,()=>gen.assign(names_1.default.vErrors,(0,codegen_1._)`[${err}]`),(0,codegen_1._)`${names_1.default.vErrors}.push(${err})`),gen.code((0,codegen_1._)`${names_1.default.errors}++`)}function returnErrors(it,errs){let{gen,validateName,schemaEnv}=it;schemaEnv.$async?gen.throw((0,codegen_1._)`new ${it.ValidationError}(${errs})`):(gen.assign((0,codegen_1._)`${validateName}.errors`,errs),gen.return(!1))}let E={keyword:new codegen_1.Name("keyword"),schemaPath:new codegen_1.Name("schemaPath"),params:new codegen_1.Name("params"),propertyName:new codegen_1.Name("propertyName"),message:new codegen_1.Name("message"),schema:new codegen_1.Name("schema"),parentSchema:new codegen_1.Name("parentSchema")};function errorObjectCode(cxt,error3,errorPaths){let{createErrors}=cxt.it;return createErrors===!1?(0,codegen_1._)`{}`:errorObject(cxt,error3,errorPaths)}function errorObject(cxt,error3,errorPaths={}){let{gen,it}=cxt,keyValues=[errorInstancePath(it,errorPaths),errorSchemaPath(cxt,errorPaths)];return extraErrorProps(cxt,error3,keyValues),gen.object(...keyValues)}function errorInstancePath({errorPath},{instancePath}){let instPath=instancePath?(0,codegen_1.str)`${errorPath}${(0,util_1.getErrorPath)(instancePath,util_1.Type.Str)}`:errorPath;return[names_1.default.instancePath,(0,codegen_1.strConcat)(names_1.default.instancePath,instPath)]}function errorSchemaPath({keyword,it:{errSchemaPath}},{schemaPath,parentSchema}){let schPath=parentSchema?errSchemaPath:(0,codegen_1.str)`${errSchemaPath}/${keyword}`;return schemaPath&&(schPath=(0,codegen_1.str)`${schPath}${(0,util_1.getErrorPath)(schemaPath,util_1.Type.Str)}`),[E.schemaPath,schPath]}function extraErrorProps(cxt,{params,message},keyValues){let{keyword,data,schemaValue,it}=cxt,{opts,propertyName,topSchemaRef,schemaPath}=it;keyValues.push([E.keyword,keyword],[E.params,typeof params=="function"?params(cxt):params||(0,codegen_1._)`{}`]),opts.messages&&keyValues.push([E.message,typeof message=="function"?message(cxt):message]),opts.verbose&&keyValues.push([E.schema,schemaValue],[E.parentSchema,(0,codegen_1._)`${topSchemaRef}${schemaPath}`],[names_1.default.data,data]),propertyName&&keyValues.push([E.propertyName,propertyName])}})),require_boolSchema=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.boolOrEmptySchema=exports.topBoolOrEmptySchema=void 0;let errors_1=require_errors(),codegen_1=require_codegen(),names_1=require_names(),boolError={message:"boolean schema is false"};function topBoolOrEmptySchema(it){let{gen,schema:schema2,validateName}=it;schema2===!1?falseSchemaError(it,!1):typeof schema2=="object"&&schema2.$async===!0?gen.return(names_1.default.data):(gen.assign((0,codegen_1._)`${validateName}.errors`,null),gen.return(!0))}exports.topBoolOrEmptySchema=topBoolOrEmptySchema;function boolOrEmptySchema(it,valid){let{gen,schema:schema2}=it;schema2===!1?(gen.var(valid,!1),falseSchemaError(it)):gen.var(valid,!0)}exports.boolOrEmptySchema=boolOrEmptySchema;function falseSchemaError(it,overrideAllErrors){let{gen,data}=it,cxt={gen,keyword:"false schema",data,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it};(0,errors_1.reportError)(cxt,boolError,void 0,overrideAllErrors)}})),require_rules=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.getRules=exports.isJSONType=void 0;let jsonTypes=new Set(["string","number","integer","boolean","null","object","array"]);function isJSONType(x){return typeof x=="string"&&jsonTypes.has(x)}exports.isJSONType=isJSONType;function getRules(){let groups={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...groups,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},groups.number,groups.string,groups.array,groups.object],post:{rules:[]},all:{},keywords:{}}}exports.getRules=getRules})),require_applicability=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.shouldUseRule=exports.shouldUseGroup=exports.schemaHasRulesForType=void 0;function schemaHasRulesForType({schema:schema2,self},type){let group=self.RULES.types[type];return group&&group!==!0&&shouldUseGroup(schema2,group)}exports.schemaHasRulesForType=schemaHasRulesForType;function shouldUseGroup(schema2,group){return group.rules.some(rule=>shouldUseRule(schema2,rule))}exports.shouldUseGroup=shouldUseGroup;function shouldUseRule(schema2,rule){var _a3;return schema2[rule.keyword]!==void 0||((_a3=rule.definition.implements)===null||_a3===void 0?void 0:_a3.some(kwd=>schema2[kwd]!==void 0))}exports.shouldUseRule=shouldUseRule})),require_dataType=__commonJSMin((exports=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.reportTypeError=exports.checkDataTypes=exports.checkDataType=exports.coerceAndCheckDataType=exports.getJSONTypes=exports.getSchemaTypes=exports.DataType=void 0;let rules_1=require_rules(),applicability_1=require_applicability(),errors_1=require_errors(),codegen_1=require_codegen(),util_1=require_util();var DataType;(function(DataType2){DataType2[DataType2.Correct=0]="Correct",DataType2[DataType2.Wrong=1]="Wrong"})(DataType||(exports.DataType=DataType={}));function getSchemaTypes(schema2){let types=getJSONTypes(schema2.type);if(types.includes("null")){if(schema2.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!types.length&&schema2.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');schema2.nullable===!0&&types.push("null")}return types}exports.getSchemaTypes=getSchemaTypes;function getJSONTypes(ts){let types=Array.isArray(ts)?ts:ts?[ts]:[];if(types.every(rules_1.isJSONType))return types;throw new Error("type must be JSONType or JSONType[]: "+types.join(","))}exports.getJSONTypes=getJSONTypes;function coerceAndCheckDataType(it,types){let{gen,data,opts}=it,coerceTo=coerceToTypes(types,opts.coerceTypes),checkTypes=types.length>0&&!(coerceTo.length===0&&types.length===1&&(0,applicability_1.schemaHasRulesForType)(it,types[0]));if(checkTypes){let wrongType=checkDataTypes(types,data,opts.strictNumbers,DataType.Wrong);gen.if(wrongType,()=>{coerceTo.length?coerceData(it,types,coerceTo):reportTypeError(it)})}return checkTypes}exports.coerceAndCheckDataType=coerceAndCheckDataType;let COERCIBLE=new Set(["string","number","integer","boolean","null"]);function coerceToTypes(types,coerceTypes){return coerceTypes?types.filter(t=>COERCIBLE.has(t)||coerceTypes==="array"&&t==="array"):[]}function coerceData(it,types,coerceTo){let{gen,data,opts}=it,dataType=gen.let("dataType",(0,codegen_1._)`typeof ${data}`),coerced=gen.let("coerced",(0,codegen_1._)`undefined`);opts.coerceTypes==="array"&&gen.if((0,codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`,()=>gen.assign(data,(0,codegen_1._)`${data}[0]`).assign(dataType,(0,codegen_1._)`typeof ${data}`).if(checkDataTypes(types,data,opts.strictNumbers),()=>gen.assign(coerced,data))),gen.if((0,codegen_1._)`${coerced} !== undefined`);for(let t of coerceTo)(COERCIBLE.has(t)||t==="array"&&opts.coerceTypes==="array")&&coerceSpecificType(t);gen.else(),reportTypeError(it),gen.endIf(),gen.if((0,codegen_1._)`${coerced} !== undefined`,()=>{gen.assign(data,coerced),assignParentData(it,coerced)});function coerceSpecificType(t){switch(t){case"string":gen.elseIf((0,codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced,(0,codegen_1._)`"" + ${data}`).elseIf((0,codegen_1._)`${data} === null`).assign(coerced,(0,codegen_1._)`""`);return;case"number":gen.elseIf((0,codegen_1._)`${dataType} == "boolean" || ${data} === null
66
66
  || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced,(0,codegen_1._)`+${data}`);return;case"integer":gen.elseIf((0,codegen_1._)`${dataType} === "boolean" || ${data} === null
67
67
  || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced,(0,codegen_1._)`+${data}`);return;case"boolean":gen.elseIf((0,codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced,!1).elseIf((0,codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced,!0);return;case"null":gen.elseIf((0,codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`),gen.assign(coerced,null);return;case"array":gen.elseIf((0,codegen_1._)`${dataType} === "string" || ${dataType} === "number"
@@ -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 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 GET_MATCH_RESULT=Symbol();var bufferToFormData=(arrayBuffer,contentType)=>new Response(arrayBuffer,{headers:{"Content-Type":contentType.replace(/^[^;]+/,mediaType=>mediaType.toLowerCase())}}).formData();var MAX_NESTING_DEPTH=32,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(".",MAX_NESTING_DEPTH+2);keys.length>MAX_NESTING_DEPTH+1&&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)),new Response(body)[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=html22=>this.#newResponse(html22,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 METHOD_NAME_ALL="ALL",METHOD_NAME_ALL_LOWERCASE="all",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 _Hono{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#path="/";routes=[];constructor(options={}){[...METHODS,METHOD_NAME_ALL_LOWERCASE].forEach(method=>{this[method]=(args1,...args)=>(typeof args1=="string"?this.#path=args1:this.#addRoute(method,this.#path,args1),args.forEach(handler=>{this.#addRoute(method,this.#path,handler)}),this)}),this.on=(method,path,...handlers)=>{for(let p of[path].flat()){this.#path=p;for(let m of[method].flat())handlers.map(handler=>{this.#addRoute(m.toUpperCase(),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(METHOD_NAME_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 _Hono({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(METHOD_NAME_ALL,mergePath(path,"*"),handler),this}#addRoute(method,path,handler,baseRoutePath){method=method.toUpperCase(),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[METHOD_NAME_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="[^/]+",ONLY_WILDCARD_REG_EXP_STR=".*",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===ONLY_WILDCARD_REG_EXP_STR||a===TAIL_WILDCARD_REG_EXP_STR?b===TAIL_WILDCARD_REG_EXP_STR?-1:1:b===ONLY_WILDCARD_REG_EXP_STR||b===TAIL_WILDCARD_REG_EXP_STR?-1:a===LABEL_REG_EXP_STR?1:b===LABEL_REG_EXP_STR?-1:a.length===b.length?a<b?-1:1:b.length-a.length}var Node=class _Node{#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?["","",ONLY_WILDCARD_REG_EXP_STR]:["","",LABEL_REG_EXP_STR]:null:token==="/*"?["","",TAIL_WILDCARD_REG_EXP_STR]:token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),nextNode;if(pattern){let name=pattern[1],regexpStr=pattern[2]||LABEL_REG_EXP_STR;if(name&&pattern[2]&&(regexpStr===".*"||(regexpStr=regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(regexpStr))||regexpStr.length===1&&regExpMetaChars.has(regexpStr)))throw PATH_ERROR;if(nextNode=node.#children[regexpStr],!nextNode){if(regexpStr!==ONLY_WILDCARD_REG_EXP_STR&&regexpStr!==TAIL_WILDCARD_REG_EXP_STR){for(let k in node.#children)if((regexpStr.length>1||k.length>1)&&k!==ONLY_WILDCARD_REG_EXP_STR&&k!==TAIL_WILDCARD_REG_EXP_STR)throw PATH_ERROR}nextNode=node.#children[regexpStr]=new _Node}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!==ONLY_WILDCARD_REG_EXP_STR&&k!==TAIL_WILDCARD_REG_EXP_STR)throw PATH_ERROR;nextNode=node.#children[token]=new _Node}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==="*"?ONLY_WILDCARD_REG_EXP_STR:`/:${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={[METHOD_NAME_ALL]:createNullObject()},this.#routes={[METHOD_NAME_ALL]:createNullObject()},this.#tries={[METHOD_NAME_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[METHOD_NAME_ALL])handlerMap[method][p]=[...handlerMap[METHOD_NAME_ALL][p]],this.#insertPath(method,p)}}path==="/*"&&(path="*");let methods=method===METHOD_NAME_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[METHOD_NAME_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[METHOD_NAME_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,Node2=class _Node2{#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 _Node2;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[METHOD_NAME_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 Node2;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 Hono2=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()}});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&&regExpMetaChars.has(regexpStr)))throw PATH_ERROR;if(nextNode=node.#children[regexpStr],!nextNode){if(regexpStr!==".*"&&regexpStr!=="(?:|/.*)"){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(`
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
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(`
769
769
 
770
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"&&parameter.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.7.3-canary.2",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 object2(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=object2(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=object2(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=>object2(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("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}var VIEW_BOOTSTRAP_STYLE=`<style>
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.7.3",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 object2(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=object2(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=object2(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=>object2(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("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}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 Hono2,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 Hono2,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&&registerSkillsRuntime(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}}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&&registerSkillsRuntime(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};
808
808
  /*! Bundled license information:
809
809
 
810
810
  @modelcontextprotocol/server/dist/src-CX2iR2pK.mjs: