xmcp 1.2.0 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cloudflare.d.ts +1 -0
- package/dist/cloudflare.js +2 -2
- package/dist/config/index.d.ts +5 -5
- package/dist/config/schemas/experimental/index.d.ts +4 -4
- package/dist/config.js +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +13 -13
- package/dist/node.d.ts +55 -0
- package/dist/node.js +1 -0
- package/dist/runtime/adapter-express.js +13 -13
- package/dist/runtime/adapter-fastify.js +13 -13
- package/dist/runtime/adapter-nestjs.js +13 -13
- package/dist/runtime/adapter-nextjs.js +13 -13
- package/dist/runtime/adapter-tanstack-cloudflare.js +240 -0
- package/dist/runtime/adapter-tanstack.js +244 -0
- package/dist/runtime/cloudflare-worker.js +20 -20
- package/dist/runtime/http.js +19 -19
- package/dist/runtime/stdio.js +11 -11
- package/dist/runtime/utils/component-metadata.d.ts +9 -0
- package/dist/runtime/utils/content.d.ts +7 -0
- package/dist/runtime/utils/server.d.ts +2 -1
- package/dist/runtime/vercel.js +20 -20
- package/dist/types/component.d.ts +10 -0
- package/dist/types/declarations.d.ts +3 -0
- package/dist/types/prompt.d.ts +4 -1
- package/dist/types/resource.d.ts +5 -1
- package/dist/types/tool.d.ts +2 -1
- package/package.json +9 -2
package/dist/runtime/http.js
CHANGED
|
@@ -85,13 +85,13 @@ data:
|
|
|
85
85
|
]))`;continue}else if("$"===r[e]){i+=`($|(?=[\r
|
|
86
86
|
]))`;continue}}if(a.s&&"."===r[e]){i+=o?`${r[e]}\r
|
|
87
87
|
`:`[${r[e]}\r
|
|
88
|
-
]`;continue}i+=r[e],"\\"===r[e]?n=!0:o&&"]"===r[e]?o=!1:o||"["!==r[e]||(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function d5(e,t){if("openAi"===t.target&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),"openApi3"===t.target&&e.keyType?._def.typeName===k.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((a,r)=>({...a,[r]:d7(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",r]})??dL(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let a={type:"object",additionalProperties:d7(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return a;if(e.keyType?._def.typeName===k.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=d0(e.keyType._def,t);return{...a,propertyNames:i}}if(e.keyType?._def.typeName===k.ZodEnum)return{...a,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===k.ZodBranded&&e.keyType._def.type._def.typeName===k.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=dU(e.keyType._def,t);return{...a,propertyNames:i}}return a}let d6={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"},d3=(e,t)=>{let a=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,a)=>d7(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${a}`]})).filter(e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0));return a.length?{anyOf:a}:void 0};function d7(e,t,a=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,a);if(i!==uR)return i}if(r&&!a){let e=me(r,t);if(void 0!==e)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let n=((e,t,a)=>{switch(t){case k.ZodString:return d0(e,a);case k.ZodNumber:let r={type:"number"};if(!e.checks)return r;for(let t of e.checks)switch(t.kind){case"int":r.type="integer",dD(r,"type",t.message,a);break;case"min":"jsonSchema7"===a.target?t.inclusive?dF(r,"minimum",t.value,t.message,a):dF(r,"exclusiveMinimum",t.value,t.message,a):(t.inclusive||(r.exclusiveMinimum=!0),dF(r,"minimum",t.value,t.message,a));break;case"max":"jsonSchema7"===a.target?t.inclusive?dF(r,"maximum",t.value,t.message,a):dF(r,"exclusiveMaximum",t.value,t.message,a):(t.inclusive||(r.exclusiveMaximum=!0),dF(r,"maximum",t.value,t.message,a));break;case"multipleOf":dF(r,"multipleOf",t.value,t.message,a)}return r;case k.ZodObject:return function(e,t){let a="openAi"===t.target,r={type:"object",properties:{}},i=[],n=e.shape();for(let e in n){let o=n[e];if(void 0===o||void 0===o._def)continue;let s=function(e){try{return e.isOptional()}catch{return!0}}(o);s&&a&&("ZodOptional"===o._def.typeName&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=d7(o._def,{...t,currentPath:[...t.currentPath,"properties",e],propertyPath:[...t.currentPath,"properties",e]});void 0!==c&&(r.properties[e]=c,s||i.push(e))}i.length&&(r.required=i);let o=function(e,t){if("ZodNever"!==e.catchall._def.typeName)return d7(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return"strict"===t.removeAdditionalStrategy?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}(e,t);return void 0!==o&&(r.additionalProperties=o),r}(e,a);case k.ZodBigInt:let i={type:"integer",format:"int64"};if(!e.checks)return i;for(let t of e.checks)switch(t.kind){case"min":"jsonSchema7"===a.target?t.inclusive?dF(i,"minimum",t.value,t.message,a):dF(i,"exclusiveMinimum",t.value,t.message,a):(t.inclusive||(i.exclusiveMinimum=!0),dF(i,"minimum",t.value,t.message,a));break;case"max":"jsonSchema7"===a.target?t.inclusive?dF(i,"maximum",t.value,t.message,a):dF(i,"exclusiveMaximum",t.value,t.message,a):(t.inclusive||(i.exclusiveMaximum=!0),dF(i,"maximum",t.value,t.message,a));break;case"multipleOf":dF(i,"multipleOf",t.value,t.message,a)}return i;case k.ZodBoolean:return{type:"boolean"};case k.ZodDate:return function e(t,a,r){let i=r??a.dateStrategy;if(Array.isArray(i))return{anyOf:i.map((r,i)=>e(t,a,r))};switch(i){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":var n=t,o=a;let s={type:"integer",format:"unix-time"};if("openApi3"===o.target)return s;for(let e of n.checks)switch(e.kind){case"min":dF(s,"minimum",e.value,e.message,o);break;case"max":dF(s,"maximum",e.value,e.message,o)}return s}}(e,a);case k.ZodUndefined:return{not:dL(a)};case k.ZodNull:return"openApi3"===a.target?{enum:["null"],nullable:!0}:{type:"null"};case k.ZodArray:let n;return n={type:"array"},e.type?._def&&e.type?._def?.typeName!==k.ZodAny&&(n.items=d7(e.type._def,{...a,currentPath:[...a.currentPath,"items"]})),e.minLength&&dF(n,"minItems",e.minLength.value,e.minLength.message,a),e.maxLength&&dF(n,"maxItems",e.maxLength.value,e.maxLength.message,a),e.exactLength&&(dF(n,"minItems",e.exactLength.value,e.exactLength.message,a),dF(n,"maxItems",e.exactLength.value,e.exactLength.message,a)),n;case k.ZodUnion:case k.ZodDiscriminatedUnion:if("openApi3"===a.target)return d3(e,a);let o=e.options instanceof Map?Array.from(e.options.values()):e.options;if(o.every(e=>e._def.typeName in d6&&(!e._def.checks||!e._def.checks.length))){let e=o.reduce((e,t)=>{let a=d6[t._def.typeName];return a&&!e.includes(a)?[...e,a]:e},[]);return{type:e.length>1?e:e[0]}}if(o.every(e=>"ZodLiteral"===e._def.typeName&&!e.description)){let e=o.reduce((e,t)=>{let a=typeof t._def.value;switch(a){case"string":case"number":case"boolean":return[...e,a];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];default:return e}},[]);if(e.length===o.length){let t=e.filter((e,t,a)=>a.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:o.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(o.every(e=>"ZodEnum"===e._def.typeName))return{type:"string",enum:o.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return d3(e,a);case k.ZodIntersection:let s,c,l;return s=[d7(e.left._def,{...a,currentPath:[...a.currentPath,"allOf","0"]}),d7(e.right._def,{...a,currentPath:[...a.currentPath,"allOf","1"]})].filter(e=>!!e),c="jsonSchema2019-09"===a.target?{unevaluatedProperties:!1}:void 0,l=[],s.forEach(e=>{if((!("type"in e)||"string"!==e.type)&&"allOf"in e)l.push(...e.allOf),void 0===e.unevaluatedProperties&&(c=void 0);else{let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){let{additionalProperties:a,...r}=e;t=r}else c=void 0;l.push(t)}}),l.length?{allOf:l,...c}:void 0;case k.ZodTuple:return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((e,t)=>d7(e._def,{...a,currentPath:[...a.currentPath,"items",`${t}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[]),additionalItems:d7(e.rest._def,{...a,currentPath:[...a.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,t)=>d7(e._def,{...a,currentPath:[...a.currentPath,"items",`${t}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[])};case k.ZodRecord:return d5(e,a);case k.ZodLiteral:let p;return"bigint"!=(p=typeof e.value)&&"number"!==p&&"boolean"!==p&&"string"!==p?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===a.target?{type:"bigint"===p?"integer":p,enum:[e.value]}:{type:"bigint"===p?"integer":p,const:e.value};case k.ZodEnum:return{type:"string",enum:Array.from(e.values)};case k.ZodNativeEnum:let u,d,m;return u=e.values,{type:1===(m=Array.from(new Set((d=Object.keys(e.values).filter(e=>"number"!=typeof u[u[e]]).map(e=>u[e])).map(e=>typeof e)))).length?"string"===m[0]?"string":"number":["string","number"],enum:d};case k.ZodNullable:if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===a.target?{type:d6[e.innerType._def.typeName],nullable:!0}:{type:[d6[e.innerType._def.typeName],"null"]};if("openApi3"===a.target){let t=d7(e.innerType._def,{...a,currentPath:[...a.currentPath]});return t&&"$ref"in t?{allOf:[t],nullable:!0}:t&&{...t,nullable:!0}}let f=d7(e.innerType._def,{...a,currentPath:[...a.currentPath,"anyOf","0"]});return f&&{anyOf:[f,{type:"null"}]};case k.ZodOptional:if(a.currentPath.toString()===a.propertyPath?.toString())return d7(e.innerType._def,a);let h=d7(e.innerType._def,{...a,currentPath:[...a.currentPath,"anyOf","1"]});return h?{anyOf:[{not:dL(a)},h]}:dL(a);case k.ZodMap:if("record"===a.mapStrategy)return d5(e,a);return{type:"array",maxItems:125,items:{type:"array",items:[d7(e.keyType._def,{...a,currentPath:[...a.currentPath,"items","items","0"]})||dL(a),d7(e.valueType._def,{...a,currentPath:[...a.currentPath,"items","items","1"]})||dL(a)],minItems:2,maxItems:2}};case k.ZodSet:let v;return v={type:"array",uniqueItems:!0,items:d7(e.valueType._def,{...a,currentPath:[...a.currentPath,"items"]})},e.minSize&&dF(v,"minItems",e.minSize.value,e.minSize.message,a),e.maxSize&&dF(v,"maxItems",e.maxSize.value,e.maxSize.message,a),v;case k.ZodLazy:return()=>e.getter()._def;case k.ZodPromise:return d7(e.type._def,a);case k.ZodNaN:case k.ZodNever:return"openAi"===a.target?void 0:{not:dL({...a,currentPath:[...a.currentPath,"not"]})};case k.ZodEffects:return"input"===a.effectStrategy?d7(e.schema._def,a):dL(a);case k.ZodAny:case k.ZodUnknown:return dL(a);case k.ZodDefault:return{...d7(e.innerType._def,a),default:e.defaultValue()};case k.ZodBranded:return dU(e,a);case k.ZodReadonly:case k.ZodCatch:return d7(e.innerType._def,a);case k.ZodPipeline:if("input"===a.pipeStrategy)return d7(e.in._def,a);if("output"===a.pipeStrategy)return d7(e.out._def,a);let g=d7(e.in._def,{...a,currentPath:[...a.currentPath,"allOf","0"]}),y=d7(e.out._def,{...a,currentPath:[...a.currentPath,"allOf",g?"1":"0"]});return{allOf:[g,y].filter(e=>void 0!==e)};case k.ZodFunction:case k.ZodVoid:case k.ZodSymbol:default:return}})(e,e.typeName,t),o="function"==typeof n?d7(n(),t):n;if(o&&mt(e,t,o),t.postProcess){let a=t.postProcess(o,e,t);return i.jsonSchema=o,a}return i.jsonSchema=o,o}let me=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:dM(t.currentPath,e.path)};case"none":case"seen":if(e.path.length<t.currentPath.length&&e.path.every((e,a)=>t.currentPath[a]===e))return console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),dL(t);return"seen"===t.$refStrategy?dL(t):void 0}},mt=(e,t,a)=>(e.description&&(a.description=e.description,t.markdownDescription&&(a.markdownDescription=e.description)),a);function ma(e,t={}){let{strict:a=!1}=t,r=Object.entries(e),i=e=>({target:t})=>{let i={},n=[];for(let[a,o]of r)i[a]=function(e,t,a){let r=e["~standard"];if(r.jsonSchema)return r.jsonSchema[a]({target:t});if("zod"===e["~standard"].vendor&&!("_zod"in e)&&"_def"in e){let a=((e,t)=>{let a,r,i=(r=void 0!==(a="string"==typeof t?{...uC,name:t}:{...uC,...t}).name?[...a.basePath,a.definitionPath,a.name]:a.basePath,{...a,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(a.definitions).map(([e,t])=>[t._def,{def:t._def,path:[...a.basePath,a.definitionPath,e],jsonSchema:void 0}]))}),n="object"==typeof t&&t.definitions?Object.entries(t.definitions).reduce((e,[t,a])=>({...e,[t]:d7(a._def,{...i,currentPath:[...i.basePath,i.definitionPath,t]},!0)??dL(i)}),{}):void 0,o="string"==typeof t?t:t?.nameStrategy==="title"?void 0:t?.name,s=d7(e._def,void 0===o?i:{...i,currentPath:[...i.basePath,i.definitionPath,o]},!1)??dL(i),c="object"==typeof t&&void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==c&&(s.title=c),i.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[i.openAiAnyTypeName]||(n[i.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:"relative"===i.$refStrategy?"1":[...i.basePath,i.definitionPath,i.openAiAnyTypeName].join("/")}}));let l=void 0===o?n?{...s,[i.definitionPath]:n}:s:{$ref:[..."relative"===i.$refStrategy?[]:i.basePath,i.definitionPath,o].join("/"),[i.definitionPath]:{...n,[o]:s}};return"jsonSchema7"===i.target?l.$schema="http://json-schema.org/draft-07/schema#":("jsonSchema2019-09"===i.target||"openAi"===i.target)&&(l.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===i.target&&("anyOf"in l||"oneOf"in l||"allOf"in l||"type"in l&&Array.isArray(l.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),l})(e,{$refStrategy:"none",target:"openapi-3.0"===t?"openApi3":"jsonSchema7"});return delete a.$schema,a}if("zod"===r.vendor&&"_zod"in e)try{let t=a0(e);return delete t.$schema,t}catch(e){throw Error(`Failed to convert a zod schema to JSON Schema (zod v4 without "~standard.jsonSchema"). Upgrade to zod >= 4.2.0. Original error: ${e instanceof Error?e.message:String(e)}`)}throw Error(`Schema library "${r.vendor}" cannot be converted to JSON Schema. Use zod v3 (>= 3.25.76), zod >= 4.2.0, or a Standard Schema library implementing "~standard.jsonSchema".`)}(o,t,e),!function(e,t){if("function"!=typeof e.safeParse)return!1;try{let a=e.safeParse(void 0);return a.success&&("input"===t||void 0===a.data)}catch{return!1}}(o,e)&&n.push(a);let o={type:"object",properties:i};return n.length>0&&(o.required=n),a&&(o.additionalProperties=!1),o},n=async t=>{if("object"!=typeof t||null===t||Array.isArray(t))return{issues:[{message:"Expected an object."}]};let i={},n=[];for(let[e,a]of r){let r=await a["~standard"].validate(t[e]);if(r.issues)for(let t of r.issues)n.push({message:t.message,path:[e,...t.path??[]]});else(e in t||void 0!==r.value)&&(i[e]=r.value)}if(a)for(let a of Object.keys(t))a in e||n.push({message:`Unrecognized key: "${a}"`,path:[a]});return n.length>0?{issues:n}:{value:i}};return{shape:e,"~standard":{version:1,vendor:"xmcp",validate:n,jsonSchema:{input:i("input"),output:i("output")}}}}var mr=a(290);let mi=(e,t)=>{globalThis[e]=t},mn=e=>globalThis[e];function mo({name:e,fallback:t=!0}){let a=Symbol.for(`xmcp-context-${e}`),r=Symbol.for(`xmcp-context-${e}-fallback-store`);if(mn(a))return mn(a);let i=new mr.AsyncLocalStorage,n=globalThis[r]??{current:null};mi(r,n);let o={provider:(e,a)=>(t&&(n.current=e),i.run(e,a)),getContext:()=>{let a=i.getStore();if(a)return a;if(t&&n.current)return n.current;throw Error(`getContext() can only be used within the ${e} context.`)},setContext:a=>{let r=i.getStore()??(t?n.current:null);if(!r)throw Error(`setContext() can only be used within the ${e} context.`);Object.assign(r,a)}};return mi(a,o),o}let ms=mo({name:"http-request-context"}),mc=ms.setContext,ml=ms.getContext,mp=ms.provider,mu=mo({name:"client-info-context"});mu.setContext;let md=mu.getContext;mu.provider;let mm=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),mf=e=>{if(!mm(e)||"string"!=typeof e.name||"string"!=typeof e.version)return;let t={name:e.name,version:e.version};return"string"==typeof e.title&&(t.title=e.title),"string"==typeof e.websiteUrl&&(t.websiteUrl=e.websiteUrl),"string"==typeof e.description&&(t.description=e.description),t},mh=e=>{if(e&&"initialize"===e.method&&mm(e.params))return mf(e.params.clientInfo)},mv=(e,t)=>{let a=t.toLowerCase();for(let[t,r]of Object.entries(e)){if(t.toLowerCase()!==a)continue;let e=Array.isArray(r)?r[0]:r;if("string"!=typeof e)break;let i=e.trim();return i.length>0?i:void 0}},mg=new Set(["message","mode","requestedSchema"]),my=new Set(["elicitationId","message","mode","url"]),mb=new Set(["properties","required","type"]),mx=new Set(["default","description","format","maxLength","minLength","title","type"]),m_=new Set(["default","description","enum","enumNames","title","type"]),mw=new Set(["default","description","title","type"]),mS=new Set(["default","description","maximum","minimum","title","type"]),mk=new Set(["date","date-time","email","uri"]);async function m$(e,t,a){let r=function(e){let t=e.mode??"form";if("url"===t)return function(e){let t;mE(e,"Elicitation request must be a plain object."),mj(e,my,"URL elicitation"),mR(e.message,"URL elicitation requires a string message."),mC(e.elicitationId,"URL elicitation requires a non-empty elicitationId."),mC(e.url,"URL elicitation requires a non-empty URL.");try{t=new URL(e.url)}catch{throw Error("URL elicitation requires a valid http or https URL.")}if("http:"!==t.protocol&&"https:"!==t.protocol)throw Error("URL elicitation requires a valid http or https URL.")}(e),e;if("form"!==t)throw Error(`Unsupported elicitation mode "${String(e.mode)}". Expected "form" or "url".`);return function(e){mE(e,"Elicitation request must be a plain object."),mj(e,mg,"Form elicitation"),mR(e.message,"Form elicitation requires a string message.");let t=e.requestedSchema;if(mE(t,"Form elicitation requires a flat object schema."),mj(t,mb,"Form elicitation schema"),"object"!==t.type)throw Error('Form elicitation schema must use type "object".');for(let[e,a]of(mE(t.properties,"Form elicitation schema requires a properties object."),Object.entries(t.properties)))!function(e,t){if(mE(t,`Form elicitation field "${e}" must be a plain object.`),mT(t.title,`Form elicitation field "${e}" title must be a string.`),mT(t.description,`Form elicitation field "${e}" description must be a string.`),"string"===t.type&&"enum"in t){var a,r;if(mj(t,m_,`Form elicitation field "${e}"`),mO(t.enum,`Form elicitation field "${e}" enum values must be strings.`),a=t.enumNames,r=`Form elicitation field "${e}" enumNames must be strings.`,void 0!==a&&mO(a,r),void 0!==t.enumNames&&t.enumNames.length!==t.enum.length)throw Error(`Form elicitation field "${e}" enumNames length must match enum length.`);if(mT(t.default,`Form elicitation field "${e}" default must be a string.`),void 0!==t.default&&!t.enum.includes(t.default))throw Error(`Form elicitation field "${e}" default must be one of its enum values.`);return}if("string"===t.type&&!("enum"in t)){mj(t,mx,`Form elicitation field "${e}"`),mP(t.minLength,`Form elicitation field "${e}" minLength must be a number.`),mP(t.maxLength,`Form elicitation field "${e}" maxLength must be a number.`),mT(t.default,`Form elicitation field "${e}" default must be a string.`);let a=t.format;if(mT(a,`Form elicitation field "${e}" format must be a string.`),void 0!==a&&!mk.has(a))throw Error(`Form elicitation field "${e}" format must be one of: ${Array.from(mk).join(", ")}.`);return}if("boolean"===t.type){if(mj(t,mw,`Form elicitation field "${e}"`),void 0!==t.default&&"boolean"!=typeof t.default)throw Error(`Form elicitation field "${e}" default must be a boolean.`);return}if("number"===t.type||"integer"===t.type){mj(t,mS,`Form elicitation field "${e}"`),mP(t.minimum,`Form elicitation field "${e}" minimum must be a number.`),mP(t.maximum,`Form elicitation field "${e}" maximum must be a number.`),mP(t.default,`Form elicitation field "${e}" default must be a number.`);return}throw Error(`Form elicitation field "${e}" uses unsupported type "${String(t.type)}". Supported types are string, boolean, number, integer, and string enums.`)}(e,a);if(void 0!==t.required){if(!Array.isArray(t.required)||t.required.some(e=>"string"!=typeof e))throw Error("Form elicitation schema required fields must be a string array.");for(let e of t.required)if(!(e in t.properties))throw Error(`Form elicitation schema required field "${e}" is not defined in properties.`)}}(e),{...e,mode:"form"}}(t);try{let t=await e.mcpReq.elicitInput(r,a);return{...t,content:t.content??void 0}}catch(e){if(e instanceof sw&&e.code===s_.MethodNotSupportedByProtocolVersion)throw Error("extra.elicit() is not available on protocol revision 2026-07-28: server-initiated elicitation was replaced by multi round-trip requests. Return inputRequired({ ... }) from the tool handler instead (re-exported from xmcp); the client fulfils the embedded requests and retries the tool call.");throw e}}function mj(e,t,a){let r=Object.keys(e).filter(e=>!t.has(e));if(0!==r.length)throw Error(`${a} includes unsupported key(s): ${r.join(", ")}.`)}function mE(e,t){if("object"!=typeof e||null===e||Array.isArray(e))throw Error(t)}function mR(e,t){if("string"!=typeof e)throw Error(t)}function mC(e,t){if("string"!=typeof e||0===e.trim().length)throw Error(t)}function mT(e,t){if(void 0!==e&&"string"!=typeof e)throw Error(t)}function mP(e,t){if(void 0!==e&&"number"!=typeof e)throw Error(t)}function mO(e,t){if(!Array.isArray(e)||e.some(e=>"string"!=typeof e))throw Error(t)}let mA=new Set(["_meta","includeContext","maxTokens","messages","metadata","modelPreferences","stopSequences","systemPrompt","temperature"]),mI=new Set(["task","toolChoice","tools"]),mq=new Set(["text","image","audio"]);async function mN(e,t,a){let r=function(e){mz(e,"Sampling request must be a plain object.");let t=Object.keys(e),a=t.filter(e=>mI.has(e));if(a.length>0)throw Error(`Sampling request key(s) not supported by xmcp yet: ${a.join(", ")}.`);let r=t.filter(e=>!mA.has(e));if(r.length>0)throw Error(`Sampling request includes unsupported key(s): ${r.join(", ")}.`);if(!Array.isArray(e.messages)||0===e.messages.length)throw Error("Sampling requires at least one message.");for(let[t,a]of e.messages.entries())!function(e,t){if(mz(t,`Sampling message at index ${e} must be a plain object.`),"user"!==t.role&&"assistant"!==t.role)throw Error(`Sampling message at index ${e} requires role "user" or "assistant".`);let a=t.content;mz(a,`Sampling message at index ${e} requires a content object.`);let r=a.type;if("string"!=typeof r||!mq.has(r))throw Error(`Sampling message at index ${e} uses unsupported content type "${String(r)}". Supported types are text, image, and audio.`);if("text"===r&&"string"!=typeof a.text)throw Error(`Sampling message at index ${e} requires string text content.`);if(("image"===r||"audio"===r)&&("string"!=typeof a.data||"string"!=typeof a.mimeType))throw Error(`Sampling message at index ${e} requires base64 data and a mimeType.`)}(t,a);if("number"!=typeof e.maxTokens)throw Error("Sampling requires a numeric maxTokens.");return e}(t);try{return await e.mcpReq.requestSampling(r,a)}catch(e){if(e instanceof sw&&e.code===s_.MethodNotSupportedByProtocolVersion)throw Error("extra.sample() is not available on protocol revision 2026-07-28: server-initiated sampling was replaced by multi round-trip requests. Return inputRequired({ ... }) with inputRequired.createMessage(...) from the tool handler instead (re-exported from xmcp); the client fulfils the embedded requests and retries the tool call.");throw e}}function mz(e,t){if("object"!=typeof e||null===e||Array.isArray(e))throw Error(t)}let mM={text:e=>"string"!=typeof e.text?{valid:!1,error:'Text content must have a "text" property of type string'}:{valid:!0},image:e=>"string"!=typeof e.data?{valid:!1,error:'Image content must have a "data" property of type string (base64-encoded image)'}:"string"!=typeof e.mimeType?{valid:!1,error:'Image content must have a "mimeType" property of type string'}:{valid:!0},audio:e=>"string"!=typeof e.data?{valid:!1,error:'Audio content must have a "data" property of type string (base64-encoded audio)'}:"string"!=typeof e.mimeType?{valid:!1,error:'Audio content must have a "mimeType" property of type string'}:{valid:!0},resource_link:e=>"string"!=typeof e.name?{valid:!1,error:'Resource link content must have a "name" property of type string'}:"string"!=typeof e.uri?{valid:!1,error:'Resource link content must have a "uri" property of type string'}:void 0!==e.title&&"string"!=typeof e.title?{valid:!1,error:'Resource link "title" property must be a string if provided'}:void 0!==e.description&&"string"!=typeof e.description?{valid:!1,error:'Resource link "description" property must be a string if provided'}:void 0!==e.mimeType&&"string"!=typeof e.mimeType?{valid:!1,error:'Resource link "mimeType" property must be a string if provided'}:{valid:!0}};function mL(e){if(!e||"object"!=typeof e)return{valid:!1,error:"Content must be an object"};if("string"!=typeof e.type)return{valid:!1,error:'Content must have a "type" property of type string'};if(void 0!==e._meta&&(null===e._meta||"object"!=typeof e._meta))return{valid:!1,error:'Content "_meta" property must be an object if provided'};let t=mM[e.type];return t?t(e):{valid:!0}}function mD(e,t,a,r){if(null===e||"object"!=typeof e||Array.isArray(e))throw Error(`Tool "${a}" ${r}: expected a plain object.`);let i=new Set(Object.keys(t)),n=Object.keys(e).filter(e=>!i.has(e));if(n.length>0)throw Error(`Tool "${a}" ${r}: unrecognized key(s): ${n.join(", ")}`);for(let[i,n]of Object.entries(t))try{n.parse(e[i])}catch(e){throw Error(`Tool "${a}" ${r}: ${e?.message??`invalid field "${i}"`}`)}}function mF(e){return!!(e&&"object"==typeof e&&Object.keys(e).some(e=>e.startsWith("ui/")))}function mU(e){let t=e.mcpReq.envelope,a=mf(t?.[i$]);if(!a)try{let e,t=ml();a=t.clientInfo??(e=t.headers,mf({name:mv(e,"x-mcp-client-name"),version:mv(e,"x-mcp-client-version"),title:mv(e,"x-mcp-client-title"),websiteUrl:mv(e,"x-mcp-client-website-url"),description:mv(e,"x-mcp-client-description")}))}catch{}if(!a)try{a=md().clientInfo}catch{}return a}function mH(e){return e.endsWith(".tsx")}let mV=new class{add(e,t){this.resources.set(e,t)}getAll(){return this.resources}clear(){this.resources.clear()}has(e){return this.resources.has(e)}constructor(){!function(e,t,a){t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a}(this,"resources",new Map)}};function mZ(e){let t={};return!function e(a,r=""){if(a&&"object"==typeof a)for(let[i,n]of Object.entries(a)){let a=r?`${r}/${i}`:i;!n||"object"!=typeof n||Array.isArray(n)||n instanceof Date||n instanceof RegExp?t[a]=n:e(n,a)}}(e),t}let mB=["ui/resourceUri","resourceUri","visibility"],mJ=["prefersBorder","domain","csp","permissions","connectDomains","resourceDomains","frameDomains","baseUriDomains"],mG=mo({name:"request-context",fallback:!1});function mK(e){let t=[...e];return(e,a,r)=>(function(e,t,a){let r,i=new Map;if(e.http){let e=ml(),t=Object.fromEntries(Object.entries(e.headers).map(([e,t])=>[e,Array.isArray(t)?Object.freeze([...t]):t]));r=Object.freeze({id:e.id,headers:Object.freeze(t)})}return mG.provider(Object.freeze({clientInfo:t?Object.freeze({...t}):void 0,http:r,signal:e.mcpReq.signal,set(e,t){i.set(e,t)},get:e=>i.get(e),async progress(t,a){let r=e.mcpReq._meta?.progressToken;void 0!==r&&await e.mcpReq.notify({method:"notifications/progress",params:{progressToken:r,progress:t,...void 0===a?{}:{total:a}}})},log:(t,a)=>e.mcpReq.log(t,a)}),a)})(a,mU(a),async()=>{if(0===t.length)return r();let a=Object.freeze({...function(){try{return mG.getContext()}catch{throw Error("getRequestContext() can only be used while handling an MCP request.")}}(),method:e.method,params:Object.freeze({...e.params})}),i=-1,n=async e=>{if(e<=i)throw Error("MCP middleware next() can only be called once");i=e;let o=t[e];return o?o(a,()=>n(e+1)):r()};return n(0)})}let mW=new Set(["tools/list","prompts/get","prompts/list","resources/read","resources/list","resources/templates/list","completion/complete"]);function mY(e){return"object"==typeof e&&null!==e&&Object.entries(e).every(([e,t])=>"string"==typeof e&&"object"==typeof t&&null!==t&&"parse"in t&&"function"==typeof t.parse)}function mX(e){return(e.split("/").pop()||e).replace(/\.[^/.]+$/,"")}function mQ(e){let t=e.split("/").filter(e=>""!==e),a=t.findIndex(e=>e.match(/^\(.+\)$/));if(-1===a)return null;let r=t[t.length-1];if(r&&r.match(/^\[.+\]\.ts$/))return null;let i=t[a].slice(1,-1),n=t.slice(a+1),o=n[n.length-1];if(o&&o.includes(".")){let e=o.split(".")[0];"index"!==e?n[n.length-1]=e:n.pop()}let s=[],c=[],l=n.map(e=>{if(!e.match(/^\[.+\]$/))return c.push(e),e;{let t=e.slice(1,-1);return s.push(t),`{${t}}`}}),p=`${i}://${l.join("/")}`,u=s.length>0?"template":"direct";return{filePath:e,uriTemplate:p,scheme:i,parameters:s,pathSegments:c,type:u}}function m0(e){let t=e.replace(/\\/g,"/");if(!t)throw Error("Invalid tool path: path is empty");let a=t.replace(/\.[^/.]+$/,"").replace(/\//g,"_");return{normalizedPath:t,baseName:a}}function m1(e){return Error(`[xmcp] Invalid prompt file: ${e}
|
|
89
|
-
-> Default export must be a prompt handler function.`)}async function
|
|
90
|
-
-> ${a}`)});let i=a.length;e.warn(`[xmcp] ${i} prompt${1===i?"":"s"} skipped due to empty files or missing default exports`)}}();function
|
|
91
|
-
-> Default export must be a resource handler function.`)}async function
|
|
92
|
-
-> ${a}`)});let i=a.length;e.warn(`[xmcp] ${i} resource${1===i?"":"s"} skipped due to empty files or missing default exports`)}}();function
|
|
93
|
-
-> Default export must be a tool handler function.`)}async function
|
|
94
|
-
-> ${a}`)});let i=a.length;e.warn(`[xmcp] ${i} tool${1===i?"":"s"} skipped due to empty files or missing default exports`)}}(),
|
|
88
|
+
]`;continue}i+=r[e],"\\"===r[e]?n=!0:o&&"]"===r[e]?o=!1:o||"["!==r[e]||(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function d5(e,t){if("openAi"===t.target&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),"openApi3"===t.target&&e.keyType?._def.typeName===k.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((a,r)=>({...a,[r]:d7(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",r]})??dL(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let a={type:"object",additionalProperties:d7(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return a;if(e.keyType?._def.typeName===k.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=d0(e.keyType._def,t);return{...a,propertyNames:i}}if(e.keyType?._def.typeName===k.ZodEnum)return{...a,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===k.ZodBranded&&e.keyType._def.type._def.typeName===k.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=dU(e.keyType._def,t);return{...a,propertyNames:i}}return a}let d6={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"},d3=(e,t)=>{let a=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,a)=>d7(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${a}`]})).filter(e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0));return a.length?{anyOf:a}:void 0};function d7(e,t,a=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,a);if(i!==uR)return i}if(r&&!a){let e=me(r,t);if(void 0!==e)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let n=((e,t,a)=>{switch(t){case k.ZodString:return d0(e,a);case k.ZodNumber:let r={type:"number"};if(!e.checks)return r;for(let t of e.checks)switch(t.kind){case"int":r.type="integer",dD(r,"type",t.message,a);break;case"min":"jsonSchema7"===a.target?t.inclusive?dF(r,"minimum",t.value,t.message,a):dF(r,"exclusiveMinimum",t.value,t.message,a):(t.inclusive||(r.exclusiveMinimum=!0),dF(r,"minimum",t.value,t.message,a));break;case"max":"jsonSchema7"===a.target?t.inclusive?dF(r,"maximum",t.value,t.message,a):dF(r,"exclusiveMaximum",t.value,t.message,a):(t.inclusive||(r.exclusiveMaximum=!0),dF(r,"maximum",t.value,t.message,a));break;case"multipleOf":dF(r,"multipleOf",t.value,t.message,a)}return r;case k.ZodObject:return function(e,t){let a="openAi"===t.target,r={type:"object",properties:{}},i=[],n=e.shape();for(let e in n){let o=n[e];if(void 0===o||void 0===o._def)continue;let s=function(e){try{return e.isOptional()}catch{return!0}}(o);s&&a&&("ZodOptional"===o._def.typeName&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=d7(o._def,{...t,currentPath:[...t.currentPath,"properties",e],propertyPath:[...t.currentPath,"properties",e]});void 0!==c&&(r.properties[e]=c,s||i.push(e))}i.length&&(r.required=i);let o=function(e,t){if("ZodNever"!==e.catchall._def.typeName)return d7(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return"strict"===t.removeAdditionalStrategy?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}(e,t);return void 0!==o&&(r.additionalProperties=o),r}(e,a);case k.ZodBigInt:let i={type:"integer",format:"int64"};if(!e.checks)return i;for(let t of e.checks)switch(t.kind){case"min":"jsonSchema7"===a.target?t.inclusive?dF(i,"minimum",t.value,t.message,a):dF(i,"exclusiveMinimum",t.value,t.message,a):(t.inclusive||(i.exclusiveMinimum=!0),dF(i,"minimum",t.value,t.message,a));break;case"max":"jsonSchema7"===a.target?t.inclusive?dF(i,"maximum",t.value,t.message,a):dF(i,"exclusiveMaximum",t.value,t.message,a):(t.inclusive||(i.exclusiveMaximum=!0),dF(i,"maximum",t.value,t.message,a));break;case"multipleOf":dF(i,"multipleOf",t.value,t.message,a)}return i;case k.ZodBoolean:return{type:"boolean"};case k.ZodDate:return function e(t,a,r){let i=r??a.dateStrategy;if(Array.isArray(i))return{anyOf:i.map((r,i)=>e(t,a,r))};switch(i){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":var n=t,o=a;let s={type:"integer",format:"unix-time"};if("openApi3"===o.target)return s;for(let e of n.checks)switch(e.kind){case"min":dF(s,"minimum",e.value,e.message,o);break;case"max":dF(s,"maximum",e.value,e.message,o)}return s}}(e,a);case k.ZodUndefined:return{not:dL(a)};case k.ZodNull:return"openApi3"===a.target?{enum:["null"],nullable:!0}:{type:"null"};case k.ZodArray:let n;return n={type:"array"},e.type?._def&&e.type?._def?.typeName!==k.ZodAny&&(n.items=d7(e.type._def,{...a,currentPath:[...a.currentPath,"items"]})),e.minLength&&dF(n,"minItems",e.minLength.value,e.minLength.message,a),e.maxLength&&dF(n,"maxItems",e.maxLength.value,e.maxLength.message,a),e.exactLength&&(dF(n,"minItems",e.exactLength.value,e.exactLength.message,a),dF(n,"maxItems",e.exactLength.value,e.exactLength.message,a)),n;case k.ZodUnion:case k.ZodDiscriminatedUnion:if("openApi3"===a.target)return d3(e,a);let o=e.options instanceof Map?Array.from(e.options.values()):e.options;if(o.every(e=>e._def.typeName in d6&&(!e._def.checks||!e._def.checks.length))){let e=o.reduce((e,t)=>{let a=d6[t._def.typeName];return a&&!e.includes(a)?[...e,a]:e},[]);return{type:e.length>1?e:e[0]}}if(o.every(e=>"ZodLiteral"===e._def.typeName&&!e.description)){let e=o.reduce((e,t)=>{let a=typeof t._def.value;switch(a){case"string":case"number":case"boolean":return[...e,a];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];default:return e}},[]);if(e.length===o.length){let t=e.filter((e,t,a)=>a.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:o.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(o.every(e=>"ZodEnum"===e._def.typeName))return{type:"string",enum:o.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return d3(e,a);case k.ZodIntersection:let s,c,l;return s=[d7(e.left._def,{...a,currentPath:[...a.currentPath,"allOf","0"]}),d7(e.right._def,{...a,currentPath:[...a.currentPath,"allOf","1"]})].filter(e=>!!e),c="jsonSchema2019-09"===a.target?{unevaluatedProperties:!1}:void 0,l=[],s.forEach(e=>{if((!("type"in e)||"string"!==e.type)&&"allOf"in e)l.push(...e.allOf),void 0===e.unevaluatedProperties&&(c=void 0);else{let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){let{additionalProperties:a,...r}=e;t=r}else c=void 0;l.push(t)}}),l.length?{allOf:l,...c}:void 0;case k.ZodTuple:return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((e,t)=>d7(e._def,{...a,currentPath:[...a.currentPath,"items",`${t}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[]),additionalItems:d7(e.rest._def,{...a,currentPath:[...a.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,t)=>d7(e._def,{...a,currentPath:[...a.currentPath,"items",`${t}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[])};case k.ZodRecord:return d5(e,a);case k.ZodLiteral:let p;return"bigint"!=(p=typeof e.value)&&"number"!==p&&"boolean"!==p&&"string"!==p?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===a.target?{type:"bigint"===p?"integer":p,enum:[e.value]}:{type:"bigint"===p?"integer":p,const:e.value};case k.ZodEnum:return{type:"string",enum:Array.from(e.values)};case k.ZodNativeEnum:let u,d,m;return u=e.values,{type:1===(m=Array.from(new Set((d=Object.keys(e.values).filter(e=>"number"!=typeof u[u[e]]).map(e=>u[e])).map(e=>typeof e)))).length?"string"===m[0]?"string":"number":["string","number"],enum:d};case k.ZodNullable:if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===a.target?{type:d6[e.innerType._def.typeName],nullable:!0}:{type:[d6[e.innerType._def.typeName],"null"]};if("openApi3"===a.target){let t=d7(e.innerType._def,{...a,currentPath:[...a.currentPath]});return t&&"$ref"in t?{allOf:[t],nullable:!0}:t&&{...t,nullable:!0}}let f=d7(e.innerType._def,{...a,currentPath:[...a.currentPath,"anyOf","0"]});return f&&{anyOf:[f,{type:"null"}]};case k.ZodOptional:if(a.currentPath.toString()===a.propertyPath?.toString())return d7(e.innerType._def,a);let h=d7(e.innerType._def,{...a,currentPath:[...a.currentPath,"anyOf","1"]});return h?{anyOf:[{not:dL(a)},h]}:dL(a);case k.ZodMap:if("record"===a.mapStrategy)return d5(e,a);return{type:"array",maxItems:125,items:{type:"array",items:[d7(e.keyType._def,{...a,currentPath:[...a.currentPath,"items","items","0"]})||dL(a),d7(e.valueType._def,{...a,currentPath:[...a.currentPath,"items","items","1"]})||dL(a)],minItems:2,maxItems:2}};case k.ZodSet:let v;return v={type:"array",uniqueItems:!0,items:d7(e.valueType._def,{...a,currentPath:[...a.currentPath,"items"]})},e.minSize&&dF(v,"minItems",e.minSize.value,e.minSize.message,a),e.maxSize&&dF(v,"maxItems",e.maxSize.value,e.maxSize.message,a),v;case k.ZodLazy:return()=>e.getter()._def;case k.ZodPromise:return d7(e.type._def,a);case k.ZodNaN:case k.ZodNever:return"openAi"===a.target?void 0:{not:dL({...a,currentPath:[...a.currentPath,"not"]})};case k.ZodEffects:return"input"===a.effectStrategy?d7(e.schema._def,a):dL(a);case k.ZodAny:case k.ZodUnknown:return dL(a);case k.ZodDefault:return{...d7(e.innerType._def,a),default:e.defaultValue()};case k.ZodBranded:return dU(e,a);case k.ZodReadonly:case k.ZodCatch:return d7(e.innerType._def,a);case k.ZodPipeline:if("input"===a.pipeStrategy)return d7(e.in._def,a);if("output"===a.pipeStrategy)return d7(e.out._def,a);let g=d7(e.in._def,{...a,currentPath:[...a.currentPath,"allOf","0"]}),y=d7(e.out._def,{...a,currentPath:[...a.currentPath,"allOf",g?"1":"0"]});return{allOf:[g,y].filter(e=>void 0!==e)};case k.ZodFunction:case k.ZodVoid:case k.ZodSymbol:default:return}})(e,e.typeName,t),o="function"==typeof n?d7(n(),t):n;if(o&&mt(e,t,o),t.postProcess){let a=t.postProcess(o,e,t);return i.jsonSchema=o,a}return i.jsonSchema=o,o}let me=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:dM(t.currentPath,e.path)};case"none":case"seen":if(e.path.length<t.currentPath.length&&e.path.every((e,a)=>t.currentPath[a]===e))return console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),dL(t);return"seen"===t.$refStrategy?dL(t):void 0}},mt=(e,t,a)=>(e.description&&(a.description=e.description,t.markdownDescription&&(a.markdownDescription=e.description)),a);function ma(e,t={}){let{strict:a=!1}=t,r=Object.entries(e),i=e=>({target:t})=>{let i={},n=[];for(let[a,o]of r)i[a]=function(e,t,a){let r=e["~standard"];if(r.jsonSchema)return r.jsonSchema[a]({target:t});if("zod"===e["~standard"].vendor&&!("_zod"in e)&&"_def"in e){let a=((e,t)=>{let a,r,i=(r=void 0!==(a="string"==typeof t?{...uC,name:t}:{...uC,...t}).name?[...a.basePath,a.definitionPath,a.name]:a.basePath,{...a,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(a.definitions).map(([e,t])=>[t._def,{def:t._def,path:[...a.basePath,a.definitionPath,e],jsonSchema:void 0}]))}),n="object"==typeof t&&t.definitions?Object.entries(t.definitions).reduce((e,[t,a])=>({...e,[t]:d7(a._def,{...i,currentPath:[...i.basePath,i.definitionPath,t]},!0)??dL(i)}),{}):void 0,o="string"==typeof t?t:t?.nameStrategy==="title"?void 0:t?.name,s=d7(e._def,void 0===o?i:{...i,currentPath:[...i.basePath,i.definitionPath,o]},!1)??dL(i),c="object"==typeof t&&void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==c&&(s.title=c),i.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[i.openAiAnyTypeName]||(n[i.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:"relative"===i.$refStrategy?"1":[...i.basePath,i.definitionPath,i.openAiAnyTypeName].join("/")}}));let l=void 0===o?n?{...s,[i.definitionPath]:n}:s:{$ref:[..."relative"===i.$refStrategy?[]:i.basePath,i.definitionPath,o].join("/"),[i.definitionPath]:{...n,[o]:s}};return"jsonSchema7"===i.target?l.$schema="http://json-schema.org/draft-07/schema#":("jsonSchema2019-09"===i.target||"openAi"===i.target)&&(l.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===i.target&&("anyOf"in l||"oneOf"in l||"allOf"in l||"type"in l&&Array.isArray(l.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),l})(e,{$refStrategy:"none",target:"openapi-3.0"===t?"openApi3":"jsonSchema7"});return delete a.$schema,a}if("zod"===r.vendor&&"_zod"in e)try{let t=a0(e);return delete t.$schema,t}catch(e){throw Error(`Failed to convert a zod schema to JSON Schema (zod v4 without "~standard.jsonSchema"). Upgrade to zod >= 4.2.0. Original error: ${e instanceof Error?e.message:String(e)}`)}throw Error(`Schema library "${r.vendor}" cannot be converted to JSON Schema. Use zod v3 (>= 3.25.76), zod >= 4.2.0, or a Standard Schema library implementing "~standard.jsonSchema".`)}(o,t,e),!function(e,t){if("function"!=typeof e.safeParse)return!1;try{let a=e.safeParse(void 0);return a.success&&("input"===t||void 0===a.data)}catch{return!1}}(o,e)&&n.push(a);let o={type:"object",properties:i};return n.length>0&&(o.required=n),a&&(o.additionalProperties=!1),o},n=async t=>{if("object"!=typeof t||null===t||Array.isArray(t))return{issues:[{message:"Expected an object."}]};let i={},n=[];for(let[e,a]of r){let r=await a["~standard"].validate(t[e]);if(r.issues)for(let t of r.issues)n.push({message:t.message,path:[e,...t.path??[]]});else(e in t||void 0!==r.value)&&(i[e]=r.value)}if(a)for(let a of Object.keys(t))a in e||n.push({message:`Unrecognized key: "${a}"`,path:[a]});return n.length>0?{issues:n}:{value:i}};return{shape:e,"~standard":{version:1,vendor:"xmcp",validate:n,jsonSchema:{input:i("input"),output:i("output")}}}}var mr=a(290);let mi=(e,t)=>{globalThis[e]=t},mn=e=>globalThis[e];function mo({name:e,fallback:t=!0}){let a=Symbol.for(`xmcp-context-${e}`),r=Symbol.for(`xmcp-context-${e}-fallback-store`);if(mn(a))return mn(a);let i=new mr.AsyncLocalStorage,n=globalThis[r]??{current:null};mi(r,n);let o={provider:(e,a)=>(t&&(n.current=e),i.run(e,a)),getContext:()=>{let a=i.getStore();if(a)return a;if(t&&n.current)return n.current;throw Error(`getContext() can only be used within the ${e} context.`)},setContext:a=>{let r=i.getStore()??(t?n.current:null);if(!r)throw Error(`setContext() can only be used within the ${e} context.`);Object.assign(r,a)}};return mi(a,o),o}let ms=mo({name:"http-request-context"}),mc=ms.setContext,ml=ms.getContext,mp=ms.provider,mu=mo({name:"client-info-context"});mu.setContext;let md=mu.getContext;mu.provider;let mm=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),mf=e=>{if(!mm(e)||"string"!=typeof e.name||"string"!=typeof e.version)return;let t={name:e.name,version:e.version};return"string"==typeof e.title&&(t.title=e.title),"string"==typeof e.websiteUrl&&(t.websiteUrl=e.websiteUrl),"string"==typeof e.description&&(t.description=e.description),t},mh=e=>{if(e&&"initialize"===e.method&&mm(e.params))return mf(e.params.clientInfo)},mv=(e,t)=>{let a=t.toLowerCase();for(let[t,r]of Object.entries(e)){if(t.toLowerCase()!==a)continue;let e=Array.isArray(r)?r[0]:r;if("string"!=typeof e)break;let i=e.trim();return i.length>0?i:void 0}},mg=new Set(["message","mode","requestedSchema"]),my=new Set(["elicitationId","message","mode","url"]),mb=new Set(["properties","required","type"]),mx=new Set(["default","description","format","maxLength","minLength","title","type"]),m_=new Set(["default","description","enum","enumNames","title","type"]),mw=new Set(["default","description","title","type"]),mS=new Set(["default","description","maximum","minimum","title","type"]),mk=new Set(["date","date-time","email","uri"]);async function m$(e,t,a){let r=function(e){let t=e.mode??"form";if("url"===t)return function(e){let t;mE(e,"Elicitation request must be a plain object."),mj(e,my,"URL elicitation"),mR(e.message,"URL elicitation requires a string message."),mC(e.elicitationId,"URL elicitation requires a non-empty elicitationId."),mC(e.url,"URL elicitation requires a non-empty URL.");try{t=new URL(e.url)}catch{throw Error("URL elicitation requires a valid http or https URL.")}if("http:"!==t.protocol&&"https:"!==t.protocol)throw Error("URL elicitation requires a valid http or https URL.")}(e),e;if("form"!==t)throw Error(`Unsupported elicitation mode "${String(e.mode)}". Expected "form" or "url".`);return function(e){mE(e,"Elicitation request must be a plain object."),mj(e,mg,"Form elicitation"),mR(e.message,"Form elicitation requires a string message.");let t=e.requestedSchema;if(mE(t,"Form elicitation requires a flat object schema."),mj(t,mb,"Form elicitation schema"),"object"!==t.type)throw Error('Form elicitation schema must use type "object".');for(let[e,a]of(mE(t.properties,"Form elicitation schema requires a properties object."),Object.entries(t.properties)))!function(e,t){if(mE(t,`Form elicitation field "${e}" must be a plain object.`),mT(t.title,`Form elicitation field "${e}" title must be a string.`),mT(t.description,`Form elicitation field "${e}" description must be a string.`),"string"===t.type&&"enum"in t){var a,r;if(mj(t,m_,`Form elicitation field "${e}"`),mO(t.enum,`Form elicitation field "${e}" enum values must be strings.`),a=t.enumNames,r=`Form elicitation field "${e}" enumNames must be strings.`,void 0!==a&&mO(a,r),void 0!==t.enumNames&&t.enumNames.length!==t.enum.length)throw Error(`Form elicitation field "${e}" enumNames length must match enum length.`);if(mT(t.default,`Form elicitation field "${e}" default must be a string.`),void 0!==t.default&&!t.enum.includes(t.default))throw Error(`Form elicitation field "${e}" default must be one of its enum values.`);return}if("string"===t.type&&!("enum"in t)){mj(t,mx,`Form elicitation field "${e}"`),mP(t.minLength,`Form elicitation field "${e}" minLength must be a number.`),mP(t.maxLength,`Form elicitation field "${e}" maxLength must be a number.`),mT(t.default,`Form elicitation field "${e}" default must be a string.`);let a=t.format;if(mT(a,`Form elicitation field "${e}" format must be a string.`),void 0!==a&&!mk.has(a))throw Error(`Form elicitation field "${e}" format must be one of: ${Array.from(mk).join(", ")}.`);return}if("boolean"===t.type){if(mj(t,mw,`Form elicitation field "${e}"`),void 0!==t.default&&"boolean"!=typeof t.default)throw Error(`Form elicitation field "${e}" default must be a boolean.`);return}if("number"===t.type||"integer"===t.type){mj(t,mS,`Form elicitation field "${e}"`),mP(t.minimum,`Form elicitation field "${e}" minimum must be a number.`),mP(t.maximum,`Form elicitation field "${e}" maximum must be a number.`),mP(t.default,`Form elicitation field "${e}" default must be a number.`);return}throw Error(`Form elicitation field "${e}" uses unsupported type "${String(t.type)}". Supported types are string, boolean, number, integer, and string enums.`)}(e,a);if(void 0!==t.required){if(!Array.isArray(t.required)||t.required.some(e=>"string"!=typeof e))throw Error("Form elicitation schema required fields must be a string array.");for(let e of t.required)if(!(e in t.properties))throw Error(`Form elicitation schema required field "${e}" is not defined in properties.`)}}(e),{...e,mode:"form"}}(t);try{let t=await e.mcpReq.elicitInput(r,a);return{...t,content:t.content??void 0}}catch(e){if(e instanceof sw&&e.code===s_.MethodNotSupportedByProtocolVersion)throw Error("extra.elicit() is not available on protocol revision 2026-07-28: server-initiated elicitation was replaced by multi round-trip requests. Return inputRequired({ ... }) from the tool handler instead (re-exported from xmcp); the client fulfils the embedded requests and retries the tool call.");throw e}}function mj(e,t,a){let r=Object.keys(e).filter(e=>!t.has(e));if(0!==r.length)throw Error(`${a} includes unsupported key(s): ${r.join(", ")}.`)}function mE(e,t){if("object"!=typeof e||null===e||Array.isArray(e))throw Error(t)}function mR(e,t){if("string"!=typeof e)throw Error(t)}function mC(e,t){if("string"!=typeof e||0===e.trim().length)throw Error(t)}function mT(e,t){if(void 0!==e&&"string"!=typeof e)throw Error(t)}function mP(e,t){if(void 0!==e&&"number"!=typeof e)throw Error(t)}function mO(e,t){if(!Array.isArray(e)||e.some(e=>"string"!=typeof e))throw Error(t)}let mA=new Set(["_meta","includeContext","maxTokens","messages","metadata","modelPreferences","stopSequences","systemPrompt","temperature"]),mI=new Set(["task","toolChoice","tools"]),mq=new Set(["text","image","audio"]);async function mN(e,t,a){let r=function(e){mz(e,"Sampling request must be a plain object.");let t=Object.keys(e),a=t.filter(e=>mI.has(e));if(a.length>0)throw Error(`Sampling request key(s) not supported by xmcp yet: ${a.join(", ")}.`);let r=t.filter(e=>!mA.has(e));if(r.length>0)throw Error(`Sampling request includes unsupported key(s): ${r.join(", ")}.`);if(!Array.isArray(e.messages)||0===e.messages.length)throw Error("Sampling requires at least one message.");for(let[t,a]of e.messages.entries())!function(e,t){if(mz(t,`Sampling message at index ${e} must be a plain object.`),"user"!==t.role&&"assistant"!==t.role)throw Error(`Sampling message at index ${e} requires role "user" or "assistant".`);let a=t.content;mz(a,`Sampling message at index ${e} requires a content object.`);let r=a.type;if("string"!=typeof r||!mq.has(r))throw Error(`Sampling message at index ${e} uses unsupported content type "${String(r)}". Supported types are text, image, and audio.`);if("text"===r&&"string"!=typeof a.text)throw Error(`Sampling message at index ${e} requires string text content.`);if(("image"===r||"audio"===r)&&("string"!=typeof a.data||"string"!=typeof a.mimeType))throw Error(`Sampling message at index ${e} requires base64 data and a mimeType.`)}(t,a);if("number"!=typeof e.maxTokens)throw Error("Sampling requires a numeric maxTokens.");return e}(t);try{return await e.mcpReq.requestSampling(r,a)}catch(e){if(e instanceof sw&&e.code===s_.MethodNotSupportedByProtocolVersion)throw Error("extra.sample() is not available on protocol revision 2026-07-28: server-initiated sampling was replaced by multi round-trip requests. Return inputRequired({ ... }) with inputRequired.createMessage(...) from the tool handler instead (re-exported from xmcp); the client fulfils the embedded requests and retries the tool call.");throw e}}function mz(e,t){if("object"!=typeof e||null===e||Array.isArray(e))throw Error(t)}let mM={text:e=>"string"!=typeof e.text?{valid:!1,error:'Text content must have a "text" property of type string'}:{valid:!0},image:e=>"string"!=typeof e.data?{valid:!1,error:'Image content must have a "data" property of type string (base64-encoded image)'}:"string"!=typeof e.mimeType?{valid:!1,error:'Image content must have a "mimeType" property of type string'}:{valid:!0},audio:e=>"string"!=typeof e.data?{valid:!1,error:'Audio content must have a "data" property of type string (base64-encoded audio)'}:"string"!=typeof e.mimeType?{valid:!1,error:'Audio content must have a "mimeType" property of type string'}:{valid:!0},resource_link:e=>"string"!=typeof e.name?{valid:!1,error:'Resource link content must have a "name" property of type string'}:"string"!=typeof e.uri?{valid:!1,error:'Resource link content must have a "uri" property of type string'}:void 0!==e.title&&"string"!=typeof e.title?{valid:!1,error:'Resource link "title" property must be a string if provided'}:void 0!==e.description&&"string"!=typeof e.description?{valid:!1,error:'Resource link "description" property must be a string if provided'}:void 0!==e.mimeType&&"string"!=typeof e.mimeType?{valid:!1,error:'Resource link "mimeType" property must be a string if provided'}:{valid:!0}};function mL(e){if(!e||"object"!=typeof e)return{valid:!1,error:"Content must be an object"};if("string"!=typeof e.type)return{valid:!1,error:'Content must have a "type" property of type string'};if(void 0!==e._meta&&(null===e._meta||"object"!=typeof e._meta))return{valid:!1,error:'Content "_meta" property must be an object if provided'};let t=mM[e.type];return t?t(e):{valid:!0}}function mD(e,t,a,r){if(null===e||"object"!=typeof e||Array.isArray(e))throw Error(`Tool "${a}" ${r}: expected a plain object.`);let i=new Set(Object.keys(t)),n=Object.keys(e).filter(e=>!i.has(e));if(n.length>0)throw Error(`Tool "${a}" ${r}: unrecognized key(s): ${n.join(", ")}`);for(let[i,n]of Object.entries(t))try{n.parse(e[i])}catch(e){throw Error(`Tool "${a}" ${r}: ${e?.message??`invalid field "${i}"`}`)}}function mF(e){return!!(e&&"object"==typeof e&&Object.keys(e).some(e=>e.startsWith("ui/")))}function mU(e){let t=e.mcpReq.envelope,a=mf(t?.[i$]);if(!a)try{let e,t=ml();a=t.clientInfo??(e=t.headers,mf({name:mv(e,"x-mcp-client-name"),version:mv(e,"x-mcp-client-version"),title:mv(e,"x-mcp-client-title"),websiteUrl:mv(e,"x-mcp-client-website-url"),description:mv(e,"x-mcp-client-description")}))}catch{}if(!a)try{a=md().clientInfo}catch{}return a}function mH(e){return e.endsWith(".tsx")}let mV=new class{add(e,t){this.resources.set(e,t)}getAll(){return this.resources}clear(){this.resources.clear()}has(e){return this.resources.has(e)}constructor(){!function(e,t,a){t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a}(this,"resources",new Map)}};function mZ(e){let t={};return!function e(a,r=""){if(a&&"object"==typeof a)for(let[i,n]of Object.entries(a)){let a=r?`${r}/${i}`:i;!n||"object"!=typeof n||Array.isArray(n)||n instanceof Date||n instanceof RegExp?t[a]=n:e(n,a)}}(e),t}let mB=["ui/resourceUri","resourceUri","visibility"],mJ=["prefersBorder","domain","csp","permissions","connectDomains","resourceDomains","frameDomains","baseUriDomains"],mG=mo({name:"request-context",fallback:!1});function mK(e){let t=[...e];return(e,a,r)=>(function(e,t,a){let r,i=new Map;if(e.http){let e=ml(),t=Object.fromEntries(Object.entries(e.headers).map(([e,t])=>[e,Array.isArray(t)?Object.freeze([...t]):t]));r=Object.freeze({id:e.id,headers:Object.freeze(t)})}return mG.provider(Object.freeze({clientInfo:t?Object.freeze({...t}):void 0,http:r,signal:e.mcpReq.signal,set(e,t){i.set(e,t)},get:e=>i.get(e),async progress(t,a){let r=e.mcpReq._meta?.progressToken;void 0!==r&&await e.mcpReq.notify({method:"notifications/progress",params:{progressToken:r,progress:t,...void 0===a?{}:{total:a}}})},log:(t,a)=>e.mcpReq.log(t,a)}),a)})(a,mU(a),async()=>{if(0===t.length)return r();let a=Object.freeze({...function(){try{return mG.getContext()}catch{throw Error("getRequestContext() can only be used while handling an MCP request.")}}(),method:e.method,params:Object.freeze({...e.params})}),i=-1,n=async e=>{if(e<=i)throw Error("MCP middleware next() can only be called once");i=e;let o=t[e];return o?o(a,()=>n(e+1)):r()};return n(0)})}let mW=new Set(["tools/list","prompts/get","prompts/list","resources/read","resources/list","resources/templates/list","completion/complete"]);function mY(e){let{tags:t,enabled:a,...r}=e;return{...r,_meta:void 0===t?r._meta:{...r._meta,"xmcp/tags":t}}}function mX(e){return"object"==typeof e&&null!==e&&Object.entries(e).every(([e,t])=>"string"==typeof e&&"object"==typeof t&&null!==t&&"parse"in t&&"function"==typeof t.parse)}function mQ(e){return(e.split("/").pop()||e).replace(/\.[^/.]+$/,"")}function m0(e){let t=e.split("/").filter(e=>""!==e),a=t.findIndex(e=>e.match(/^\(.+\)$/));if(-1===a)return null;let r=t[t.length-1];if(r&&r.match(/^\[.+\]\.ts$/))return null;let i=t[a].slice(1,-1),n=t.slice(a+1),o=n[n.length-1];if(o&&o.includes(".")){let e=o.split(".")[0];"index"!==e?n[n.length-1]=e:n.pop()}let s=[],c=[],l=n.map(e=>{if(!e.match(/^\[.+\]$/))return c.push(e),e;{let t=e.slice(1,-1);return s.push(t),`{${t}}`}}),p=`${i}://${l.join("/")}`,u=s.length>0?"template":"direct";return{filePath:e,uriTemplate:p,scheme:i,parameters:s,pathSegments:c,type:u}}function m1(e){let t=e.replace(/\\/g,"/");if(!t)throw Error("Invalid tool path: path is empty");let a=t.replace(/\.[^/.]+$/,"").replace(/\//g,"_");return{normalizedPath:t,baseName:a}}function m2(e){return Error(`[xmcp] Invalid prompt file: ${e}
|
|
89
|
+
-> Default export must be a prompt handler function.`)}async function m4(e){let t=new Map,a=[];for(let r of(await Promise.all(Object.entries(e).map(async([e,t])=>{let a=await t(),r=function(e,t){if("object"!=typeof e||null===e)throw m2(t);let a=Object.keys(e),r=e.default,i=a.filter(e=>"__esModule"!==e);if(0===a.length||1===i.length&&"default"===i[0]&&"object"==typeof r&&null!==r&&0===Object.keys(r).length)return"empty";if(!("default"in e)||void 0===e.default)return"missing-default";if("function"!=typeof e.default)throw m2(t);return"valid"}(a,e);return"empty"===r?{skipped:!0,issue:{path:e,message:"File is empty."}}:"missing-default"===r?{skipped:!0,issue:{path:e,message:"File does not export a default prompt handler."}}:{skipped:!1,path:e,promptModule:a}})))){if(r.skipped){a.push(r.issue);continue}t.set(r.path,r.promptModule)}return{promptModules:t,skippedPrompts:a}}let m8=function(e=console){let t="";return a=>{let r=a.map(({path:e,message:t})=>`${e}:${t}`).sort().join("|");if(r===t||(t=r,0===a.length))return;a.forEach(({path:t,message:a})=>{e.warn(`[xmcp] Failed to load prompt file: ${t}
|
|
90
|
+
-> ${a}`)});let i=a.length;e.warn(`[xmcp] ${i} prompt${1===i?"":"s"} skipped due to empty files or missing default exports`)}}();function m9(e){return Error(`[xmcp] Invalid resource file: ${e}
|
|
91
|
+
-> Default export must be a resource handler function.`)}async function m5(e){let t=new Map,a=[];for(let r of(await Promise.all(Object.entries(e).map(async([e,t])=>{let a=await t(),r=function(e,t){if("object"!=typeof e||null===e)throw m9(t);let a=Object.keys(e),r=e.default,i=a.filter(e=>"__esModule"!==e);if(0===a.length||1===i.length&&"default"===i[0]&&"object"==typeof r&&null!==r&&0===Object.keys(r).length)return"empty";if(!("default"in e)||void 0===e.default)return"missing-default";if("function"!=typeof e.default)throw m9(t);return"valid"}(a,e);return"empty"===r?{skipped:!0,issue:{path:e,message:"File is empty."}}:"missing-default"===r?{skipped:!0,issue:{path:e,message:"File does not export a default resource handler."}}:{skipped:!1,path:e,resourceModule:a}})))){if(r.skipped){a.push(r.issue);continue}t.set(r.path,r.resourceModule)}return{resourceModules:t,skippedResources:a}}let m6=function(e=console){let t="";return a=>{let r=a.map(({path:e,message:t})=>`${e}:${t}`).sort().join("|");if(r===t||(t=r,0===a.length))return;a.forEach(({path:t,message:a})=>{e.warn(`[xmcp] Failed to load resource file: ${t}
|
|
92
|
+
-> ${a}`)});let i=a.length;e.warn(`[xmcp] ${i} resource${1===i?"":"s"} skipped due to empty files or missing default exports`)}}();function m3(e){return Error(`[xmcp] Invalid tool file: ${e}
|
|
93
|
+
-> Default export must be a tool handler function.`)}async function m7(e){let t=new Map,a=[];for(let r of(await Promise.all(Object.entries(e).map(async([e,t])=>{let a=await t(),r=function(e,t){if("object"!=typeof e||null===e)throw m3(t);let a=Object.keys(e),r=e.default,i=a.filter(e=>"__esModule"!==e);if(0===a.length||1===i.length&&"default"===i[0]&&"object"==typeof r&&null!==r&&0===Object.keys(r).length)return"empty";if(!("default"in e)||void 0===e.default)return"missing-default";if("function"!=typeof e.default)throw m3(t);return"valid"}(a,e);return"empty"===r?{skipped:!0,issue:{path:e,message:"File is empty."}}:"missing-default"===r?{skipped:!0,issue:{path:e,message:"File does not export a default tool handler."}}:{skipped:!1,path:e,toolModule:a}})))){if(r.skipped){a.push(r.issue);continue}t.set(r.path,r.toolModule)}return{toolModules:t,skippedTools:a}}let fe=function(e=console){let t="";return a=>{let r=a.map(({path:e,message:t})=>`${e}:${t}`).sort().join("|");if(r===t||(t=r,0===a.length))return;a.forEach(({path:t,message:a})=>{e.warn(`[xmcp] Failed to load tool file: ${t}
|
|
94
|
+
-> ${a}`)});let i=a.length;e.warn(`[xmcp] ${i} tool${1===i?"":"s"} skipped due to empty files or missing default exports`)}}(),ft=INJECTED_TOOLS,fa=INJECTED_PROMPTS,fr=INJECTED_RESOURCES,fi=SERVER_INFO;async function fn(e,t,r,i){let n=await INJECTED_MIDDLEWARE?.(),o=function(e){if(void 0===e)return[];let t=Array.isArray(e)?[...e]:[e];if(!t.every(e=>"function"==typeof e))throw Error("src/middleware.ts must export mcp as a function or an array of functions");return t}(n?.mcp);return mV.clear(),!function(e,t,a){let r=e.server,i=r.setRequestHandler,n=mK(t);r.setRequestHandler=(e,...t)=>{if(mW.has(e)&&1===t.length&&"function"==typeof t[0]){let e=t[0];t[0]=(t,a)=>n({method:t.method,params:t.params??{}},a,()=>e(t,a))}Reflect.apply(i,r,[e,...t])};try{a()}finally{r.setRequestHandler=i}}(e,o,()=>{!function(e,t,a=[]){t.forEach((t,r)=>{var i,n;let o,s,c,l={name:mQ(r),description:"No description provided"},{default:p,metadata:u,schema:d,outputSchema:m}=t;if("object"==typeof u&&null!==u&&Object.assign(l,u),!1===l.enabled)return;if("function"==typeof p&&"__x402"in p){let e=global.__XMCP_X402_REGISTRY;e&&e.set(l.name,p.__x402)}let f={};if(mX(d)?f=d:null!=d&&console.warn(`Invalid schema for tool "${l.name}" at ${r}. Expected Record<string, z.ZodType>`),null!=m)if(mX(m))o=m;else throw Error(`Invalid outputSchema for tool "${l.name}" at ${r}. Expected Record<string, z.ZodType>`);l.annotations={...l.annotations??{}},void 0===l.annotations.title&&(l.annotations.title=l.name),l._meta={...mY(l)._meta};let h=mH(r),v=!!(i=l._meta)&&"object"==typeof i&&"ui"in i&&"object"==typeof i.ui||h,g=l._meta;if(v){let e=`ui://app/${l.name}.html`;l._meta.ui||(l._meta.ui={}),l._meta.ui.resourceUri||(l._meta.ui.resourceUri=e);let t=function(e){let t={},a={};if(e.ui&&"object"==typeof e.ui){let r=e.ui,i={},n={};for(let[e,t]of Object.entries(r))mB.includes(e)?i[e]=t:mJ.includes(e)?n[e]=t:i[e]=t;Object.keys(i).length>0&&(t.ui=i),Object.keys(n).length>0&&(a.ui=n)}for(let[a,r]of Object.entries(e))"ui"!==a&&(t[a]=r);return{toolMeta:t,resourceMeta:a}}(g);g=t.toolMeta;let a=t.resourceMeta;a.ui=a.ui||{},a.ui.csp=a.ui.csp||{},a.ui.csp.resourceDomains=a.ui.csp.resourceDomains||[],a.ui.csp.resourceDomains.includes("https://esm.sh")||a.ui.csp.resourceDomains.push("https://esm.sh"),mV.add(l.name,{name:l.name,uri:e,handler:p,mimeType:"text/html;profile=mcp-app",_meta:a,toolPath:h?r:void 0})}let y=mZ(g),b=v?y:void 0;s=mH(r)&&v?async(e,t)=>({content:[{type:"text",text:""}],_meta:b,structuredContent:{args:e}}):function(e,t,a,r="unknown-tool"){return async(i,n)=>{let o,s,c=e(i,(o=mU(n),s=function(e){if(!e)return;let t={};return e.headers.forEach((e,a)=>{t[a]=e}),t}(n.http?.req),{signal:n.mcpReq.signal,authInfo:n.http?.authInfo,sessionId:n.sessionId,_meta:n.mcpReq._meta,requestId:n.mcpReq.id,requestInfo:s?{headers:s}:void 0,clientInfo:o,sendNotification:e=>n.mcpReq.notify(e),sendRequest:(e,t,a)=>n.mcpReq.send(e,t,a),elicit:(e,t)=>m$(n,e,t),sample:(e,t)=>mN(n,e,t),inputResponses:n.mcpReq.inputResponses,requestState:n.mcpReq.requestState}));if(c instanceof Promise&&(c=await c),cE(c))return c;if("string"==typeof c||"number"==typeof c){if(a){let e=Object.entries(a);if(1===e.length){let[t,a]=e[0];try{return a.parse(c),{content:[{type:"text",text:"number"==typeof c?`${c}`:c}],structuredContent:{[t]:c}}}catch{}}}return mF(t)?{content:[{type:"text",text:""}],structuredContent:{args:i},_meta:t}:{content:[{type:"text",text:"number"==typeof c?`${c}`:c}]}}if(!a||!c||"object"!=typeof c||Array.isArray(c)||"structuredContent"in c||"content"in c&&Array.isArray(c.content)||"_meta"in c||"isError"in c||(mD(c,a,r,"returned data that does not match outputSchema"),c={structuredContent:c}),c&&"object"==typeof c&&"_meta"in c&&!("content"in c)&&!("structuredContent"in c)){let e=c._meta;if(mF(e))return{content:[{type:"text",text:""}],_meta:e}}if(!c||"object"!=typeof c){let e=null===c?"null":typeof c,t=void 0===c?"undefined":null===c?"null":"object"==typeof c?JSON.stringify(c,null,2):String(c);throw Error(`Tool handler must return a CallToolResult, string, or number. Got ${e}: ${t}
|
|
95
95
|
|
|
96
96
|
Expected CallToolResult format:
|
|
97
97
|
{
|
|
@@ -158,7 +158,7 @@ Expected format:
|
|
|
158
158
|
key: "value",
|
|
159
159
|
nested: { data: "here" }
|
|
160
160
|
}
|
|
161
|
-
}`)}}return c}}(p,b,o,l.name);let x={title:l.annotations?.title,description:l.description,inputSchema:ma(f),outputSchema:o?ma(o,{strict:!0}):void 0,annotations:l.annotations,_meta:y};e.registerTool(l.name,x,(n=l.name,c=mK(a),(e,t)=>c({method:"tools/call",params:{name:n,arguments:e}},t,()=>s(e,t))))})}(e,t,o),r.forEach((t,a)=>{let r=
|
|
161
|
+
}`)}}return c}}(p,b,o,l.name);let x={title:l.annotations?.title,description:l.description,inputSchema:ma(f),outputSchema:o?ma(o,{strict:!0}):void 0,annotations:l.annotations,icons:l.icons,_meta:y};e.registerTool(l.name,x,(n=l.name,c=mK(a),(e,t)=>c({method:"tools/call",params:{name:n,arguments:e}},t,()=>s(e,t))))})}(e,t,o),r.forEach((t,a)=>{let r=mQ(a),i={name:r,title:r,description:"No description provided"},n={},{default:o,metadata:s,schema:c}=t;if("object"==typeof s&&null!==s&&Object.assign(i,s),!1===i.enabled)return;let l=function(e,t="assistant"){return async(a,r)=>{let i,n=e(a,r);if(n instanceof Promise&&(n=await n),Array.isArray(n)||null!==n&&"object"==typeof n&&"messages"in n){let e=Array.isArray(n)?{messages:n}:n,t=await c7.GetPromptResult["~standard"].validate(e);if(t.issues){let e=t.issues.map(e=>{let t=e.path?.map(e=>"object"==typeof e?e.key:e).join(".");return`${t||"result"}: ${e.message}`});throw Error(`Invalid prompt result: ${e.join("; ")}`)}return e}if("string"==typeof n||"number"==typeof n)i={type:"text",text:"number"==typeof n?`${n}`:n};else{let e=mL(n);if(e.valid)i=n;else{let t=null===n?"null":typeof n,a=void 0===n?"undefined":null===n?"null":"object"==typeof n?JSON.stringify(n,null,2):String(n);throw Error(`Prompt handler must return a PromptContent object, string, number, PromptMessage[], or GetPromptResult. Got ${t}: ${a}
|
|
162
162
|
|
|
163
163
|
Validation error: ${e.error}
|
|
164
164
|
|
|
@@ -171,7 +171,7 @@ Expected formats:
|
|
|
171
171
|
- Image content: { type: "image", data: "base64data", mimeType: "image/jpeg" }
|
|
172
172
|
- Audio content: { type: "audio", data: "base64data", mimeType: "audio/mpeg" }
|
|
173
173
|
- Resource link: { type: "resource_link", name: "resource name", uri: "resource://uri" }
|
|
174
|
-
- All content types support an optional "_meta" object property`)}}if("user"!==t&&"assistant"!==t)throw Error(`Invalid role: ${t}`);return{messages:[{role:t,content:i}]}}}(o,i.role||"assistant");
|
|
174
|
+
- All content types support an optional "_meta" object property`)}}if("user"!==t&&"assistant"!==t)throw Error(`Invalid role: ${t}`);return{messages:[{role:t,content:i}]}}}(o,i.role||"assistant");mX(c)?Object.assign(n,c):null!=c&&console.warn(`Invalid schema for prompt "${i.name}" at ${a}. Expected Record<string, z.ZodType>`),e.registerPrompt(i.name,{title:i.title,description:i.description,icons:i.icons,_meta:mY(i)._meta,argsSchema:ma(n)},l)}),[...mV.getAll()].forEach(([t,r])=>{let i=r.mimeType||"text/html;profile=mcp-app",n=r?._meta?mZ(r._meta):void 0,o={name:r.name,description:`Auto-generated resource for ${r.name} tool`,mimeType:r.mimeType,_meta:n},s=async(e,t)=>{if(r.mimeType&&r.toolPath)try{var n;let e,t,o=(n=r.toolPath,IS_CLOUDFLARE?function(e){let{normalizedPath:t,baseName:a}=m1(e),r=5381;for(let e=0;e<t.length;e++)r=Math.imul(r,33)+t.charCodeAt(e)>>>0;let i=r.toString(16).slice(0,6).padStart(6,"0");return`${a}_${i}`}(n):function(e){let{normalizedPath:t,baseName:r}=m1(e),i=a(6982).createHash("md5").update(t).digest("hex").slice(0,6);return`${r}_${i}`}(n)),s=function(e){if(INJECTED_CLIENT_BUNDLES)return INJECTED_CLIENT_BUNDLES[e]||null;if(!IS_CLOUDFLARE)try{let t=a(9896),r=a(6928);for(let a of[r.join(process.cwd(),"dist","client"),r.join(process.cwd(),"client")]){let i=r.join(a,`${e}.bundle.js`),n=r.join(a,`${e}.bundle.css`);if(t.existsSync(i)){let e,a=t.readFileSync(i,"utf-8");return t.existsSync(n)&&(e=t.readFileSync(n,"utf-8")),{js:a,css:e}}}}catch{}return null}(o);if(!s)throw Error(`React client bundle not found for "${r.name}" (bundle: "${o}").
|
|
175
175
|
React tool bundles are generated automatically when you run "xmcp build" (or "xmcp dev").
|
|
176
176
|
Please re-run the build so the framework can regenerate the bundle.`);let c=s.js,l=s.css,p=(e=`
|
|
177
177
|
<script type="module">
|
|
@@ -226,7 +226,7 @@ Please re-run the build so the framework can regenerate the bundle.`);let c=s.js
|
|
|
226
226
|
<div id="root"></div>
|
|
227
227
|
${e}
|
|
228
228
|
</body>
|
|
229
|
-
</html>`);return{contents:[{uri:r.uri,text:p,mimeType:i,_meta:r._meta}]}}catch(e){throw console.error(`React failed for ${r.name}:`,e),e}let o=r.handler({},t);if(o instanceof Promise&&(o=await o),"string"==typeof o)return{contents:[{uri:r.uri,text:o,mimeType:i,_meta:r._meta}]};if(o&&"object"==typeof o&&"_meta"in o&&!("content"in o))return{contents:[{uri:r.uri,text:"",mimeType:i,_meta:r._meta}]};if(o&&"object"==typeof o&&"content"in o&&Array.isArray(o.content)){let e=o.content.find(e=>"text"===e.type);if(e&&"text"===e.type&&"string"==typeof e.text)return{contents:[{uri:r.uri,text:e.text,mimeType:i,_meta:r._meta}]}}return{contents:[{uri:r.uri,text:"",mimeType:i,_meta:r._meta}]}};e.registerResource(r.name,r.uri,o,s)}),i.forEach((t,a)=>{let r={name:
|
|
229
|
+
</html>`);return{contents:[{uri:r.uri,text:p,mimeType:i,_meta:r._meta}]}}catch(e){throw console.error(`React failed for ${r.name}:`,e),e}let o=r.handler({},t);if(o instanceof Promise&&(o=await o),"string"==typeof o)return{contents:[{uri:r.uri,text:o,mimeType:i,_meta:r._meta}]};if(o&&"object"==typeof o&&"_meta"in o&&!("content"in o))return{contents:[{uri:r.uri,text:"",mimeType:i,_meta:r._meta}]};if(o&&"object"==typeof o&&"content"in o&&Array.isArray(o.content)){let e=o.content.find(e=>"text"===e.type);if(e&&"text"===e.type&&"string"==typeof e.text)return{contents:[{uri:r.uri,text:e.text,mimeType:i,_meta:r._meta}]}}return{contents:[{uri:r.uri,text:"",mimeType:i,_meta:r._meta}]}};e.registerResource(r.name,r.uri,o,s)}),i.forEach((t,a)=>{let r={name:mQ(a),description:"No description provided"},{default:i,metadata:n,schema:o,complete:s}=t;if("object"==typeof n&&null!==n&&Object.assign(r,n),!1===r.enabled)return;let c={};mX(o)?c=o:null!=o&&console.warn(`Invalid schema for resource "${r.name}" at ${a}. Expected Record<string, z.ZodType>`);let l=m0(a);if(!l)return void console.warn(`Skipping resource "${r.name}" at ${a}: Invalid file path format`);let p=l.uriTemplate;r.mimeType&&r.mimeType.includes("html")&&(p=p.endsWith(".html")?p:`${p}.html`);let u=function(e,t,a={}){let r=m0(t);if(!r)throw Error(`Invalid resource file path: ${t}. Must follow (scheme)/path/[param] convention.`);return async(t,i)=>{let n=e(function(e,t,a){let r={},i={};if(0===t.parameters.length)return i;let n=t.uriTemplate.split("://")[1]||"",o=e.split("://")[1]||"",s=n.split("/"),c=o.split("/");for(let e=0;e<s.length&&e<c.length;e++){let t=s[e],a=c[e],i=t.match(/^\{(.+)\}$/);i&&(r[i[1]]=a)}for(let e of t.parameters){let t=r[e],n=a[e];if(void 0===t)throw Error(`Missing required parameter: ${e}`);if(!n){i[e]=t;continue}try{i[e]=n.parse(t)}catch(a){throw Error(`Invalid parameter "${e}": ${t}. Validation error: ${a instanceof Error?a.message:String(a)}`)}}return i}(t.href,r,a),i);if(n instanceof Promise&&(n=await n),"string"==typeof n)return{contents:[{uri:t.href,text:n}]};if(!n||"object"!=typeof n||!Array.isArray(n.contents)){let e=null===n?"null":typeof n,t=void 0===n?"undefined":null===n?"null":"object"==typeof n?JSON.stringify(n,null,2):String(n);throw Error(`Resource handler must return a ReadResourceResult or string. Got ${e}: ${t}
|
|
230
230
|
|
|
231
231
|
Expected ReadResourceResult format:
|
|
232
232
|
{
|
|
@@ -235,7 +235,7 @@ Expected ReadResourceResult format:
|
|
|
235
235
|
{ uri: "resource://uri", mimeType: "application/json", text: "json content" },
|
|
236
236
|
{ uri: "resource://uri", blob: base64data }
|
|
237
237
|
]
|
|
238
|
-
}`)}return n.contents.forEach(e=>{e.uri||(e.uri=t.href)}),n}}(i,a,
|
|
238
|
+
}`)}return n.contents.forEach(e=>{e.uri||(e.uri=t.href)}),n}}(i,a,c);if("direct"===l.type)e.registerResource(r.name,p,mY(r),u);else{let t=Object.create(null);for(let e of l.parameters)s&&Object.hasOwn(s,e)&&(t[e]=s[e]);let a=new up(p,{list:void 0,complete:t}),n=async(e,t,a)=>{let r={};for(let e of l.parameters){let a=t[e],i=c[e];if(void 0===a)throw Error(`Missing required parameter: ${e}. Available variables: ${Object.keys(t)}`);i?r[e]=i.parse(a):r[e]=a}let n=i(r,a);return n instanceof Promise&&(n=await n),"string"==typeof n?{contents:[{uri:e.href,text:n}]}:n};e.registerResource(r.name,a,mY(r),n)}})}),e}async function fo(){let{toolModules:e,skippedTools:t}=await m7(ft);return fe(t),e}async function fs(){let{promptModules:e,skippedPrompts:t}=await m4(fa);return m8(t),e}async function fc(){let{resourceModules:e,skippedResources:t}=await m5(fr);return m6(t),e}async function fl(){let{instructions:e,...t}=fi,a=new ul(t,{instructions:e}),r=fo(),i=fs(),n=fc(),[o,s,c]=await Promise.all([r,i,n]);return fn(a,o,s,c)}var fp=a(8611),fu=a.n(fp);require("http2");var fd=a(2203),fm=a(6982),ff=global.Request,fh=class extends ff{constructor(e,t){"object"==typeof e&&fg in e&&(e=e[fg]()),void 0!==t?.body?.getReader&&(t.duplex??="half"),super(e,t)}},fv=Symbol("wrapBodyStream"),fg=Symbol("getRequestCache"),fy=Symbol("requestCache"),fb=Symbol("incomingKey"),fx=Symbol("urlKey"),f_=Symbol("headersKey"),fw=Symbol("abortControllerKey"),fS=Symbol("getAbortController"),fk={get method(){return this[fb].method||"GET"},get url(){return this[fx]},get headers(){return this[f_]||=(e=>{let t=[],a=e.rawHeaders;for(let e=0;e<a.length;e+=2){let{[e]:r,[e+1]:i}=a;58!==r.charCodeAt(0)&&t.push([r,i])}return new Headers(t)})(this[fb])},[fS](){return this[fg](),this[fw]},[fg](){return this[fw]||=new AbortController,this[fy]||=((e,t,a,r,i)=>{let n={method:e,headers:a,signal:i.signal};if("TRACE"===e){n.method="GET";let e=new fh(t,n);return Object.defineProperty(e,"method",{get:()=>"TRACE"}),e}if("GET"!==e&&"HEAD"!==e)if("rawBody"in r&&r.rawBody instanceof Buffer)n.body=new ReadableStream({start(e){e.enqueue(r.rawBody),e.close()}});else if(r[fv]){let e;n.body=new ReadableStream({async pull(t){try{e||=fd.Readable.toWeb(r).getReader();let{done:a,value:i}=await e.read();a?t.close():t.enqueue(i)}catch(e){t.error(e)}}})}else n.body=fd.Readable.toWeb(r);return new fh(t,n)})(this.method,this[fx],this.headers,this[fb],this[fw])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(e=>{Object.defineProperty(fk,e,{get(){return this[fg]()[e]}})}),["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(fk,e,{value:function(){return this[fg]()[e]()}})}),Object.defineProperty(fk,Symbol.for("nodejs.util.inspect.custom"),{value:function(e,t,a){let r={method:this.method,url:this.url,headers:this.headers,nativeRequest:this[fy]};return`Request (lightweight) ${a(r,{...t,depth:null==e?null:e-1})}`}}),Object.setPrototypeOf(fk,fh.prototype);var f$=Symbol("responseCache"),fj=Symbol("getResponseCache"),fE=Symbol("cache"),fR=global.Response,fC=class e{#e;#t;[fj](){return delete this[fE],this[f$]||=new fR(this.#e,this.#t)}constructor(t,a){let r;if(this.#e=t,a instanceof e){const e=a[f$];if(e){this.#t=e,this[fj]();return}this.#t=a.#t,r=new Headers(a.#t.headers)}else this.#t=a;("string"==typeof t||void 0!==t?.getReader||t instanceof Blob||t instanceof Uint8Array)&&(this[fE]=[a?.status||200,t,r||a?.headers])}get headers(){let e=this[fE];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":"text/plain; charset=UTF-8"})),e[2]):this[fj]().headers}get status(){return this[fE]?.[0]??this[fj]().status}get ok(){let e=this.status;return e>=200&&e<300}};function fT(e){return Array.isArray(e)?e[0]:e}async function fP(e,t,a){let r,i=(e.method??"GET").toUpperCase(),n=`http://${fT(e.headers.host)??fT(e.headers[":authority"])??"localhost"}${e.url??"/"}`,o=new Headers;for(let[t,a]of Object.entries(e.headers))if(!(void 0===a||t.startsWith(":")))if(Array.isArray(a))for(let e of a)o.append(t,e);else o.set(t,a);if("GET"!==i&&"HEAD"!==i)if(void 0===t){let t=new TextDecoder,a="";for await(let r of e)a+="string"==typeof r?r:t.decode(r,{stream:!0});(a+=t.decode()).length>0&&(r=a)}else{let e=JSON.stringify(t);o.delete("content-encoding"),o.delete("transfer-encoding"),void 0===e?o.delete("content-length"):(r=e,o.set("content-length",String(new TextEncoder().encode(e).byteLength)))}return new Request(n,{method:i,headers:o,...a?.signal!==void 0&&{signal:a.signal},...void 0!==r&&{body:r}})}["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(e=>{Object.defineProperty(fC.prototype,e,{get(){return this[fj]()[e]}})}),["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(fC.prototype,e,{value:function(){return this[fj]()[e]()}})}),Object.defineProperty(fC.prototype,Symbol.for("nodejs.util.inspect.custom"),{value:function(e,t,a){let r={status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[f$]};return`Response (lightweight) ${a(r,{...t,depth:null==e?null:e-1})}`}}),Object.setPrototypeOf(fC,fR),Object.setPrototypeOf(fC.prototype,fR.prototype),void 0===global.crypto&&(global.crypto=fm),Symbol("outgoingEnded"),Symbol("incomingDraining");var fO=a(5711),fA=a.n(fO);let fI=require("node:crypto"),fq="This MCP server was bootstrapped with xmcp.",fN={cursor:`
|
|
239
239
|
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
|
|
240
240
|
<g clip-path="url(#cursor)">
|
|
241
241
|
<path d="M18.1937 4.73376L10.1872 0.111231C9.93007 -0.0372398 9.61283 -0.0372398 9.35573 0.111231L1.34956 4.73376C1.13344 4.85855 1 5.08934 1 5.33929V14.6606C1 14.9106 1.13344 15.1414 1.34956 15.2662L9.3561 19.8887C9.6132 20.0372 9.93044 20.0372 10.1875 19.8887L18.1941 15.2662C18.4102 15.1414 18.5436 14.9106 18.5436 14.6606V5.33929C18.5436 5.08934 18.4102 4.85855 18.1941 4.73376H18.1937ZM17.6908 5.71291L9.96164 19.1001C9.90939 19.1903 9.77145 19.1535 9.77145 19.049V10.2832C9.77145 10.108 9.67785 9.94603 9.526 9.85808L1.9348 5.47536C1.84459 5.42311 1.88143 5.28517 1.98592 5.28517H17.4442C17.6637 5.28517 17.8009 5.5231 17.6912 5.71329H17.6908V5.71291Z" fill="currentColor" />
|
|
@@ -290,7 +290,7 @@ Expected ReadResourceResult format:
|
|
|
290
290
|
</clipPath>
|
|
291
291
|
</defs>
|
|
292
292
|
</svg>
|
|
293
|
-
`},
|
|
293
|
+
`},fz=String.raw`
|
|
294
294
|
:root {
|
|
295
295
|
color-scheme: dark;
|
|
296
296
|
--brand-white: #f7f7f7;
|
|
@@ -589,7 +589,7 @@ Expected ReadResourceResult format:
|
|
|
589
589
|
clip: rect(0, 0, 0, 0);
|
|
590
590
|
border: 0;
|
|
591
591
|
}
|
|
592
|
-
`;function
|
|
592
|
+
`;function fM(e){return`\u001b[33m${e}\u001b[39m`}var fL=a(9278),fD=a.n(fL);async function fF(e=3001,t="127.0.0.1"){return new Promise(a=>{let r;(r=fD().createServer(),new Promise((a,i)=>{r.once("error",e=>{"code"in e&&"EADDRINUSE"===e.code?a(!1):i(e)}),r.once("listening",()=>{r.close(),a(!0)}),r.listen(e,t)})).then(t=>{t?a(e):(console.log(`\u001b[1m\u001b[33m❯\u001b[39m\u001b[22m Port ${fM(String(e))} is in use, trying ${fM(String(e+1))} instead.`),fF(e+1).then(a))})})}let fU={origin:"*",methods:["GET","POST"],allowedHeaders:["Content-Type","Authorization","mcp-session-id","mcp-protocol-version","mcp-method","mcp-name","x-mcp-client-name","x-mcp-client-version","x-mcp-client-title","x-mcp-client-website-url","x-mcp-client-description"],exposedHeaders:["Content-Type","Authorization","mcp-session-id"],credentials:!1,maxAge:86400};function fH(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}class fV{get requestListener(){return this.app}log(e,...t){this.debug&&console.log(`[StatelessHTTP] ${e}`,...t)}setupProviders(){if(this.providers)for(let e of this.providers)e.router&&this.app.use(e.router),e.middleware&&this.app.use(e.middleware)}setupInitialMiddleware(){var e;this.app.use((e=this.corsConfig,(t,a,r)=>{let i=t.headers.origin;for(let[t,r]of Object.entries(function(e,t){let a={};if(void 0!==e.origin){if(!0===e.origin)t&&(a["Access-Control-Allow-Origin"]=t);else if(!1!==e.origin)if(Array.isArray(e.origin)){let r=t&&e.origin.includes(t)?t:e.origin[0]||"*";a["Access-Control-Allow-Origin"]=r}else a["Access-Control-Allow-Origin"]=String(e.origin)}return void 0!==e.methods&&(a["Access-Control-Allow-Methods"]=Array.isArray(e.methods)?e.methods.join(","):String(e.methods)),void 0!==e.allowedHeaders&&(a["Access-Control-Allow-Headers"]=Array.isArray(e.allowedHeaders)?e.allowedHeaders.join(","):String(e.allowedHeaders)),void 0!==e.exposedHeaders&&(a["Access-Control-Expose-Headers"]=Array.isArray(e.exposedHeaders)?e.exposedHeaders.join(","):String(e.exposedHeaders)),"boolean"==typeof e.credentials&&(a["Access-Control-Allow-Credentials"]=String(e.credentials)),"number"==typeof e.maxAge&&(a["Access-Control-Max-Age"]=String(e.maxAge)),a}(e,i)))a.setHeader(t,r);"OPTIONS"===t.method?a.status(204).end():r()})),this.app.use((e,t,a)=>{this.log(`${e.method} ${e.path}`),a()})}setupInitialRoutes(){this.app.get("/health",(e,t)=>{t.status(200).json({status:"ok",transport:"streamable-http",mode:"stateless"})}),this.app.get("/",(e,t)=>{var a,r,i;let n=this.options.template?.homePage;n?t.send(n):t.send((a=this.endpoint,r=this.options.template?.name,i=this.options.template?.description,`
|
|
593
593
|
<!DOCTYPE html>
|
|
594
594
|
<html lang="en">
|
|
595
595
|
<head>
|
|
@@ -610,7 +610,7 @@ Expected ReadResourceResult format:
|
|
|
610
610
|
rel="stylesheet"
|
|
611
611
|
/>
|
|
612
612
|
<style>
|
|
613
|
-
${
|
|
613
|
+
${fz}
|
|
614
614
|
</style>
|
|
615
615
|
</head>
|
|
616
616
|
<body>
|
|
@@ -620,7 +620,7 @@ ${fN}
|
|
|
620
620
|
<div class="section-header">
|
|
621
621
|
<h2 id="server-name" class="display text-gradient">xmcp server</h2>
|
|
622
622
|
<p id="server-description" class="lead">
|
|
623
|
-
${i||
|
|
623
|
+
${i||fq}
|
|
624
624
|
</p>
|
|
625
625
|
</div>
|
|
626
626
|
</div>
|
|
@@ -727,7 +727,7 @@ ${`
|
|
|
727
727
|
(templateConfig.serverName && templateConfig.serverName.trim()) || "xmcp server";
|
|
728
728
|
const resolvedDescription =
|
|
729
729
|
(templateConfig.serverDescription && templateConfig.serverDescription.trim()) ||
|
|
730
|
-
"${
|
|
730
|
+
"${fq}";
|
|
731
731
|
const endpointPath =
|
|
732
732
|
(templateConfig.endpoint && templateConfig.endpoint.trim()) || "/";
|
|
733
733
|
const normalizedEndpoint = endpointPath.startsWith("/")
|
|
@@ -749,7 +749,7 @@ ${`
|
|
|
749
749
|
elements.description.textContent = resolvedDescription;
|
|
750
750
|
}
|
|
751
751
|
|
|
752
|
-
const icons = ${JSON.stringify(
|
|
752
|
+
const icons = ${JSON.stringify(fN)};
|
|
753
753
|
|
|
754
754
|
const connectionOptions = [
|
|
755
755
|
{
|
|
@@ -952,10 +952,10 @@ args = ["-y", "mcp-remote", "\${serverUrl}"]\`,
|
|
|
952
952
|
</script>
|
|
953
953
|
</body>
|
|
954
954
|
</html>
|
|
955
|
-
`))}),this.setupMcpServerCardRoute(),this.setupOpenAIAppsChallengeRoute(),this.app.use((e,t,a)=>{mp({id:(0,
|
|
955
|
+
`))}),this.setupMcpServerCardRoute(),this.setupOpenAIAppsChallengeRoute(),this.app.use((e,t,a)=>{mp({id:(0,fI.randomUUID)(),headers:e.headers},()=>{a()})})}setupMcpServerCardRoute(){this.app.get("/.well-known/mcp/server-card.json",(e,t)=>{let a=e.get("host")??"localhost",r=a.replace(/:\d+$/,"").split(".").reverse().join("."),i=e.headers["x-forwarded-proto"]?.split(",")[0]?.trim()??e.protocol,n={$schema:"https://static.modelcontextprotocol.io/schemas/v1/server-card.schema.json",name:`${r}/mcp`,version:SERVER_INFO.version,description:this.options.template?.description,title:this.options.template?.name,remotes:[{type:"streamable-http",url:`${i}://${a}${this.endpoint}`}]};this.options.template?.icons?.length&&(n.icons=this.options.template.icons),t.setHeader("Content-Type","application/mcp-server-card+json").setHeader("Cache-Control","public, max-age=3600, must-revalidate").setHeader("Access-Control-Allow-Origin","*").json(n)})}setupOpenAIAppsChallengeRoute(){let e=process.env.OPENAI_APPS_VERIFICATION_TOKEN;if(!e){this.debug&&this.log("OpenAI Apps verification token not configured; skipping challenge route");return}this.app.get("/.well-known/openai-apps-challenge",(t,a)=>{a.status(200).set("Content-Type","text/plain").send(e)})}setupEndpointRoute(){this.app.use(this.endpoint,async(e,t)=>{this.log(`${e.method} ${e.path}`),this.extractAndStoreToolName(e),await this.handleStatelessRequest(e,t)})}extractAndStoreToolName(e){try{let t=function(e){if(e?.body===void 0||null===e.body)return[];let t=Array.isArray(e.body)?e.body:[e.body],a=[];for(let e of t)if("object"==typeof e&&null!==e&&"method"in e&&"tools/call"===e.method){let t=e.params;t&&"object"==typeof t&&"name"in t&&"string"==typeof t.name&&a.push(t.name)}return a}(e);t.length>0&&(0!==t.length&&(e.headers["x-mcp-tool-name"]=t[0],e.headers["x-mcp-tool-names"]=t.join(",")),global.__XMCP_CURRENT_TOOL_NAME=t[0])}catch(e){}}async handleStatelessRequest(e,t){let a=(e=>{for(let t of Array.isArray(e)?e:[e]){let e=mh(t);if(e)return e}})(e.body);t.on("finish",()=>{global.__XMCP_CURRENT_TOOL_NAME=void 0}),t.on("close",()=>{global.__XMCP_CURRENT_TOOL_NAME=void 0}),mc({clientInfo:a}),await this.nodeMcpHandler(e,t,e.body)}async start(){let e=this.options.host||"127.0.0.1",t=await fF(this.port,e);this.server.listen(t,e,()=>{console.log(`\u001b[1m\u001b[32m✔\u001b[39m\u001b[22m MCP Server running on http://${e}:${t}${this.endpoint}`),this.setupShutdownHandlers()})}setupShutdownHandlers(){process.on("SIGINT",this.shutdown.bind(this)),process.on("SIGTERM",this.shutdown.bind(this))}shutdown(){this.log("Shutting down server"),this.mcpHandler.close(),this.server.close(),process.exit(0)}constructor(e,t={},a=fU,r){var i,n;fH(this,"app",void 0),fH(this,"server",void 0),fH(this,"port",void 0),fH(this,"endpoint",void 0),fH(this,"debug",void 0),fH(this,"options",void 0),fH(this,"createServerFn",void 0),fH(this,"corsConfig",void 0),fH(this,"providers",void 0),fH(this,"mcpHandler",void 0),fH(this,"nodeMcpHandler",void 0),this.options={...t},this.app=fA()(),this.server=fu().createServer(this.app),this.port=t.port??parseInt(process.env.PORT||"3001",10),this.endpoint=t.endpoint??"/mcp",this.debug=t.debug??!1,this.createServerFn=e,this.corsConfig=a,this.providers=r,this.mcpHandler=function(e,t={}){var a;let{legacy:r,onerror:i,responseMode:n}=t;if("function"==typeof r)throw TypeError("The 'legacy' option only accepts 'stateless' or 'reject', not a handler function. To serve 2025-era traffic with your own handler, route in user land with the exported isLegacyRequest(request) predicate in front of a strict (legacy: 'reject') handler.");let p=new Set,u=!1,d=e=>{try{i?.(e)}catch{}},m=t.bus??new ut(d),f={toolsChanged:()=>m.publish({kind:"tools_list_changed"}),promptsChanged:()=>m.publish({kind:"prompts_list_changed"}),resourcesChanged:()=>m.publish({kind:"resources_list_changed"}),resourceUpdated:e=>m.publish({kind:"resource_updated",uri:e})},h=function(e){let{bus:t,onerror:a}=e,r=e.maxSubscriptions??1024,i=e.keepAliveMs??15e3,n=new Set;return{serve:function(e,o,s,c){var l,p,u;let d,m,f,h,v,g,y;if(n.size>=r)return a?.(Error(`subscriptions/listen refused: subscription limit reached (${r})`)),ua(e.id,-32603,"Subscription limit reached");let b=(l=e,(v=cd(cu).validateRequest("subscriptions/listen",l)).ok?v.value.params?.notifications:void 0);if(void 0===b)return ua(e.id,-32602,"Invalid params: 'notifications' is required and must be a valid SubscriptionFilter");let x=(p=b,u=s,g={},y=e=>void 0===u||!0===e,!0===p.toolsListChanged&&y(u?.tools?.listChanged)&&(g.toolsListChanged=!0),!0===p.promptsListChanged&&y(u?.prompts?.listChanged)&&(g.promptsListChanged=!0),!0===p.resourcesListChanged&&y(u?.resources?.listChanged)&&(g.resourcesListChanged=!0),void 0!==p.resourceSubscriptions&&p.resourceSubscriptions.length>0&&y(u?.resources?.subscribe)&&(g.resourceSubscriptions=[...p.resourceSubscriptions]),g),_=e.id,w=new TextEncoder,S=!1,k=e=>{if(!S)try{d.enqueue(w.encode(e))}catch(e){a?.(e instanceof Error?e:Error(String(e)))}},$=(e,t)=>{k(`event: message
|
|
956
956
|
data: ${JSON.stringify({jsonrpc:"2.0",method:e,params:t})}
|
|
957
957
|
|
|
958
958
|
`)},j=e=>{if(!S){e&&k(`event: message
|
|
959
959
|
data: ${JSON.stringify({jsonrpc:"2.0",id:_,result:{resultType:"complete",_meta:{[iR]:_,[ij]:c}}})}
|
|
960
960
|
|
|
961
|
-
`),S=!0;try{m?.()}catch(e){a?.(e instanceof Error?e:Error(String(e)))}void 0!==f&&clearInterval(f),h?.(),n.delete(j);try{d.close()}catch{}}},E=new ReadableStream({start(e){d=e;let a=ur({method:"notifications/subscriptions/acknowledged",params:{notifications:x}},_);$(a.method,a.params),m=t.subscribe(e=>{if(S||!function(e,t){switch(t.kind){case"tools_list_changed":return!0===e.toolsListChanged;case"prompts_list_changed":return!0===e.promptsListChanged;case"resources_list_changed":return!0===e.resourcesListChanged;case"resource_updated":return void 0!==e.resourceSubscriptions&&e.resourceSubscriptions.includes(t.uri)}}(x,e))return;let t=ur(function(e){switch(e.kind){case"tools_list_changed":return{method:"notifications/tools/list_changed"};case"prompts_list_changed":return{method:"notifications/prompts/list_changed"};case"resources_list_changed":return{method:"notifications/resources/list_changed"};case"resource_updated":return{method:"notifications/resources/updated",params:{uri:e.uri}}}}(e),_);$(t.method,t.params)}),f=ue(i,()=>k(": keepalive\n\n")),n.add(j)},cancel(){j(!1)}});if(void 0!==o)if(o.aborted)j(!1);else{let e=()=>j(!1);o.addEventListener("abort",e,{once:!0}),h=()=>o.removeEventListener("abort",e)}return new Response(E,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}})},closeAll(){for(let e of n)e(!0)},get openCount(){return n.size}}}({bus:m,maxSubscriptions:t.maxSubscriptions??1024,keepAliveMs:t.keepAliveMs??15e3,onerror:d});"json"===n&&console.warn("responseMode: 'json' drops mid-call notifications. subscriptions/listen streams are always served over SSE regardless; other notifications emitted before a result are dropped.");let v="reject"===r?void 0:(a=t.keepAliveMs,async(t,r)=>{if("POST"!==t.method.toUpperCase())return uS(405,-32e3,"Method not allowed.");try{let i=await e({era:"legacy",...r?.authInfo!==void 0&&{authInfo:r.authInfo},requestInfo:t}),n=new u_({sessionIdGenerator:void 0,...void 0!==a&&{keepAliveMs:a}});await i.connect(n);let o=()=>{n.close().catch(()=>{}),i.close().catch(()=>{})};t.signal?.addEventListener("abort",o,{once:!0});let s=await n.handleRequest(t,{...r?.authInfo!==void 0&&{authInfo:r.authInfo},...r?.parsedBody!==void 0&&{parsedBody:r.parsedBody}});if(null===s.body||"text/event-stream"!==lp(s.headers.get("content-type")))return o(),s;let c=s.body.getReader(),l=!1,p=()=>{l||(l=!0,o())},u=new ReadableStream({pull:async e=>{try{let{done:t,value:a}=await c.read();if(t){p(),e.close();return}void 0!==a&&e.enqueue(a)}catch(t){p(),e.error(t)}},cancel:e=>(p(),c.cancel(e).catch(()=>{}))});return new Response(u,{status:s.status,statusText:s.statusText,headers:s.headers})}catch(e){try{d?.(u$(e))}catch{}return uj(uw(r?.parsedBody))}});async function g(a,r,i){var u,m;let f=a.classification.revision;if(void 0===f||!sE.includes(f)){let e=new s9({supported:[...sE],requested:f??"unknown"});return d(e),uS(400,e.code,e.message,e.data,uw(a.message))}let v=function(e,t){if("request"!==t.messageKind)return;let a=t.message.method;if(void 0===e.mcpMethodHeader)return cU("method-header-missing","(missing)",`the body names method ${a} but the required Mcp-Method header is absent`,"standard-header-validation");let r=Object.hasOwn(cH,a)?cH[a]:void 0;if(void 0===r)return;let i=t.message.params?.[r],n="string"==typeof i?i:void 0;if(void 0===e.mcpNameHeader){if(void 0===n)return;return cU("name-header-missing","(missing)",`the body carries params.${r}="${n}" but the required Mcp-Name header is absent`,"standard-header-validation")}let o=cV(e.mcpNameHeader),s=cz(o);return void 0===s?cU("name-header-invalid-encoding",o,"the Mcp-Name header carries an invalid Base64 sentinel value","standard-header-validation"):void 0!==n&&s!==n?cU("name-header-mismatch",o,`the body carries params.${r}="${n}" but the Mcp-Name header names "${s}"`,"standard-header-validation"):void 0}({httpMethod:r.method,mcpMethodHeader:r.headers.get("mcp-method")??void 0,mcpNameHeader:r.headers.get("mcp-name")??void 0},a);if(void 0!==v)return d(Error(`Rejected inbound request (${v.cell}): ${v.message}`)),uk(v,uw(a.message));let g="request"===a.messageKind?cy(a.message.params):void 0,y=g?.[iE];if("request"===a.messageKind){let e=Object.hasOwn(sS,u=a.message.method)?sS[u]:void 0;if(void 0!==e){let t=s$(e,y);if(void 0!==t){let e=new s5({requiredCapabilities:t});return d(e),uS(cD[e.code]??400,e.code,e.message,e.data,a.message.id)}}}let b=await e({era:"modern",...void 0!==i&&{authInfo:i},requestInfo:r}),x=b instanceof ul?b.server:b;if("request"===a.messageKind&&"subscriptions/listen"===a.message.method){let e=x.getCapabilities(),t=l(x);return b.close().catch(d),h.serve(a.message,r.signal,e,t)}if("request"===a.messageKind&&"tools/call"===a.message.method&&b instanceof ul){let e=a.message.params,t="string"==typeof e?.name?e.name:void 0,i=void 0===t?void 0:b.toolInputSchemaJson(t);if(void 0!==i){let t=cP(i);if(t.valid&&t.declarations.length>0){let i=function(e,t,a){for(let r of e){let e=`Mcp-Param-${r.headerName}`,i=a.get(e),n=function(e,t){let a=e;for(let e of t){if(null===a||"object"!=typeof a)return;a=a[e]}return a}(t,r.path);if(null==n)continue;let o=function(e){if("string"==typeof e)return e;if("boolean"==typeof e)return e?"true":"false";if("number"==typeof e){if(!Number.isFinite(e)||Number.isInteger(e)&&!Number.isSafeInteger(e))return;return String(e)}}(n);if(void 0===o)continue;if(null===i)return cM("param-header-missing",e,`the body carries ${cI(r.path)}=${JSON.stringify(n)} but the ${e} header is absent`);let s=cz(i);if(void 0===s)return cM("param-header-invalid-encoding",e,`the ${e} header carries an invalid Base64 sentinel value`);if(!(("integer"===r.type||"number"===r.type)&&cN.test(s)&&"number"==typeof n?Number(s)===n:s===o))return cM("param-header-mismatch",e,`the ${e} header decodes to ${JSON.stringify(s)} but the body carries ${cI(r.path)}=${JSON.stringify(n)}`)}}(t.declarations,e?.arguments,r.headers);if(void 0!==i)return b.close().catch(d),d(Error(`Rejected inbound request (${i.cell}): ${i.message}`)),uk(i,a.message.id)}}}o(x,f),c(x,sE),void 0!==g&&(m={clientInfo:g[i$],clientCapabilities:y},s(x,m));let _=x.onclose;p.add(x),x.onclose=()=>{p.delete(x),_?.()};try{let e=await ux(b,a.message,{classification:a.classification,request:r,...void 0!==i&&{authInfo:i},...void 0!==n&&{responseMode:n},...void 0!==t.keepAliveMs&&{keepAliveMs:t.keepAliveMs}});return"notification"===a.messageKind&&queueMicrotask(()=>void x.close().catch(()=>{})),e}catch(e){if(e instanceof sw&&e.code===s_.ConnectionClosed)return new Response(null,{status:499});return await x.close().catch(()=>{}),p.delete(x),d(u$(e)),uj(uw(a.message))}}async function y(e,t,a,r){if(void 0!==v)return v(t,{...void 0!==a&&{authInfo:a},...void 0!==r&&{parsedBody:r}});let i=function(e,t){switch(e.reason){case"http-method":return cF("http-method","modern-only-method-not-allowed",405,new s2(-32e3,"Method not allowed."),!0);case"batch":return cF("jsonrpc-shape","modern-only-batch-not-supported",400,new s2(s1.InvalidRequest,"Bad Request: JSON-RPC batches are not supported by this endpoint"),!0);case"response":return cF("jsonrpc-shape","modern-only-response-post",400,new s2(s1.InvalidRequest,"Bad Request: JSON-RPC responses cannot be posted to this endpoint"),!0);case"notification":return;case"initialize":case"no-claim":{let a=e.requestedVersion;return cF("era-classification","modern-only-missing-envelope",400,void 0===a?new s2(s1.UnsupportedProtocolVersion,"Unsupported protocol version: the request did not name a protocol version",{supported:[...t]}):new s9({supported:[...t],requested:a}),!0)}}}(e,sE);return void 0===i?new Response(null,{status:202}):(d(Error(`Rejected 2025-era request on a modern-only endpoint (${i.cell}): ${i.message}`)),uk(i,uw(r)))}async function b(e,t){let a=t?.authInfo;if("POST"===e.method.toUpperCase()&&!lu(e.headers.get("content-type")))return d(Error("Unsupported Media Type: Content-Type must be application/json")),uS(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let r=await uE(e,t?.parsedBody);if("unreadable-body"===r.step)return uS(400,-32700,"Parse error: the request body could not be read");if("no-json-body"===r.step)return void 0!==v?v(r.forwardRequest,{...void 0!==a&&{authInfo:a}}):uS(400,-32700,"Parse error: the request body is not valid JSON");let{outcome:i,body:n,parsedBody:o,forwardRequest:s}=r;try{switch(i.kind){case"reject":return d(Error(`Rejected inbound request (${i.cell}): ${i.message}`)),uk(i,uw(n));case"modern":return await g(i,e,a);case"legacy":return await y(i,s,a,o)}}catch(e){return d(u$(e)),uj(uw(n))}}return{fetch:async(e,t)=>{if(u)throw Error("This MCP handler has been closed");try{return await b(e,t)}catch(e){return d(u$(e)),uj(uw(t?.parsedBody))}},notify:f,bus:m,close:async()=>{u=!0,h.closeAll();let e=[...p].map(e=>e.close().catch(()=>{}));p.clear(),await Promise.all(e)}}}(()=>this.createServerFn(),{legacy:"stateless",onerror:e=>this.log("MCP handler error:",e)}),this.nodeMcpHandler=(i=this.mcpHandler,n={onerror:e=>console.error("[HTTP-server] Error handling MCP request:",e)},async(e,t,a)=>{let r,o;"function"==typeof a&&(a=void 0);let s=!1,c=new AbortController;t.on("close",()=>{s||c.abort()}),!0===t.destroyed&&c.abort();try{let t=await fT(e,a,{signal:c.signal});r=await i.fetch(t,{...void 0!==e.auth&&{authInfo:e.auth},...void 0!==a&&{parsedBody:a}})}catch(e){var l;try{n?.onerror?.(e instanceof Error?e:Error(String(e)))}catch{}l=function(e){if(null===e||"object"!=typeof e||Array.isArray(e))return null;let{method:t,id:a}=e;return"string"!=typeof t?null:"string"==typeof a||"number"==typeof a?a:null}(a),r=Response.json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:l},{status:500})}let p={};for(let[e,t]of r.headers)p[e]=t;if(t.writeHead(r.status,p),null===r.body){s=!0,t.end();return}t.on("drain",()=>{o?.(),o=void 0});let u=new Promise(e=>{c.signal.addEventListener("abort",()=>e(),{once:!0})});try{for await(let e of r.body){if(c.signal.aborted)break;!1===t.write(e)&&await Promise.race([new Promise(e=>{o=e}),u])}}catch{}s=!0,t.end()}),this.app.use(fO().json({limit:this.options.bodySizeLimit||"10mb"})),this.setupInitialRoutes(),this.setupInitialMiddleware(),this.setupProviders(),this.setupEndpointRoute()}}function fV(e){return"function"==typeof e}function fZ(e){var t;return"object"==typeof e&&null!==e&&"middleware"in e&&"router"in e&&"function"==typeof e.middleware&&"function"==typeof(t=e.router)&&null!==t&&"function"==typeof t.use&&"function"==typeof t.get&&"function"==typeof t.post&&"function"==typeof t.route}let fB=mo({name:"http-transport-context"});fB.setContext,fB.getContext;let fJ=fB.provider;var fG=a(8583);a.n(fG)().config();let fK=HTTP_CONFIG,fW=HTTP_CORS_CONFIG,fY=TEMPLATE_CONFIG,fX=INJECTED_MIDDLEWARE;async function fQ(){let e={port:fK?.port,host:fK?.host,debug:fK?.debug,bodySizeLimit:fK?.bodySizeLimit?.toString(),endpoint:fK?.endpoint,template:fY},t={origin:fW.origin,methods:fW.methods,allowedHeaders:fW.allowedHeaders,exposedHeaders:fW.exposedHeaders,credentials:fW.credentials,maxAge:fW.maxAge},a=[];if(fX){let e=await fX();e&&e.default&&(a=function(e){let t=[];if(Array.isArray(e))for(let a of e)fV(a)?t.push({middleware:a}):fZ(a)&&t.push({middleware:a.middleware,router:a.router});else fV(e)?t.push({middleware:e}):fZ(e)&&t.push({middleware:e.middleware,router:e.router});return t}(e.default))}return fJ({config:{http:fK}},async()=>new fH(fc,e,t,a))}!async function(){let e=await fQ();await e.start()}()})(),{}})());
|
|
961
|
+
`),S=!0;try{m?.()}catch(e){a?.(e instanceof Error?e:Error(String(e)))}void 0!==f&&clearInterval(f),h?.(),n.delete(j);try{d.close()}catch{}}},E=new ReadableStream({start(e){d=e;let a=ur({method:"notifications/subscriptions/acknowledged",params:{notifications:x}},_);$(a.method,a.params),m=t.subscribe(e=>{if(S||!function(e,t){switch(t.kind){case"tools_list_changed":return!0===e.toolsListChanged;case"prompts_list_changed":return!0===e.promptsListChanged;case"resources_list_changed":return!0===e.resourcesListChanged;case"resource_updated":return void 0!==e.resourceSubscriptions&&e.resourceSubscriptions.includes(t.uri)}}(x,e))return;let t=ur(function(e){switch(e.kind){case"tools_list_changed":return{method:"notifications/tools/list_changed"};case"prompts_list_changed":return{method:"notifications/prompts/list_changed"};case"resources_list_changed":return{method:"notifications/resources/list_changed"};case"resource_updated":return{method:"notifications/resources/updated",params:{uri:e.uri}}}}(e),_);$(t.method,t.params)}),f=ue(i,()=>k(": keepalive\n\n")),n.add(j)},cancel(){j(!1)}});if(void 0!==o)if(o.aborted)j(!1);else{let e=()=>j(!1);o.addEventListener("abort",e,{once:!0}),h=()=>o.removeEventListener("abort",e)}return new Response(E,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}})},closeAll(){for(let e of n)e(!0)},get openCount(){return n.size}}}({bus:m,maxSubscriptions:t.maxSubscriptions??1024,keepAliveMs:t.keepAliveMs??15e3,onerror:d});"json"===n&&console.warn("responseMode: 'json' drops mid-call notifications. subscriptions/listen streams are always served over SSE regardless; other notifications emitted before a result are dropped.");let v="reject"===r?void 0:(a=t.keepAliveMs,async(t,r)=>{if("POST"!==t.method.toUpperCase())return uS(405,-32e3,"Method not allowed.");try{let i=await e({era:"legacy",...r?.authInfo!==void 0&&{authInfo:r.authInfo},requestInfo:t}),n=new u_({sessionIdGenerator:void 0,...void 0!==a&&{keepAliveMs:a}});await i.connect(n);let o=()=>{n.close().catch(()=>{}),i.close().catch(()=>{})};t.signal?.addEventListener("abort",o,{once:!0});let s=await n.handleRequest(t,{...r?.authInfo!==void 0&&{authInfo:r.authInfo},...r?.parsedBody!==void 0&&{parsedBody:r.parsedBody}});if(null===s.body||"text/event-stream"!==lp(s.headers.get("content-type")))return o(),s;let c=s.body.getReader(),l=!1,p=()=>{l||(l=!0,o())},u=new ReadableStream({pull:async e=>{try{let{done:t,value:a}=await c.read();if(t){p(),e.close();return}void 0!==a&&e.enqueue(a)}catch(t){p(),e.error(t)}},cancel:e=>(p(),c.cancel(e).catch(()=>{}))});return new Response(u,{status:s.status,statusText:s.statusText,headers:s.headers})}catch(e){try{d?.(u$(e))}catch{}return uj(uw(r?.parsedBody))}});async function g(a,r,i){var u,m;let f=a.classification.revision;if(void 0===f||!sE.includes(f)){let e=new s9({supported:[...sE],requested:f??"unknown"});return d(e),uS(400,e.code,e.message,e.data,uw(a.message))}let v=function(e,t){if("request"!==t.messageKind)return;let a=t.message.method;if(void 0===e.mcpMethodHeader)return cU("method-header-missing","(missing)",`the body names method ${a} but the required Mcp-Method header is absent`,"standard-header-validation");let r=Object.hasOwn(cH,a)?cH[a]:void 0;if(void 0===r)return;let i=t.message.params?.[r],n="string"==typeof i?i:void 0;if(void 0===e.mcpNameHeader){if(void 0===n)return;return cU("name-header-missing","(missing)",`the body carries params.${r}="${n}" but the required Mcp-Name header is absent`,"standard-header-validation")}let o=cV(e.mcpNameHeader),s=cz(o);return void 0===s?cU("name-header-invalid-encoding",o,"the Mcp-Name header carries an invalid Base64 sentinel value","standard-header-validation"):void 0!==n&&s!==n?cU("name-header-mismatch",o,`the body carries params.${r}="${n}" but the Mcp-Name header names "${s}"`,"standard-header-validation"):void 0}({httpMethod:r.method,mcpMethodHeader:r.headers.get("mcp-method")??void 0,mcpNameHeader:r.headers.get("mcp-name")??void 0},a);if(void 0!==v)return d(Error(`Rejected inbound request (${v.cell}): ${v.message}`)),uk(v,uw(a.message));let g="request"===a.messageKind?cy(a.message.params):void 0,y=g?.[iE];if("request"===a.messageKind){let e=Object.hasOwn(sS,u=a.message.method)?sS[u]:void 0;if(void 0!==e){let t=s$(e,y);if(void 0!==t){let e=new s5({requiredCapabilities:t});return d(e),uS(cD[e.code]??400,e.code,e.message,e.data,a.message.id)}}}let b=await e({era:"modern",...void 0!==i&&{authInfo:i},requestInfo:r}),x=b instanceof ul?b.server:b;if("request"===a.messageKind&&"subscriptions/listen"===a.message.method){let e=x.getCapabilities(),t=l(x);return b.close().catch(d),h.serve(a.message,r.signal,e,t)}if("request"===a.messageKind&&"tools/call"===a.message.method&&b instanceof ul){let e=a.message.params,t="string"==typeof e?.name?e.name:void 0,i=void 0===t?void 0:b.toolInputSchemaJson(t);if(void 0!==i){let t=cP(i);if(t.valid&&t.declarations.length>0){let i=function(e,t,a){for(let r of e){let e=`Mcp-Param-${r.headerName}`,i=a.get(e),n=function(e,t){let a=e;for(let e of t){if(null===a||"object"!=typeof a)return;a=a[e]}return a}(t,r.path);if(null==n)continue;let o=function(e){if("string"==typeof e)return e;if("boolean"==typeof e)return e?"true":"false";if("number"==typeof e){if(!Number.isFinite(e)||Number.isInteger(e)&&!Number.isSafeInteger(e))return;return String(e)}}(n);if(void 0===o)continue;if(null===i)return cM("param-header-missing",e,`the body carries ${cI(r.path)}=${JSON.stringify(n)} but the ${e} header is absent`);let s=cz(i);if(void 0===s)return cM("param-header-invalid-encoding",e,`the ${e} header carries an invalid Base64 sentinel value`);if(!(("integer"===r.type||"number"===r.type)&&cN.test(s)&&"number"==typeof n?Number(s)===n:s===o))return cM("param-header-mismatch",e,`the ${e} header decodes to ${JSON.stringify(s)} but the body carries ${cI(r.path)}=${JSON.stringify(n)}`)}}(t.declarations,e?.arguments,r.headers);if(void 0!==i)return b.close().catch(d),d(Error(`Rejected inbound request (${i.cell}): ${i.message}`)),uk(i,a.message.id)}}}o(x,f),c(x,sE),void 0!==g&&(m={clientInfo:g[i$],clientCapabilities:y},s(x,m));let _=x.onclose;p.add(x),x.onclose=()=>{p.delete(x),_?.()};try{let e=await ux(b,a.message,{classification:a.classification,request:r,...void 0!==i&&{authInfo:i},...void 0!==n&&{responseMode:n},...void 0!==t.keepAliveMs&&{keepAliveMs:t.keepAliveMs}});return"notification"===a.messageKind&&queueMicrotask(()=>void x.close().catch(()=>{})),e}catch(e){if(e instanceof sw&&e.code===s_.ConnectionClosed)return new Response(null,{status:499});return await x.close().catch(()=>{}),p.delete(x),d(u$(e)),uj(uw(a.message))}}async function y(e,t,a,r){if(void 0!==v)return v(t,{...void 0!==a&&{authInfo:a},...void 0!==r&&{parsedBody:r}});let i=function(e,t){switch(e.reason){case"http-method":return cF("http-method","modern-only-method-not-allowed",405,new s2(-32e3,"Method not allowed."),!0);case"batch":return cF("jsonrpc-shape","modern-only-batch-not-supported",400,new s2(s1.InvalidRequest,"Bad Request: JSON-RPC batches are not supported by this endpoint"),!0);case"response":return cF("jsonrpc-shape","modern-only-response-post",400,new s2(s1.InvalidRequest,"Bad Request: JSON-RPC responses cannot be posted to this endpoint"),!0);case"notification":return;case"initialize":case"no-claim":{let a=e.requestedVersion;return cF("era-classification","modern-only-missing-envelope",400,void 0===a?new s2(s1.UnsupportedProtocolVersion,"Unsupported protocol version: the request did not name a protocol version",{supported:[...t]}):new s9({supported:[...t],requested:a}),!0)}}}(e,sE);return void 0===i?new Response(null,{status:202}):(d(Error(`Rejected 2025-era request on a modern-only endpoint (${i.cell}): ${i.message}`)),uk(i,uw(r)))}async function b(e,t){let a=t?.authInfo;if("POST"===e.method.toUpperCase()&&!lu(e.headers.get("content-type")))return d(Error("Unsupported Media Type: Content-Type must be application/json")),uS(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let r=await uE(e,t?.parsedBody);if("unreadable-body"===r.step)return uS(400,-32700,"Parse error: the request body could not be read");if("no-json-body"===r.step)return void 0!==v?v(r.forwardRequest,{...void 0!==a&&{authInfo:a}}):uS(400,-32700,"Parse error: the request body is not valid JSON");let{outcome:i,body:n,parsedBody:o,forwardRequest:s}=r;try{switch(i.kind){case"reject":return d(Error(`Rejected inbound request (${i.cell}): ${i.message}`)),uk(i,uw(n));case"modern":return await g(i,e,a);case"legacy":return await y(i,s,a,o)}}catch(e){return d(u$(e)),uj(uw(n))}}return{fetch:async(e,t)=>{if(u)throw Error("This MCP handler has been closed");try{return await b(e,t)}catch(e){return d(u$(e)),uj(uw(t?.parsedBody))}},notify:f,bus:m,close:async()=>{u=!0,h.closeAll();let e=[...p].map(e=>e.close().catch(()=>{}));p.clear(),await Promise.all(e)}}}(()=>this.createServerFn(),{legacy:"stateless",onerror:e=>this.log("MCP handler error:",e)}),this.nodeMcpHandler=(i=this.mcpHandler,n={onerror:e=>console.error("[HTTP-server] Error handling MCP request:",e)},async(e,t,a)=>{let r,o;"function"==typeof a&&(a=void 0);let s=!1,c=new AbortController;t.on("close",()=>{s||c.abort()}),!0===t.destroyed&&c.abort();try{let t=await fP(e,a,{signal:c.signal});r=await i.fetch(t,{...void 0!==e.auth&&{authInfo:e.auth},...void 0!==a&&{parsedBody:a}})}catch(e){var l;try{n?.onerror?.(e instanceof Error?e:Error(String(e)))}catch{}l=function(e){if(null===e||"object"!=typeof e||Array.isArray(e))return null;let{method:t,id:a}=e;return"string"!=typeof t?null:"string"==typeof a||"number"==typeof a?a:null}(a),r=Response.json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:l},{status:500})}let p={};for(let[e,t]of r.headers)p[e]=t;if(t.writeHead(r.status,p),null===r.body){s=!0,t.end();return}t.on("drain",()=>{o?.(),o=void 0});let u=new Promise(e=>{c.signal.addEventListener("abort",()=>e(),{once:!0})});try{for await(let e of r.body){if(c.signal.aborted)break;!1===t.write(e)&&await Promise.race([new Promise(e=>{o=e}),u])}}catch{}s=!0,t.end()}),this.app.use(fA().json({limit:this.options.bodySizeLimit||"10mb"})),this.setupInitialRoutes(),this.setupInitialMiddleware(),this.setupProviders(),this.setupEndpointRoute()}}function fZ(e){return"function"==typeof e}function fB(e){var t;return"object"==typeof e&&null!==e&&"middleware"in e&&"router"in e&&"function"==typeof e.middleware&&"function"==typeof(t=e.router)&&null!==t&&"function"==typeof t.use&&"function"==typeof t.get&&"function"==typeof t.post&&"function"==typeof t.route}let fJ=mo({name:"http-transport-context"});fJ.setContext,fJ.getContext;let fG=fJ.provider;var fK=a(8583);a.n(fK)().config();let fW=HTTP_CONFIG,fY=HTTP_CORS_CONFIG,fX=TEMPLATE_CONFIG,fQ=INJECTED_MIDDLEWARE;async function f0(){let e={port:fW?.port,host:fW?.host,debug:fW?.debug,bodySizeLimit:fW?.bodySizeLimit?.toString(),endpoint:fW?.endpoint,template:fX},t={origin:fY.origin,methods:fY.methods,allowedHeaders:fY.allowedHeaders,exposedHeaders:fY.exposedHeaders,credentials:fY.credentials,maxAge:fY.maxAge},a=[];if(fQ){let e=await fQ();e&&e.default&&(a=function(e){let t=[];if(Array.isArray(e))for(let a of e)fZ(a)?t.push({middleware:a}):fB(a)&&t.push({middleware:a.middleware,router:a.router});else fZ(e)?t.push({middleware:e}):fB(e)&&t.push({middleware:e.middleware,router:e.router});return t}(e.default))}return fG({config:{http:fW}},async()=>new fV(fl,e,t,a))}!async function(){let e=await f0();await e.start()}()})(),{}})());
|