xmcp 1.0.0 → 1.1.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/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/runtime/adapter-express.js +14 -14
- package/dist/runtime/adapter-fastify.js +14 -14
- package/dist/runtime/adapter-nestjs.js +14 -14
- package/dist/runtime/adapter-nextjs.js +14 -14
- package/dist/runtime/http.js +26 -26
- package/dist/runtime/stdio.js +12 -12
- package/dist/runtime/utils/sampling.d.ts +3 -0
- package/dist/types/tool.d.ts +5 -1
- package/package.json +1 -1
package/dist/runtime/stdio.js
CHANGED
|
@@ -69,13 +69,13 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
69
69
|
]))`;continue}else if("$"===a[e]){i+=`($|(?=[\r
|
|
70
70
|
]))`;continue}}if(r.s&&"."===a[e]){i+=o?`${a[e]}\r
|
|
71
71
|
`:`[${a[e]}\r
|
|
72
|
-
]`;continue}i+=a[e],"\\"===a[e]?n=!0:o&&"]"===a[e]?o=!1:o||"["!==a[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 pq(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((r,a)=>({...r,[a]:pM(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",a]})??ph(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:pM(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return r;if(e.keyType?._def.typeName===k.ZodString&&e.keyType._def.checks?.length){let{type:a,...i}=pT(e.keyType._def,t);return{...r,propertyNames:i}}if(e.keyType?._def.typeName===k.ZodEnum)return{...r,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:a,...i}=py(e.keyType._def,t);return{...r,propertyNames:i}}return r}let pz={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"},pA=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,r)=>pM(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]})).filter(e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0));return r.length?{anyOf:r}:void 0};function pM(e,t,r=!1){let a=t.seen.get(e);if(t.override){let i=t.override?.(e,t,a,r);if(i!==da)return i}if(a&&!r){let e=pL(a,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,r)=>{switch(t){case k.ZodString:return pT(e,r);case k.ZodNumber:let a={type:"number"};if(!e.checks)return a;for(let t of e.checks)switch(t.kind){case"int":a.type="integer",pf(a,"type",t.message,r);break;case"min":"jsonSchema7"===r.target?t.inclusive?pg(a,"minimum",t.value,t.message,r):pg(a,"exclusiveMinimum",t.value,t.message,r):(t.inclusive||(a.exclusiveMinimum=!0),pg(a,"minimum",t.value,t.message,r));break;case"max":"jsonSchema7"===r.target?t.inclusive?pg(a,"maximum",t.value,t.message,r):pg(a,"exclusiveMaximum",t.value,t.message,r):(t.inclusive||(a.exclusiveMaximum=!0),pg(a,"maximum",t.value,t.message,r));break;case"multipleOf":pg(a,"multipleOf",t.value,t.message,r)}return a;case k.ZodObject:return function(e,t){let r="openAi"===t.target,a={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&&r&&("ZodOptional"===o._def.typeName&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let l=pM(o._def,{...t,currentPath:[...t.currentPath,"properties",e],propertyPath:[...t.currentPath,"properties",e]});void 0!==l&&(a.properties[e]=l,s||i.push(e))}i.length&&(a.required=i);let o=function(e,t){if("ZodNever"!==e.catchall._def.typeName)return pM(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&&(a.additionalProperties=o),a}(e,r);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"===r.target?t.inclusive?pg(i,"minimum",t.value,t.message,r):pg(i,"exclusiveMinimum",t.value,t.message,r):(t.inclusive||(i.exclusiveMinimum=!0),pg(i,"minimum",t.value,t.message,r));break;case"max":"jsonSchema7"===r.target?t.inclusive?pg(i,"maximum",t.value,t.message,r):pg(i,"exclusiveMaximum",t.value,t.message,r):(t.inclusive||(i.exclusiveMaximum=!0),pg(i,"maximum",t.value,t.message,r));break;case"multipleOf":pg(i,"multipleOf",t.value,t.message,r)}return i;case k.ZodBoolean:return{type:"boolean"};case k.ZodDate:return function e(t,r,a){let i=a??r.dateStrategy;if(Array.isArray(i))return{anyOf:i.map((a,i)=>e(t,r,a))};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=r;let s={type:"integer",format:"unix-time"};if("openApi3"===o.target)return s;for(let e of n.checks)switch(e.kind){case"min":pg(s,"minimum",e.value,e.message,o);break;case"max":pg(s,"maximum",e.value,e.message,o)}return s}}(e,r);case k.ZodUndefined:return{not:ph(r)};case k.ZodNull:return"openApi3"===r.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=pM(e.type._def,{...r,currentPath:[...r.currentPath,"items"]})),e.minLength&&pg(n,"minItems",e.minLength.value,e.minLength.message,r),e.maxLength&&pg(n,"maxItems",e.maxLength.value,e.maxLength.message,r),e.exactLength&&(pg(n,"minItems",e.exactLength.value,e.exactLength.message,r),pg(n,"maxItems",e.exactLength.value,e.exactLength.message,r)),n;case k.ZodUnion:case k.ZodDiscriminatedUnion:if("openApi3"===r.target)return pA(e,r);let o=e.options instanceof Map?Array.from(e.options.values()):e.options;if(o.every(e=>e._def.typeName in pz&&(!e._def.checks||!e._def.checks.length))){let e=o.reduce((e,t)=>{let r=pz[t._def.typeName];return r&&!e.includes(r)?[...e,r]: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 r=typeof t._def.value;switch(r){case"string":case"number":case"boolean":return[...e,r];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,r)=>r.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 pA(e,r);case k.ZodIntersection:let s,l,c;return s=[pM(e.left._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),pM(e.right._def,{...r,currentPath:[...r.currentPath,"allOf","1"]})].filter(e=>!!e),l="jsonSchema2019-09"===r.target?{unevaluatedProperties:!1}:void 0,c=[],s.forEach(e=>{if((!("type"in e)||"string"!==e.type)&&"allOf"in e)c.push(...e.allOf),void 0===e.unevaluatedProperties&&(l=void 0);else{let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){let{additionalProperties:r,...a}=e;t=a}else l=void 0;c.push(t)}}),c.length?{allOf:c,...l}:void 0;case k.ZodTuple:return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((e,t)=>pM(e._def,{...r,currentPath:[...r.currentPath,"items",`${t}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[]),additionalItems:pM(e.rest._def,{...r,currentPath:[...r.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,t)=>pM(e._def,{...r,currentPath:[...r.currentPath,"items",`${t}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[])};case k.ZodRecord:return pq(e,r);case k.ZodLiteral:let u;return"bigint"!=(u=typeof e.value)&&"number"!==u&&"boolean"!==u&&"string"!==u?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===r.target?{type:"bigint"===u?"integer":u,enum:[e.value]}:{type:"bigint"===u?"integer":u,const:e.value};case k.ZodEnum:return{type:"string",enum:Array.from(e.values)};case k.ZodNativeEnum:let d,p,m;return d=e.values,{type:1===(m=Array.from(new Set((p=Object.keys(e.values).filter(e=>"number"!=typeof d[d[e]]).map(e=>d[e])).map(e=>typeof e)))).length?"string"===m[0]?"string":"number":["string","number"],enum:p};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"===r.target?{type:pz[e.innerType._def.typeName],nullable:!0}:{type:[pz[e.innerType._def.typeName],"null"]};if("openApi3"===r.target){let t=pM(e.innerType._def,{...r,currentPath:[...r.currentPath]});return t&&"$ref"in t?{allOf:[t],nullable:!0}:t&&{...t,nullable:!0}}let h=pM(e.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","0"]});return h&&{anyOf:[h,{type:"null"}]};case k.ZodOptional:if(r.currentPath.toString()===r.propertyPath?.toString())return pM(e.innerType._def,r);let f=pM(e.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","1"]});return f?{anyOf:[{not:ph(r)},f]}:ph(r);case k.ZodMap:if("record"===r.mapStrategy)return pq(e,r);return{type:"array",maxItems:125,items:{type:"array",items:[pM(e.keyType._def,{...r,currentPath:[...r.currentPath,"items","items","0"]})||ph(r),pM(e.valueType._def,{...r,currentPath:[...r.currentPath,"items","items","1"]})||ph(r)],minItems:2,maxItems:2}};case k.ZodSet:let g;return g={type:"array",uniqueItems:!0,items:pM(e.valueType._def,{...r,currentPath:[...r.currentPath,"items"]})},e.minSize&&pg(g,"minItems",e.minSize.value,e.minSize.message,r),e.maxSize&&pg(g,"maxItems",e.maxSize.value,e.maxSize.message,r),g;case k.ZodLazy:return()=>e.getter()._def;case k.ZodPromise:return pM(e.type._def,r);case k.ZodNaN:case k.ZodNever:return"openAi"===r.target?void 0:{not:ph({...r,currentPath:[...r.currentPath,"not"]})};case k.ZodEffects:return"input"===r.effectStrategy?pM(e.schema._def,r):ph(r);case k.ZodAny:case k.ZodUnknown:return ph(r);case k.ZodDefault:return{...pM(e.innerType._def,r),default:e.defaultValue()};case k.ZodBranded:return py(e,r);case k.ZodReadonly:case k.ZodCatch:return pM(e.innerType._def,r);case k.ZodPipeline:if("input"===r.pipeStrategy)return pM(e.in._def,r);if("output"===r.pipeStrategy)return pM(e.out._def,r);let y=pM(e.in._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),v=pM(e.out._def,{...r,currentPath:[...r.currentPath,"allOf",y?"1":"0"]});return{allOf:[y,v].filter(e=>void 0!==e)};case k.ZodFunction:case k.ZodVoid:case k.ZodSymbol:default:return}})(e,e.typeName,t),o="function"==typeof n?pM(n(),t):n;if(o&&pZ(e,t,o),t.postProcess){let r=t.postProcess(o,e,t);return i.jsonSchema=o,r}return i.jsonSchema=o,o}let pL=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:pm(t.currentPath,e.path)};case"none":case"seen":if(e.path.length<t.currentPath.length&&e.path.every((e,r)=>t.currentPath[r]===e))return console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),ph(t);return"seen"===t.$refStrategy?ph(t):void 0}},pZ=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r);function pD(e,t={}){let{strict:r=!1}=t,a=Object.entries(e),i=e=>({target:t})=>{let i={},n=[];for(let[r,o]of a)i[r]=function(e,t,r){let a=e["~standard"];if(a.jsonSchema)return a.jsonSchema[r]({target:t});if("zod"===e["~standard"].vendor&&!("_zod"in e)&&"_def"in e){let r=((e,t)=>{let r,a,i=(a=void 0!==(r="string"==typeof t?{...di,name:t}:{...di,...t}).name?[...r.basePath,r.definitionPath,r.name]:r.basePath,{...r,flags:{hasReferencedOpenAiAnyType:!1},currentPath:a,propertyPath:void 0,seen:new Map(Object.entries(r.definitions).map(([e,t])=>[t._def,{def:t._def,path:[...r.basePath,r.definitionPath,e],jsonSchema:void 0}]))}),n="object"==typeof t&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:pM(r._def,{...i,currentPath:[...i.basePath,i.definitionPath,t]},!0)??ph(i)}),{}):void 0,o="string"==typeof t?t:t?.nameStrategy==="title"?void 0:t?.name,s=pM(e._def,void 0===o?i:{...i,currentPath:[...i.basePath,i.definitionPath,o]},!1)??ph(i),l="object"==typeof t&&void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==l&&(s.title=l),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 c=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?c.$schema="http://json-schema.org/draft-07/schema#":("jsonSchema2019-09"===i.target||"openAi"===i.target)&&(c.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===i.target&&("anyOf"in c||"oneOf"in c||"allOf"in c||"type"in c&&Array.isArray(c.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),c})(e,{$refStrategy:"none",target:"openapi-3.0"===t?"openApi3":"jsonSchema7"});return delete r.$schema,r}if("zod"===a.vendor&&"_zod"in e)try{let t=rQ(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 "${a.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 r=e.safeParse(void 0);return r.success&&("input"===t||void 0===r.data)}catch{return!1}}(o,e)&&n.push(r);let o={type:"object",properties:i};return n.length>0&&(o.required=n),r&&(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,r]of a){let a=await r["~standard"].validate(t[e]);if(a.issues)for(let t of a.issues)n.push({message:t.message,path:[e,...t.path??[]]});else(e in t||void 0!==a.value)&&(i[e]=a.value)}if(r)for(let r of Object.keys(t))r in e||n.push({message:`Unrecognized key: "${r}"`,path:[r]});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")}}}}let pV=require("async_hooks"),pU=(e,t)=>{globalThis[e]=t},pF=e=>globalThis[e];function pH({name:e}){let t=Symbol.for(`xmcp-context-${e}`),r=Symbol.for(`xmcp-context-${e}-fallback-store`);if(pF(t))return pF(t);let a=new pV.AsyncLocalStorage,i=globalThis[r]??{current:null};pU(r,i);let n={provider:(e,t)=>(i.current=e,a.run(e,t)),getContext:()=>{let t=a.getStore();if(t)return t;if(i.current)return i.current;throw Error(`getContext() can only be used within the ${e} context.`)},setContext:t=>{let r=a.getStore()??i.current;if(!r)throw Error(`setContext() can only be used within the ${e} context.`);Object.assign(r,t)}};return pU(t,n),n}let pJ=pH({name:"http-request-context"});pJ.setContext;let pK=pJ.getContext;pJ.provider;let pB=pH({name:"client-info-context"}),pG=pB.setContext,pW=pB.getContext,pY=pB.provider,pX=e=>{if(!("object"==typeof e&&null!==e&&!Array.isArray(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},pQ=(e,t)=>{let r=t.toLowerCase();for(let[t,a]of Object.entries(e)){if(t.toLowerCase()!==r)continue;let e=Array.isArray(a)?a[0]:a;if("string"!=typeof e)break;let i=e.trim();return i.length>0?i:void 0}},p0=new Set(["message","mode","requestedSchema"]),p1=new Set(["elicitationId","message","mode","url"]),p2=new Set(["properties","required","type"]),p9=new Set(["default","description","format","maxLength","minLength","title","type"]),p4=new Set(["default","description","enum","enumNames","title","type"]),p6=new Set(["default","description","title","type"]),p5=new Set(["default","description","maximum","minimum","title","type"]),p3=new Set(["date","date-time","email","uri"]);async function p8(e,t,r){let a=function(e){let t=e.mode??"form";if("url"===t)return function(e){let t;me(e,"Elicitation request must be a plain object."),p7(e,p1,"URL elicitation"),mt(e.message,"URL elicitation requires a string message."),mr(e.elicitationId,"URL elicitation requires a non-empty elicitationId."),mr(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."),p7(e,p0,"Form elicitation"),mt(e.message,"Form elicitation requires a string message.");let t=e.requestedSchema;if(me(t,"Form elicitation requires a flat object schema."),p7(t,p2,"Form elicitation schema"),"object"!==t.type)throw Error('Form elicitation schema must use type "object".');for(let[e,r]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.`),ma(t.title,`Form elicitation field "${e}" title must be a string.`),ma(t.description,`Form elicitation field "${e}" description must be a string.`),"string"===t.type&&"enum"in t){var r,a;if(p7(t,p4,`Form elicitation field "${e}"`),mn(t.enum,`Form elicitation field "${e}" enum values must be strings.`),r=t.enumNames,a=`Form elicitation field "${e}" enumNames must be strings.`,void 0!==r&&mn(r,a),void 0!==t.enumNames&&t.enumNames.length!==t.enum.length)throw Error(`Form elicitation field "${e}" enumNames length must match enum length.`);if(ma(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)){p7(t,p9,`Form elicitation field "${e}"`),mi(t.minLength,`Form elicitation field "${e}" minLength must be a number.`),mi(t.maxLength,`Form elicitation field "${e}" maxLength must be a number.`),ma(t.default,`Form elicitation field "${e}" default must be a string.`);let r=t.format;if(ma(r,`Form elicitation field "${e}" format must be a string.`),void 0!==r&&!p3.has(r))throw Error(`Form elicitation field "${e}" format must be one of: ${Array.from(p3).join(", ")}.`);return}if("boolean"===t.type){if(p7(t,p6,`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){p7(t,p5,`Form elicitation field "${e}"`),mi(t.minimum,`Form elicitation field "${e}" minimum must be a number.`),mi(t.maximum,`Form elicitation field "${e}" maximum must be a number.`),mi(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,r);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(a,r);return{...t,content:t.content??void 0}}catch(e){if(e instanceof sS&&e.code===sb.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 p7(e,t,r){let a=Object.keys(e).filter(e=>!t.has(e));if(0!==a.length)throw Error(`${r} includes unsupported key(s): ${a.join(", ")}.`)}function me(e,t){if("object"!=typeof e||null===e||Array.isArray(e))throw Error(t)}function mt(e,t){if("string"!=typeof e)throw Error(t)}function mr(e,t){if("string"!=typeof e||0===e.trim().length)throw Error(t)}function ma(e,t){if(void 0!==e&&"string"!=typeof e)throw Error(t)}function mi(e,t){if(void 0!==e&&"number"!=typeof e)throw Error(t)}function mn(e,t){if(!Array.isArray(e)||e.some(e=>"string"!=typeof e))throw Error(t)}let mo={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 ms(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=mo[e.type];return t?t(e):{valid:!0}}function ml(e,t,r,a){if(null===e||"object"!=typeof e||Array.isArray(e))throw Error(`Tool "${r}" ${a}: 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 "${r}" ${a}: unrecognized key(s): ${n.join(", ")}`);for(let[i,n]of Object.entries(t))try{n.parse(e[i])}catch(e){throw Error(`Tool "${r}" ${a}: ${e?.message??`invalid field "${i}"`}`)}}function mc(e){return!!(e&&"object"==typeof e&&Object.keys(e).some(e=>e.startsWith("ui/")))}function mu(e){return e.endsWith(".tsx")}let md=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,r){t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r}(this,"resources",new Map)}};function mp(e){let t={};return!function e(r,a=""){if(r&&"object"==typeof r)for(let[i,n]of Object.entries(r)){let r=a?`${a}/${i}`:i;!n||"object"!=typeof n||Array.isArray(n)||n instanceof Date||n instanceof RegExp?t[r]=n:e(n,r)}}(e),t}let mm=["ui/resourceUri","resourceUri","visibility"],mh=["prefersBorder","domain","csp","permissions","connectDomains","resourceDomains","frameDomains","baseUriDomains"];function mf(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 mg(e){return(e.split("/").pop()||e).replace(/\.[^/.]+$/,"")}function my(e){let t=e.split("/").filter(e=>""!==e),r=t.findIndex(e=>e.match(/^\(.+\)$/));if(-1===r)return null;let a=t[t.length-1];if(a&&a.match(/^\[.+\]\.ts$/))return null;let i=t[r].slice(1,-1),n=t.slice(r+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=[],l=[],c=n.map(e=>{if(!e.match(/^\[.+\]$/))return l.push(e),e;{let t=e.slice(1,-1);return s.push(t),`{${t}}`}}),u=`${i}://${c.join("/")}`,d=s.length>0?"template":"direct";return{filePath:e,uriTemplate:u,scheme:i,parameters:s,pathSegments:l,type:d}}function mv(e){let t=e.replace(/\\/g,"/");if(!t)throw Error("Invalid tool path: path is empty");let r=t.replace(/\.[^/.]+$/,"").replace(/\//g,"_");return{normalizedPath:t,baseName:r}}function m_(e){return Error(`[xmcp] Invalid prompt file: ${e}
|
|
73
|
-
-> Default export must be a prompt handler function.`)}async function
|
|
74
|
-
-> ${r}`)});let i=r.length;e.warn(`[xmcp] ${i} prompt${1===i?"":"s"} skipped due to empty files or missing default exports`)}}();function
|
|
75
|
-
-> Default export must be a resource handler function.`)}async function
|
|
76
|
-
-> ${r}`)});let i=r.length;e.warn(`[xmcp] ${i} resource${1===i?"":"s"} skipped due to empty files or missing default exports`)}}();function
|
|
77
|
-
-> Default export must be a tool handler function.`)}async function
|
|
78
|
-
-> ${r}`)});let i=r.length;e.warn(`[xmcp] ${i} tool${1===i?"":"s"} skipped due to empty files or missing default exports`)}}(),
|
|
72
|
+
]`;continue}i+=a[e],"\\"===a[e]?n=!0:o&&"]"===a[e]?o=!1:o||"["!==a[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 pq(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((r,a)=>({...r,[a]:pM(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",a]})??ph(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:pM(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return r;if(e.keyType?._def.typeName===k.ZodString&&e.keyType._def.checks?.length){let{type:a,...i}=pT(e.keyType._def,t);return{...r,propertyNames:i}}if(e.keyType?._def.typeName===k.ZodEnum)return{...r,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:a,...i}=py(e.keyType._def,t);return{...r,propertyNames:i}}return r}let pz={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"},pA=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,r)=>pM(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]})).filter(e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0));return r.length?{anyOf:r}:void 0};function pM(e,t,r=!1){let a=t.seen.get(e);if(t.override){let i=t.override?.(e,t,a,r);if(i!==da)return i}if(a&&!r){let e=pL(a,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,r)=>{switch(t){case k.ZodString:return pT(e,r);case k.ZodNumber:let a={type:"number"};if(!e.checks)return a;for(let t of e.checks)switch(t.kind){case"int":a.type="integer",pf(a,"type",t.message,r);break;case"min":"jsonSchema7"===r.target?t.inclusive?pg(a,"minimum",t.value,t.message,r):pg(a,"exclusiveMinimum",t.value,t.message,r):(t.inclusive||(a.exclusiveMinimum=!0),pg(a,"minimum",t.value,t.message,r));break;case"max":"jsonSchema7"===r.target?t.inclusive?pg(a,"maximum",t.value,t.message,r):pg(a,"exclusiveMaximum",t.value,t.message,r):(t.inclusive||(a.exclusiveMaximum=!0),pg(a,"maximum",t.value,t.message,r));break;case"multipleOf":pg(a,"multipleOf",t.value,t.message,r)}return a;case k.ZodObject:return function(e,t){let r="openAi"===t.target,a={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&&r&&("ZodOptional"===o._def.typeName&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let l=pM(o._def,{...t,currentPath:[...t.currentPath,"properties",e],propertyPath:[...t.currentPath,"properties",e]});void 0!==l&&(a.properties[e]=l,s||i.push(e))}i.length&&(a.required=i);let o=function(e,t){if("ZodNever"!==e.catchall._def.typeName)return pM(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&&(a.additionalProperties=o),a}(e,r);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"===r.target?t.inclusive?pg(i,"minimum",t.value,t.message,r):pg(i,"exclusiveMinimum",t.value,t.message,r):(t.inclusive||(i.exclusiveMinimum=!0),pg(i,"minimum",t.value,t.message,r));break;case"max":"jsonSchema7"===r.target?t.inclusive?pg(i,"maximum",t.value,t.message,r):pg(i,"exclusiveMaximum",t.value,t.message,r):(t.inclusive||(i.exclusiveMaximum=!0),pg(i,"maximum",t.value,t.message,r));break;case"multipleOf":pg(i,"multipleOf",t.value,t.message,r)}return i;case k.ZodBoolean:return{type:"boolean"};case k.ZodDate:return function e(t,r,a){let i=a??r.dateStrategy;if(Array.isArray(i))return{anyOf:i.map((a,i)=>e(t,r,a))};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=r;let s={type:"integer",format:"unix-time"};if("openApi3"===o.target)return s;for(let e of n.checks)switch(e.kind){case"min":pg(s,"minimum",e.value,e.message,o);break;case"max":pg(s,"maximum",e.value,e.message,o)}return s}}(e,r);case k.ZodUndefined:return{not:ph(r)};case k.ZodNull:return"openApi3"===r.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=pM(e.type._def,{...r,currentPath:[...r.currentPath,"items"]})),e.minLength&&pg(n,"minItems",e.minLength.value,e.minLength.message,r),e.maxLength&&pg(n,"maxItems",e.maxLength.value,e.maxLength.message,r),e.exactLength&&(pg(n,"minItems",e.exactLength.value,e.exactLength.message,r),pg(n,"maxItems",e.exactLength.value,e.exactLength.message,r)),n;case k.ZodUnion:case k.ZodDiscriminatedUnion:if("openApi3"===r.target)return pA(e,r);let o=e.options instanceof Map?Array.from(e.options.values()):e.options;if(o.every(e=>e._def.typeName in pz&&(!e._def.checks||!e._def.checks.length))){let e=o.reduce((e,t)=>{let r=pz[t._def.typeName];return r&&!e.includes(r)?[...e,r]: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 r=typeof t._def.value;switch(r){case"string":case"number":case"boolean":return[...e,r];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,r)=>r.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 pA(e,r);case k.ZodIntersection:let s,l,c;return s=[pM(e.left._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),pM(e.right._def,{...r,currentPath:[...r.currentPath,"allOf","1"]})].filter(e=>!!e),l="jsonSchema2019-09"===r.target?{unevaluatedProperties:!1}:void 0,c=[],s.forEach(e=>{if((!("type"in e)||"string"!==e.type)&&"allOf"in e)c.push(...e.allOf),void 0===e.unevaluatedProperties&&(l=void 0);else{let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){let{additionalProperties:r,...a}=e;t=a}else l=void 0;c.push(t)}}),c.length?{allOf:c,...l}:void 0;case k.ZodTuple:return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((e,t)=>pM(e._def,{...r,currentPath:[...r.currentPath,"items",`${t}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[]),additionalItems:pM(e.rest._def,{...r,currentPath:[...r.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,t)=>pM(e._def,{...r,currentPath:[...r.currentPath,"items",`${t}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[])};case k.ZodRecord:return pq(e,r);case k.ZodLiteral:let u;return"bigint"!=(u=typeof e.value)&&"number"!==u&&"boolean"!==u&&"string"!==u?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===r.target?{type:"bigint"===u?"integer":u,enum:[e.value]}:{type:"bigint"===u?"integer":u,const:e.value};case k.ZodEnum:return{type:"string",enum:Array.from(e.values)};case k.ZodNativeEnum:let d,p,m;return d=e.values,{type:1===(m=Array.from(new Set((p=Object.keys(e.values).filter(e=>"number"!=typeof d[d[e]]).map(e=>d[e])).map(e=>typeof e)))).length?"string"===m[0]?"string":"number":["string","number"],enum:p};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"===r.target?{type:pz[e.innerType._def.typeName],nullable:!0}:{type:[pz[e.innerType._def.typeName],"null"]};if("openApi3"===r.target){let t=pM(e.innerType._def,{...r,currentPath:[...r.currentPath]});return t&&"$ref"in t?{allOf:[t],nullable:!0}:t&&{...t,nullable:!0}}let h=pM(e.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","0"]});return h&&{anyOf:[h,{type:"null"}]};case k.ZodOptional:if(r.currentPath.toString()===r.propertyPath?.toString())return pM(e.innerType._def,r);let f=pM(e.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","1"]});return f?{anyOf:[{not:ph(r)},f]}:ph(r);case k.ZodMap:if("record"===r.mapStrategy)return pq(e,r);return{type:"array",maxItems:125,items:{type:"array",items:[pM(e.keyType._def,{...r,currentPath:[...r.currentPath,"items","items","0"]})||ph(r),pM(e.valueType._def,{...r,currentPath:[...r.currentPath,"items","items","1"]})||ph(r)],minItems:2,maxItems:2}};case k.ZodSet:let g;return g={type:"array",uniqueItems:!0,items:pM(e.valueType._def,{...r,currentPath:[...r.currentPath,"items"]})},e.minSize&&pg(g,"minItems",e.minSize.value,e.minSize.message,r),e.maxSize&&pg(g,"maxItems",e.maxSize.value,e.maxSize.message,r),g;case k.ZodLazy:return()=>e.getter()._def;case k.ZodPromise:return pM(e.type._def,r);case k.ZodNaN:case k.ZodNever:return"openAi"===r.target?void 0:{not:ph({...r,currentPath:[...r.currentPath,"not"]})};case k.ZodEffects:return"input"===r.effectStrategy?pM(e.schema._def,r):ph(r);case k.ZodAny:case k.ZodUnknown:return ph(r);case k.ZodDefault:return{...pM(e.innerType._def,r),default:e.defaultValue()};case k.ZodBranded:return py(e,r);case k.ZodReadonly:case k.ZodCatch:return pM(e.innerType._def,r);case k.ZodPipeline:if("input"===r.pipeStrategy)return pM(e.in._def,r);if("output"===r.pipeStrategy)return pM(e.out._def,r);let y=pM(e.in._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),v=pM(e.out._def,{...r,currentPath:[...r.currentPath,"allOf",y?"1":"0"]});return{allOf:[y,v].filter(e=>void 0!==e)};case k.ZodFunction:case k.ZodVoid:case k.ZodSymbol:default:return}})(e,e.typeName,t),o="function"==typeof n?pM(n(),t):n;if(o&&pZ(e,t,o),t.postProcess){let r=t.postProcess(o,e,t);return i.jsonSchema=o,r}return i.jsonSchema=o,o}let pL=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:pm(t.currentPath,e.path)};case"none":case"seen":if(e.path.length<t.currentPath.length&&e.path.every((e,r)=>t.currentPath[r]===e))return console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),ph(t);return"seen"===t.$refStrategy?ph(t):void 0}},pZ=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r);function pD(e,t={}){let{strict:r=!1}=t,a=Object.entries(e),i=e=>({target:t})=>{let i={},n=[];for(let[r,o]of a)i[r]=function(e,t,r){let a=e["~standard"];if(a.jsonSchema)return a.jsonSchema[r]({target:t});if("zod"===e["~standard"].vendor&&!("_zod"in e)&&"_def"in e){let r=((e,t)=>{let r,a,i=(a=void 0!==(r="string"==typeof t?{...di,name:t}:{...di,...t}).name?[...r.basePath,r.definitionPath,r.name]:r.basePath,{...r,flags:{hasReferencedOpenAiAnyType:!1},currentPath:a,propertyPath:void 0,seen:new Map(Object.entries(r.definitions).map(([e,t])=>[t._def,{def:t._def,path:[...r.basePath,r.definitionPath,e],jsonSchema:void 0}]))}),n="object"==typeof t&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:pM(r._def,{...i,currentPath:[...i.basePath,i.definitionPath,t]},!0)??ph(i)}),{}):void 0,o="string"==typeof t?t:t?.nameStrategy==="title"?void 0:t?.name,s=pM(e._def,void 0===o?i:{...i,currentPath:[...i.basePath,i.definitionPath,o]},!1)??ph(i),l="object"==typeof t&&void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==l&&(s.title=l),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 c=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?c.$schema="http://json-schema.org/draft-07/schema#":("jsonSchema2019-09"===i.target||"openAi"===i.target)&&(c.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===i.target&&("anyOf"in c||"oneOf"in c||"allOf"in c||"type"in c&&Array.isArray(c.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),c})(e,{$refStrategy:"none",target:"openapi-3.0"===t?"openApi3":"jsonSchema7"});return delete r.$schema,r}if("zod"===a.vendor&&"_zod"in e)try{let t=rQ(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 "${a.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 r=e.safeParse(void 0);return r.success&&("input"===t||void 0===r.data)}catch{return!1}}(o,e)&&n.push(r);let o={type:"object",properties:i};return n.length>0&&(o.required=n),r&&(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,r]of a){let a=await r["~standard"].validate(t[e]);if(a.issues)for(let t of a.issues)n.push({message:t.message,path:[e,...t.path??[]]});else(e in t||void 0!==a.value)&&(i[e]=a.value)}if(r)for(let r of Object.keys(t))r in e||n.push({message:`Unrecognized key: "${r}"`,path:[r]});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")}}}}let pV=require("async_hooks"),pU=(e,t)=>{globalThis[e]=t},pF=e=>globalThis[e];function pH({name:e}){let t=Symbol.for(`xmcp-context-${e}`),r=Symbol.for(`xmcp-context-${e}-fallback-store`);if(pF(t))return pF(t);let a=new pV.AsyncLocalStorage,i=globalThis[r]??{current:null};pU(r,i);let n={provider:(e,t)=>(i.current=e,a.run(e,t)),getContext:()=>{let t=a.getStore();if(t)return t;if(i.current)return i.current;throw Error(`getContext() can only be used within the ${e} context.`)},setContext:t=>{let r=a.getStore()??i.current;if(!r)throw Error(`setContext() can only be used within the ${e} context.`);Object.assign(r,t)}};return pU(t,n),n}let pJ=pH({name:"http-request-context"});pJ.setContext;let pK=pJ.getContext;pJ.provider;let pB=pH({name:"client-info-context"}),pG=pB.setContext,pW=pB.getContext,pY=pB.provider,pX=e=>{if(!("object"==typeof e&&null!==e&&!Array.isArray(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},pQ=(e,t)=>{let r=t.toLowerCase();for(let[t,a]of Object.entries(e)){if(t.toLowerCase()!==r)continue;let e=Array.isArray(a)?a[0]:a;if("string"!=typeof e)break;let i=e.trim();return i.length>0?i:void 0}},p0=new Set(["message","mode","requestedSchema"]),p1=new Set(["elicitationId","message","mode","url"]),p2=new Set(["properties","required","type"]),p9=new Set(["default","description","format","maxLength","minLength","title","type"]),p4=new Set(["default","description","enum","enumNames","title","type"]),p6=new Set(["default","description","title","type"]),p5=new Set(["default","description","maximum","minimum","title","type"]),p3=new Set(["date","date-time","email","uri"]);async function p8(e,t,r){let a=function(e){let t=e.mode??"form";if("url"===t)return function(e){let t;me(e,"Elicitation request must be a plain object."),p7(e,p1,"URL elicitation"),mt(e.message,"URL elicitation requires a string message."),mr(e.elicitationId,"URL elicitation requires a non-empty elicitationId."),mr(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."),p7(e,p0,"Form elicitation"),mt(e.message,"Form elicitation requires a string message.");let t=e.requestedSchema;if(me(t,"Form elicitation requires a flat object schema."),p7(t,p2,"Form elicitation schema"),"object"!==t.type)throw Error('Form elicitation schema must use type "object".');for(let[e,r]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.`),ma(t.title,`Form elicitation field "${e}" title must be a string.`),ma(t.description,`Form elicitation field "${e}" description must be a string.`),"string"===t.type&&"enum"in t){var r,a;if(p7(t,p4,`Form elicitation field "${e}"`),mn(t.enum,`Form elicitation field "${e}" enum values must be strings.`),r=t.enumNames,a=`Form elicitation field "${e}" enumNames must be strings.`,void 0!==r&&mn(r,a),void 0!==t.enumNames&&t.enumNames.length!==t.enum.length)throw Error(`Form elicitation field "${e}" enumNames length must match enum length.`);if(ma(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)){p7(t,p9,`Form elicitation field "${e}"`),mi(t.minLength,`Form elicitation field "${e}" minLength must be a number.`),mi(t.maxLength,`Form elicitation field "${e}" maxLength must be a number.`),ma(t.default,`Form elicitation field "${e}" default must be a string.`);let r=t.format;if(ma(r,`Form elicitation field "${e}" format must be a string.`),void 0!==r&&!p3.has(r))throw Error(`Form elicitation field "${e}" format must be one of: ${Array.from(p3).join(", ")}.`);return}if("boolean"===t.type){if(p7(t,p6,`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){p7(t,p5,`Form elicitation field "${e}"`),mi(t.minimum,`Form elicitation field "${e}" minimum must be a number.`),mi(t.maximum,`Form elicitation field "${e}" maximum must be a number.`),mi(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,r);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(a,r);return{...t,content:t.content??void 0}}catch(e){if(e instanceof sS&&e.code===sb.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 p7(e,t,r){let a=Object.keys(e).filter(e=>!t.has(e));if(0!==a.length)throw Error(`${r} includes unsupported key(s): ${a.join(", ")}.`)}function me(e,t){if("object"!=typeof e||null===e||Array.isArray(e))throw Error(t)}function mt(e,t){if("string"!=typeof e)throw Error(t)}function mr(e,t){if("string"!=typeof e||0===e.trim().length)throw Error(t)}function ma(e,t){if(void 0!==e&&"string"!=typeof e)throw Error(t)}function mi(e,t){if(void 0!==e&&"number"!=typeof e)throw Error(t)}function mn(e,t){if(!Array.isArray(e)||e.some(e=>"string"!=typeof e))throw Error(t)}let mo=new Set(["_meta","includeContext","maxTokens","messages","metadata","modelPreferences","stopSequences","systemPrompt","temperature"]),ms=new Set(["task","toolChoice","tools"]),ml=new Set(["text","image","audio"]);async function mc(e,t,r){let a=function(e){mu(e,"Sampling request must be a plain object.");let t=Object.keys(e),r=t.filter(e=>ms.has(e));if(r.length>0)throw Error(`Sampling request key(s) not supported by xmcp yet: ${r.join(", ")}.`);let a=t.filter(e=>!mo.has(e));if(a.length>0)throw Error(`Sampling request includes unsupported key(s): ${a.join(", ")}.`);if(!Array.isArray(e.messages)||0===e.messages.length)throw Error("Sampling requires at least one message.");for(let[t,r]of e.messages.entries())!function(e,t){if(mu(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 r=t.content;mu(r,`Sampling message at index ${e} requires a content object.`);let a=r.type;if("string"!=typeof a||!ml.has(a))throw Error(`Sampling message at index ${e} uses unsupported content type "${String(a)}". Supported types are text, image, and audio.`);if("text"===a&&"string"!=typeof r.text)throw Error(`Sampling message at index ${e} requires string text content.`);if(("image"===a||"audio"===a)&&("string"!=typeof r.data||"string"!=typeof r.mimeType))throw Error(`Sampling message at index ${e} requires base64 data and a mimeType.`)}(t,r);if("number"!=typeof e.maxTokens)throw Error("Sampling requires a numeric maxTokens.");return e}(t);try{return await e.mcpReq.requestSampling(a,r)}catch(e){if(e instanceof sS&&e.code===sb.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 mu(e,t){if("object"!=typeof e||null===e||Array.isArray(e))throw Error(t)}let md={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 mp(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=md[e.type];return t?t(e):{valid:!0}}function mm(e,t,r,a){if(null===e||"object"!=typeof e||Array.isArray(e))throw Error(`Tool "${r}" ${a}: 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 "${r}" ${a}: unrecognized key(s): ${n.join(", ")}`);for(let[i,n]of Object.entries(t))try{n.parse(e[i])}catch(e){throw Error(`Tool "${r}" ${a}: ${e?.message??`invalid field "${i}"`}`)}}function mh(e){return!!(e&&"object"==typeof e&&Object.keys(e).some(e=>e.startsWith("ui/")))}function mf(e){return e.endsWith(".tsx")}let mg=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,r){t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r}(this,"resources",new Map)}};function my(e){let t={};return!function e(r,a=""){if(r&&"object"==typeof r)for(let[i,n]of Object.entries(r)){let r=a?`${a}/${i}`:i;!n||"object"!=typeof n||Array.isArray(n)||n instanceof Date||n instanceof RegExp?t[r]=n:e(n,r)}}(e),t}let mv=["ui/resourceUri","resourceUri","visibility"],m_=["prefersBorder","domain","csp","permissions","connectDomains","resourceDomains","frameDomains","baseUriDomains"];function mb(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 mS(e){return(e.split("/").pop()||e).replace(/\.[^/.]+$/,"")}function m$(e){let t=e.split("/").filter(e=>""!==e),r=t.findIndex(e=>e.match(/^\(.+\)$/));if(-1===r)return null;let a=t[t.length-1];if(a&&a.match(/^\[.+\]\.ts$/))return null;let i=t[r].slice(1,-1),n=t.slice(r+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=[],l=[],c=n.map(e=>{if(!e.match(/^\[.+\]$/))return l.push(e),e;{let t=e.slice(1,-1);return s.push(t),`{${t}}`}}),u=`${i}://${c.join("/")}`,d=s.length>0?"template":"direct";return{filePath:e,uriTemplate:u,scheme:i,parameters:s,pathSegments:l,type:d}}function mw(e){let t=e.replace(/\\/g,"/");if(!t)throw Error("Invalid tool path: path is empty");let r=t.replace(/\.[^/.]+$/,"").replace(/\//g,"_");return{normalizedPath:t,baseName:r}}function mk(e){return Error(`[xmcp] Invalid prompt file: ${e}
|
|
73
|
+
-> Default export must be a prompt handler function.`)}async function mR(e){let t=new Map,r=[];for(let a of(await Promise.all(Object.entries(e).map(async([e,t])=>{let r=await t(),a=function(e,t){if("object"!=typeof e||null===e)throw mk(t);let r=Object.keys(e),a=e.default,i=r.filter(e=>"__esModule"!==e);if(0===r.length||1===i.length&&"default"===i[0]&&"object"==typeof a&&null!==a&&0===Object.keys(a).length)return"empty";if(!("default"in e)||void 0===e.default)return"missing-default";if("function"!=typeof e.default)throw mk(t);return"valid"}(r,e);return"empty"===a?{skipped:!0,issue:{path:e,message:"File is empty."}}:"missing-default"===a?{skipped:!0,issue:{path:e,message:"File does not export a default prompt handler."}}:{skipped:!1,path:e,promptModule:r}})))){if(a.skipped){r.push(a.issue);continue}t.set(a.path,a.promptModule)}return{promptModules:t,skippedPrompts:r}}let mx=function(e=console){let t="";return r=>{let a=r.map(({path:e,message:t})=>`${e}:${t}`).sort().join("|");if(a===t||(t=a,0===r.length))return;r.forEach(({path:t,message:r})=>{e.warn(`[xmcp] Failed to load prompt file: ${t}
|
|
74
|
+
-> ${r}`)});let i=r.length;e.warn(`[xmcp] ${i} prompt${1===i?"":"s"} skipped due to empty files or missing default exports`)}}();function mP(e){return Error(`[xmcp] Invalid resource file: ${e}
|
|
75
|
+
-> Default export must be a resource handler function.`)}async function mE(e){let t=new Map,r=[];for(let a of(await Promise.all(Object.entries(e).map(async([e,t])=>{let r=await t(),a=function(e,t){if("object"!=typeof e||null===e)throw mP(t);let r=Object.keys(e),a=e.default,i=r.filter(e=>"__esModule"!==e);if(0===r.length||1===i.length&&"default"===i[0]&&"object"==typeof a&&null!==a&&0===Object.keys(a).length)return"empty";if(!("default"in e)||void 0===e.default)return"missing-default";if("function"!=typeof e.default)throw mP(t);return"valid"}(r,e);return"empty"===a?{skipped:!0,issue:{path:e,message:"File is empty."}}:"missing-default"===a?{skipped:!0,issue:{path:e,message:"File does not export a default resource handler."}}:{skipped:!1,path:e,resourceModule:r}})))){if(a.skipped){r.push(a.issue);continue}t.set(a.path,a.resourceModule)}return{resourceModules:t,skippedResources:r}}let mT=function(e=console){let t="";return r=>{let a=r.map(({path:e,message:t})=>`${e}:${t}`).sort().join("|");if(a===t||(t=a,0===r.length))return;r.forEach(({path:t,message:r})=>{e.warn(`[xmcp] Failed to load resource file: ${t}
|
|
76
|
+
-> ${r}`)});let i=r.length;e.warn(`[xmcp] ${i} resource${1===i?"":"s"} skipped due to empty files or missing default exports`)}}();function mj(e){return Error(`[xmcp] Invalid tool file: ${e}
|
|
77
|
+
-> Default export must be a tool handler function.`)}async function mO(e){let t=new Map,r=[];for(let a of(await Promise.all(Object.entries(e).map(async([e,t])=>{let r=await t(),a=function(e,t){if("object"!=typeof e||null===e)throw mj(t);let r=Object.keys(e),a=e.default,i=r.filter(e=>"__esModule"!==e);if(0===r.length||1===i.length&&"default"===i[0]&&"object"==typeof a&&null!==a&&0===Object.keys(a).length)return"empty";if(!("default"in e)||void 0===e.default)return"missing-default";if("function"!=typeof e.default)throw mj(t);return"valid"}(r,e);return"empty"===a?{skipped:!0,issue:{path:e,message:"File is empty."}}:"missing-default"===a?{skipped:!0,issue:{path:e,message:"File does not export a default tool handler."}}:{skipped:!1,path:e,toolModule:r}})))){if(a.skipped){r.push(a.issue);continue}t.set(a.path,a.toolModule)}return{toolModules:t,skippedTools:r}}let mC=function(e=console){let t="";return r=>{let a=r.map(({path:e,message:t})=>`${e}:${t}`).sort().join("|");if(a===t||(t=a,0===r.length))return;r.forEach(({path:t,message:r})=>{e.warn(`[xmcp] Failed to load tool file: ${t}
|
|
78
|
+
-> ${r}`)});let i=r.length;e.warn(`[xmcp] ${i} tool${1===i?"":"s"} skipped due to empty files or missing default exports`)}}(),mN=INJECTED_TOOLS,mI=INJECTED_PROMPTS,mq=INJECTED_RESOURCES,mz=SERVER_INFO;async function mA(e,t,a,i){return mg.clear(),t.forEach((t,r)=>{var a;let i,n,o={name:mS(r),description:"No description provided"},{default:s,metadata:l,schema:c,outputSchema:u}=t;if("object"==typeof l&&null!==l&&Object.assign(o,l),"function"==typeof s&&"__x402"in s){let e=global.__XMCP_X402_REGISTRY;e&&e.set(o.name,s.__x402)}let d={};if(mb(c)?d=c:null!=c&&console.warn(`Invalid schema for tool "${o.name}" at ${r}. Expected Record<string, z.ZodType>`),null!=u)if(mb(u))i=u;else throw Error(`Invalid outputSchema for tool "${o.name}" at ${r}. Expected Record<string, z.ZodType>`);o.annotations={...o.annotations??{}},void 0===o.annotations.title&&(o.annotations.title=o.name),void 0===o._meta&&(o._meta={});let p=mf(r),m=!!(a=o._meta)&&"object"==typeof a&&"ui"in a&&"object"==typeof a.ui||p,h=o._meta;if(m){let e=`ui://app/${o.name}.html`;o._meta.ui||(o._meta.ui={}),o._meta.ui.resourceUri||(o._meta.ui.resourceUri=e);let t=function(e){let t={},r={};if(e.ui&&"object"==typeof e.ui){let a=e.ui,i={},n={};for(let[e,t]of Object.entries(a))mv.includes(e)?i[e]=t:m_.includes(e)?n[e]=t:i[e]=t;Object.keys(i).length>0&&(t.ui=i),Object.keys(n).length>0&&(r.ui=n)}for(let[r,a]of Object.entries(e))"ui"!==r&&(t[r]=a);return{toolMeta:t,resourceMeta:r}}(h);h=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"),mg.add(o.name,{name:o.name,uri:e,handler:s,mimeType:"text/html;profile=mcp-app",_meta:a,toolPath:p?r:void 0})}let f=my(h),g=m?f:void 0;n=mf(r)&&m?async(e,t)=>({content:[{type:"text",text:""}],_meta:g,structuredContent:{args:e}}):function(e,t,r,a="unknown-tool"){return async(i,n)=>{let o=e(i,function(e){let t=e.mcpReq.envelope,r=pX(t?.[ik]);if(!r)try{let e,t=pK();r=t.clientInfo??(e=t.headers,pX({name:pQ(e,"x-mcp-client-name"),version:pQ(e,"x-mcp-client-version"),title:pQ(e,"x-mcp-client-title"),websiteUrl:pQ(e,"x-mcp-client-website-url"),description:pQ(e,"x-mcp-client-description")}))}catch{}if(!r)try{r=pW().clientInfo}catch{}let a=function(e){if(!e)return;let t={};return e.headers.forEach((e,r)=>{t[r]=e}),t}(e.http?.req);return{signal:e.mcpReq.signal,authInfo:e.http?.authInfo,sessionId:e.sessionId,_meta:e.mcpReq._meta,requestId:e.mcpReq.id,requestInfo:a?{headers:a}:void 0,clientInfo:r,sendNotification:t=>e.mcpReq.notify(t),sendRequest:(t,r,a)=>e.mcpReq.send(t,r,a),elicit:(t,r)=>p8(e,t,r),sample:(t,r)=>mc(e,t,r),inputResponses:e.mcpReq.inputResponses,requestState:e.mcpReq.requestState}}(n));if(o instanceof Promise&&(o=await o),l$(o))return o;if("string"==typeof o||"number"==typeof o){if(r){let e=Object.entries(r);if(1===e.length){let[t,r]=e[0];try{return r.parse(o),{content:[{type:"text",text:"number"==typeof o?`${o}`:o}],structuredContent:{[t]:o}}}catch{}}}return mh(t)?{content:[{type:"text",text:""}],structuredContent:{args:i},_meta:t}:{content:[{type:"text",text:"number"==typeof o?`${o}`:o}]}}if(!r||!o||"object"!=typeof o||Array.isArray(o)||"structuredContent"in o||"content"in o&&Array.isArray(o.content)||"_meta"in o||"isError"in o||(mm(o,r,a,"returned data that does not match outputSchema"),o={structuredContent:o}),o&&"object"==typeof o&&"_meta"in o&&!("content"in o)&&!("structuredContent"in o)){let e=o._meta;if(mh(e))return{content:[{type:"text",text:""}],_meta:e}}if(!o||"object"!=typeof o){let e=null===o?"null":typeof o,t=void 0===o?"undefined":null===o?"null":"object"==typeof o?JSON.stringify(o,null,2):String(o);throw Error(`Tool handler must return a CallToolResult, string, or number. Got ${e}: ${t}
|
|
79
79
|
|
|
80
80
|
Expected CallToolResult format:
|
|
81
81
|
{
|
|
@@ -125,7 +125,7 @@ Or both for backwards compatibility:
|
|
|
125
125
|
{
|
|
126
126
|
content: [{ type: "text", text: "fallback" }],
|
|
127
127
|
structuredContent: { your: "data" }
|
|
128
|
-
}`)}if(c&&!s&&!l){let{isError:e,...t}=o,r=Object.keys(t).length>0?`Tool execution failed: ${JSON.stringify(t)}`:"Tool execution failed";o.content=[{type:"text",text:r}],s=!0}if(r&&l&&!c&&
|
|
128
|
+
}`)}if(c&&!s&&!l){let{isError:e,...t}=o,r=Object.keys(t).length>0?`Tool execution failed: ${JSON.stringify(t)}`:"Tool execution failed";o.content=[{type:"text",text:r}],s=!0}if(r&&l&&!c&&mm(o.structuredContent,r,a,"returned structuredContent that does not match outputSchema"),!s&&l&&(o.content=[{type:"text",text:JSON.stringify(o.structuredContent)}],s=!0),s)for(let e=0;e<o.content.length;e++){let t=o.content[e],r=mp(t);if(!r.valid)throw Error(`Invalid content item at index ${e}: ${r.error}
|
|
129
129
|
|
|
130
130
|
Content item: ${JSON.stringify(t,null,2)}
|
|
131
131
|
|
|
@@ -142,7 +142,7 @@ Expected format:
|
|
|
142
142
|
key: "value",
|
|
143
143
|
nested: { data: "here" }
|
|
144
144
|
}
|
|
145
|
-
}`)}}return o}}(s,g,i,o.name);let y={title:o.annotations?.title,description:o.description,inputSchema:pD(d),outputSchema:i?pD(i,{strict:!0}):void 0,annotations:o.annotations,_meta:f};e.registerTool(o.name,y,n)}),a.forEach((t,r)=>{let a=
|
|
145
|
+
}`)}}return o}}(s,g,i,o.name);let y={title:o.annotations?.title,description:o.description,inputSchema:pD(d),outputSchema:i?pD(i,{strict:!0}):void 0,annotations:o.annotations,_meta:f};e.registerTool(o.name,y,n)}),a.forEach((t,r)=>{let a=mS(r),i={name:a,title:a,description:"No description provided"},n={},{default:o,metadata:s,schema:l}=t;"object"==typeof s&&null!==s&&Object.assign(i,s);let c=function(e,t="assistant"){return async(r,a)=>{let i,n=e(r,a);if(n instanceof Promise&&(n=await n),"string"==typeof n||"number"==typeof n)i={type:"text",text:"number"==typeof n?`${n}`:n};else{let e=mp(n);if(e.valid)i=n;else{let t=null===n?"null":typeof n,r=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, or number. Got ${t}: ${r}
|
|
146
146
|
|
|
147
147
|
Validation error: ${e.error}
|
|
148
148
|
|
|
@@ -153,7 +153,7 @@ Expected formats:
|
|
|
153
153
|
- Image content: { type: "image", data: "base64data", mimeType: "image/jpeg" }
|
|
154
154
|
- Audio content: { type: "audio", data: "base64data", mimeType: "audio/mpeg" }
|
|
155
155
|
- Resource link: { type: "resource_link", name: "resource name", uri: "resource://uri" }
|
|
156
|
-
- 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");
|
|
156
|
+
- 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");mb(l)?Object.assign(n,l):null!=l&&console.warn(`Invalid schema for prompt "${i.name}" at ${r}. Expected Record<string, z.ZodType>`),e.registerPrompt(i.name,{title:i.title,description:i.description,argsSchema:pD(n)},c)}),[...mg.getAll()].forEach(([t,a])=>{let i=a.mimeType||"text/html;profile=mcp-app",n=a?._meta?my(a._meta):void 0,o={name:a.name,description:`Auto-generated resource for ${a.name} tool`,mimeType:a.mimeType,_meta:n},s=async(e,t)=>{if(a.mimeType&&a.toolPath)try{var n;let e,t,o=(n=a.toolPath,IS_CLOUDFLARE?function(e){let{normalizedPath:t,baseName:r}=mw(e),a=5381;for(let e=0;e<t.length;e++)a=Math.imul(a,33)+t.charCodeAt(e)>>>0;let i=a.toString(16).slice(0,6).padStart(6,"0");return`${r}_${i}`}(n):function(e){let{normalizedPath:t,baseName:a}=mw(e),i=r(6982).createHash("md5").update(t).digest("hex").slice(0,6);return`${a}_${i}`}(n)),s=function(e){if(INJECTED_CLIENT_BUNDLES)return INJECTED_CLIENT_BUNDLES[e]||null;if(!IS_CLOUDFLARE)try{let t=r(9896),a=r(6928);for(let r of[a.join(process.cwd(),"dist","client"),a.join(process.cwd(),"client")]){let i=a.join(r,`${e}.bundle.js`),n=a.join(r,`${e}.bundle.css`);if(t.existsSync(i)){let e,r=t.readFileSync(i,"utf-8");return t.existsSync(n)&&(e=t.readFileSync(n,"utf-8")),{js:r,css:e}}}}catch{}return null}(o);if(!s)throw Error(`React client bundle not found for "${a.name}" (bundle: "${o}").
|
|
157
157
|
React tool bundles are generated automatically when you run "xmcp build" (or "xmcp dev").
|
|
158
158
|
Please re-run the build so the framework can regenerate the bundle.`);let l=s.js,c=s.css,u=(e=`
|
|
159
159
|
<script type="module">
|
|
@@ -208,7 +208,7 @@ Please re-run the build so the framework can regenerate the bundle.`);let l=s.js
|
|
|
208
208
|
<div id="root"></div>
|
|
209
209
|
${e}
|
|
210
210
|
</body>
|
|
211
|
-
</html>`);return{contents:[{uri:a.uri,text:u,mimeType:i,_meta:a._meta}]}}catch(e){throw console.error(`React failed for ${a.name}:`,e),e}let o=a.handler({},t);if(o instanceof Promise&&(o=await o),"string"==typeof o)return{contents:[{uri:a.uri,text:o,mimeType:i,_meta:a._meta}]};if(o&&"object"==typeof o&&"_meta"in o&&!("content"in o))return{contents:[{uri:a.uri,text:"",mimeType:i,_meta:a._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:a.uri,text:e.text,mimeType:i,_meta:a._meta}]}}return{contents:[{uri:a.uri,text:"",mimeType:i,_meta:a._meta}]}};e.registerResource(a.name,a.uri,o,s)}),i.forEach((t,r)=>{let a={name:
|
|
211
|
+
</html>`);return{contents:[{uri:a.uri,text:u,mimeType:i,_meta:a._meta}]}}catch(e){throw console.error(`React failed for ${a.name}:`,e),e}let o=a.handler({},t);if(o instanceof Promise&&(o=await o),"string"==typeof o)return{contents:[{uri:a.uri,text:o,mimeType:i,_meta:a._meta}]};if(o&&"object"==typeof o&&"_meta"in o&&!("content"in o))return{contents:[{uri:a.uri,text:"",mimeType:i,_meta:a._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:a.uri,text:e.text,mimeType:i,_meta:a._meta}]}}return{contents:[{uri:a.uri,text:"",mimeType:i,_meta:a._meta}]}};e.registerResource(a.name,a.uri,o,s)}),i.forEach((t,r)=>{let a={name:mS(r),description:"No description provided"},{default:i,metadata:n,schema:o}=t;"object"==typeof n&&null!==n&&Object.assign(a,n);let s={};mb(o)?s=o:null!=o&&console.warn(`Invalid schema for resource "${a.name}" at ${r}. Expected Record<string, z.ZodType>`);let l=m$(r);if(!l)return void console.warn(`Skipping resource "${a.name}" at ${r}: Invalid file path format`);let c=l.uriTemplate;a.mimeType&&a.mimeType.includes("html")&&(c=c.endsWith(".html")?c:`${c}.html`);let u=function(e,t,r={}){let a=m$(t);if(!a)throw Error(`Invalid resource file path: ${t}. Must follow (scheme)/path/[param] convention.`);return async(t,i)=>{let n=e(function(e,t,r){let a={},i={};if(0===t.parameters.length)return i;let n=t.uriTemplate.split("://")[1]||"",o=e.split("://")[1]||"",s=n.split("/"),l=o.split("/");for(let e=0;e<s.length&&e<l.length;e++){let t=s[e],r=l[e],i=t.match(/^\{(.+)\}$/);i&&(a[i[1]]=r)}for(let e of t.parameters){let t=a[e],n=r[e];if(void 0===t)throw Error(`Missing required parameter: ${e}`);if(!n){i[e]=t;continue}try{i[e]=n.parse(t)}catch(r){throw Error(`Invalid parameter "${e}": ${t}. Validation error: ${r instanceof Error?r.message:String(r)}`)}}return i}(t.href,a,r),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}
|
|
212
212
|
|
|
213
213
|
Expected ReadResourceResult format:
|
|
214
214
|
{
|
|
@@ -217,4 +217,4 @@ Expected ReadResourceResult format:
|
|
|
217
217
|
{ uri: "resource://uri", mimeType: "application/json", text: "json content" },
|
|
218
218
|
{ uri: "resource://uri", blob: base64data }
|
|
219
219
|
]
|
|
220
|
-
}`)}return n.contents.forEach(e=>{e.uri||(e.uri=t.href)}),n}}(i,r,s);if("direct"===l.type)e.registerResource(a.name,c,a,u);else{let t=new u1(c,{list:void 0}),r=async(e,t,r)=>{let a={};for(let e of l.parameters){let r=t[e],i=s[e];if(void 0===r)throw Error(`Missing required parameter: ${e}. Available variables: ${Object.keys(t)}`);i?a[e]=i.parse(r):a[e]=r}let n=i(a,r);return n instanceof Promise&&(n=await n),"string"==typeof n?{contents:[{uri:e.href,text:n}]}:n};e.registerResource(a.name,t,a,r)}}),e}async function
|
|
220
|
+
}`)}return n.contents.forEach(e=>{e.uri||(e.uri=t.href)}),n}}(i,r,s);if("direct"===l.type)e.registerResource(a.name,c,a,u);else{let t=new u1(c,{list:void 0}),r=async(e,t,r)=>{let a={};for(let e of l.parameters){let r=t[e],i=s[e];if(void 0===r)throw Error(`Missing required parameter: ${e}. Available variables: ${Object.keys(t)}`);i?a[e]=i.parse(r):a[e]=r}let n=i(a,r);return n instanceof Promise&&(n=await n),"string"==typeof n?{contents:[{uri:e.href,text:n}]}:n};e.registerResource(a.name,t,a,r)}}),e}async function mM(){let{toolModules:e,skippedTools:t}=await mO(mN);return mC(t),e}async function mL(){let{promptModules:e,skippedPrompts:t}=await mR(mI);return mx(t),e}async function mZ(){let{resourceModules:e,skippedResources:t}=await mE(mq);return mT(t),e}async function mD(){let{instructions:e,...t}=mz,r=new u0(t,{instructions:e}),a=mM(),i=mL(),n=mZ(),[o,s,l]=await Promise.all([a,i,n]);return mA(r,o,s,l)}var mV=r(8583);r.n(mV)().config();let mU=STDIO_CONFIG.debug||!1;if(STDIO_CONFIG.silent){let e=new console.Console(process.stderr,process.stderr);for(let t of["log","debug","info","warn","error","dir","table","trace","assert","time","timeEnd","timeLog","count","countReset","group","groupEnd","groupCollapsed","clear"])console[t]=e[t].bind(e)}pY({clientInfo:void 0},()=>{let e;!function(e,t={}){let r,a=t.legacy??"serve",i=t.transport??new de,n={phase:"opening"},c=!1,u=()=>c||"closed"===n.phase,d=e=>{try{t.onerror?.(e)}catch{}},p=(e,t,r,a)=>i.send({jsonrpc:"2.0",id:e,error:{code:t,message:r,...void 0!==a&&{data:a}}}).catch(e=>d(dr(e))),m=new uB(t.maxSubscriptions??1024),h=e=>{if(!iJ.safeParse(e).success)return;let t=m.routeOutbound(e);if("passthrough"!==t){for(let e of t)i.send({jsonrpc:"2.0",...e}).catch(e=>d(dr(e)));return"handled"}},f=async e=>{if(lS(e)&&"subscriptions/listen"===e.method){let t,r=lg(e.params),a=ly(e.params)?(void 0===r?[]:l_(r))[0]:{key:"_meta",problem:"the per-request envelope is required on protocol revision 2026-07-28"},n=lv(e.params);if(void 0!==a)t={jsonrpc:"2.0",id:e.id,error:{code:-32602,message:`Invalid _meta envelope: ${a.key}: ${a.problem}`}};else if(void 0!==n&&sR.includes(n))t=m.serve(e);else{let r=new s9({supported:[...sR],requested:n??"unknown"});t={jsonrpc:"2.0",id:e.id,error:{code:r.code,message:r.message,data:r.data}}}return await i.send("error"in t?t:{jsonrpc:"2.0",method:t.method,params:t.params}).catch(e=>d(dr(e))),!0}if(iJ.safeParse(e).success&&"notifications/cancelled"===e.method){let t=e.params?.requestId;if(void 0!==t&&m.cancel(t))return!0}return!1},g=(e,t,r)=>{let a=function(e,t){switch(e.reason){case"http-method":return lT("http-method","modern-only-method-not-allowed",405,new s0(-32e3,"Method not allowed."),!0);case"batch":return lT("jsonrpc-shape","modern-only-batch-not-supported",400,new s0(sQ.InvalidRequest,"Bad Request: JSON-RPC batches are not supported by this endpoint"),!0);case"response":return lT("jsonrpc-shape","modern-only-response-post",400,new s0(sQ.InvalidRequest,"Bad Request: JSON-RPC responses cannot be posted to this endpoint"),!0);case"notification":return;case"initialize":case"no-claim":{let r=e.requestedVersion;return lT("era-classification","modern-only-missing-envelope",400,void 0===r?new s0(sQ.UnsupportedProtocolVersion,"Unsupported protocol version: the request did not name a protocol version",{supported:[...t]}):new s9({supported:[...t],requested:r}),!0)}}}({kind:"legacy",reason:t,...void 0!==r&&{requestedVersion:r}},sR);return void 0===a?Promise.resolve():(d(Error(`Rejected 2025-era request on a modern-only stdio connection (${a.cell}): ${a.message}`)),p(e.id,a.code,a.message,a.data))},y=async(t,a)=>{let n=await e({era:t}),u=n instanceof u0?n.server:n;"modern"===t&&(o(u,a),s(u,sR),m.setServerCapabilities(u.getCapabilities(),l(u)));let d=new dt(i,()=>{!c&&d!==r&&k()},"modern"===t?h:void 0);return await n.connect(d),{product:n,channel:d}},v=e=>e.product.close().catch(e=>d(dr(e))),_=async e=>{r=e.channel;try{await e.channel.whenRequestsAnswered(3e3)||d(Error("Discarded the probe instance with requests still unanswered after 3000ms; continuing with the fallback")),await e.product.close()}catch(e){d(dr(e))}finally{r=void 0}},b=async e=>{if("closed"===n.phase)return;if("pinned"===n.phase)return"modern"===n.era&&lS(e)&&"initialize"===e.method&&!lj(e.params)?void await g(e,"initialize",null!==e.params&&"object"==typeof e.params&&"string"==typeof e.params.protocolVersion?e.params.protocolVersion:void 0):void("modern"===n.era&&await f(e)||n.instance.channel.deliver(e));if(!lS(e)&&!iJ.safeParse(e).success)return void d(Error("Discarded a JSON-RPC response received before the connection negotiated an era"));let t=function(e){let t=e.params;if("initialize"===e.method&&!lj(t)){let e=null!==t&&"object"==typeof t&&"string"==typeof t.protocolVersion?t.protocolVersion:void 0;return{kind:"legacy",reason:"initialize",...void 0!==e&&{requestedVersion:e}}}if(!ly(t))return{kind:"legacy",reason:"no-claim"};let r=lg(t),a=(void 0===r?[]:l_(r))[0];if(void 0!==a)return{kind:"invalid-envelope",issue:a};let i=lv(t);return void 0!==i&&sR.includes(i)?{kind:"modern",revision:i,classification:{era:"modern",revision:i}}:{kind:"unsupported-revision",requested:i??"unknown"}}(e);switch(t.kind){case"invalid-envelope":{let r=`Invalid _meta envelope for protocol revision 2026-07-28: ${t.issue.key}: ${t.issue.problem}`;lS(e)?await p(e.id,sQ.InvalidParams,r,{envelope:t.issue}):d(Error(`Discarded a notification with a malformed envelope: ${r}`));return}case"unsupported-revision":if(lS(e)){let r=new s9({supported:[...sR],requested:t.requested});d(r),await p(e.id,r.code,r.message,r.data)}else d(Error(`Discarded a notification claiming unsupported protocol revision ${t.requested}`));return;case"modern":if(lS(e)&&"server/discover"===e.method){if("probe"===n.phase)return void n.instance.channel.deliver(e,{classification:t.classification});let r=await y("modern",t.revision);if(u())return void await v(r);n={phase:"probe",instance:r},r.channel.deliver(e,{classification:t.classification});return}if("probe"===n.phase){if(iJ.safeParse(e).success)return void n.instance.channel.deliver(e,{classification:t.classification});n={phase:"pinned",era:"modern",instance:n.instance}}else{let e=await y("modern",t.revision);if(u())return void await v(e);n={phase:"pinned",era:"modern",instance:e}}if(await f(e))return;n.instance.channel.deliver(e,{classification:t.classification});return;case"legacy":{if("reject"===a){lS(e)&&await g(e,t.reason,t.requestedVersion);return}if("probe"===n.phase){if(await _(n.instance),u())return;n={phase:"opening"}}let r=await y("legacy");if(u())return void await v(r);(n={phase:"pinned",era:"legacy",instance:r}).instance.channel.deliver(e);return}}},S=[],$=!1,w=async()=>{if(!$){$=!0;try{for(;S.length>0;){let e=S.shift();try{await b(e)}catch(t){lS(e)&&await p(e.id,sQ.InternalError,"Internal server error"),d(dr(t))}}}finally{$=!1}}},k=async()=>{if(c||"closed"===n.phase)return;c=!0;let e=n;for(let e of(n={phase:"closed"},m.teardownAll()))await i.send(e).catch(e=>d(dr(e)));("probe"===e.phase||"pinned"===e.phase)&&await e.instance.product.close().catch(e=>d(dr(e))),await i.close().catch(e=>d(dr(e)))};i.onmessage=e=>{S.push(e),w()},i.onerror=e=>{d(e),("probe"===n.phase||"pinned"===n.phase)&&n.instance.channel.onerror?.(e)},i.onclose=()=>{if(c||"closed"===n.phase)return;c=!0;let e=n;n={phase:"closed"},("probe"===e.phase||"pinned"===e.phase)&&e.instance.product.close().catch(e=>d(dr(e)))},i.start().catch(e=>{throw d(dr(e)),e}).catch(()=>{})}(async()=>{let e=await mD();return e.server.oninitialized=()=>{let t=pX(e.server.getClientVersion());pG({clientInfo:t}),mU&&t&&console.log(`[STDIO] MCP client initialized: ${t.name}@${t.version}`)},e},{legacy:"serve",onerror:mU?e=>console.error("[STDIO] Error:",e):void 0}),mU&&console.log("[STDIO] MCP Server running with STDIO transport"),e=()=>{mU&&console.log("[STDIO] Shutting down STDIO transport"),process.exit(0)},process.on("SIGINT",e),process.on("SIGTERM",e)})})(),{}})());
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { ServerContext } from "@modelcontextprotocol/server";
|
|
2
|
+
import type { SampleRequest, SampleResult, ToolRequestOptions } from "@/types/tool";
|
|
3
|
+
export declare function sampleFromTool(ctx: ServerContext, request: SampleRequest, options?: ToolRequestOptions): Promise<SampleResult>;
|
package/dist/types/tool.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { z } from "zod/v3";
|
|
2
2
|
import type { ZodType as ZodTypeV4, infer as inferV4 } from "zod";
|
|
3
|
-
import type { ElicitResult as McpElicitResult } from "@modelcontextprotocol/server";
|
|
3
|
+
import type { CreateMessageRequestParamsBase, CreateMessageResult, ElicitResult as McpElicitResult } from "@modelcontextprotocol/server";
|
|
4
4
|
import { UIMetadata } from "./ui-meta";
|
|
5
5
|
import type { McpClientInfo } from "./client-info";
|
|
6
6
|
export interface ToolAnnotations {
|
|
@@ -34,6 +34,8 @@ type InferCompatibleZodType<T extends CompatibleZodType> = T extends z.ZodTypeAn
|
|
|
34
34
|
export type ToolSchema = Record<string, CompatibleZodType>;
|
|
35
35
|
export type ToolOutputSchema = Record<string, CompatibleZodType>;
|
|
36
36
|
export type ElicitResult = McpElicitResult;
|
|
37
|
+
export type SampleRequest = Omit<CreateMessageRequestParamsBase, "task">;
|
|
38
|
+
export type SampleResult = CreateMessageResult;
|
|
37
39
|
export interface ToolRequestOptions {
|
|
38
40
|
/** Progress notification callback */
|
|
39
41
|
onprogress?: (progress: any) => void;
|
|
@@ -137,6 +139,8 @@ export interface ToolExtraArguments {
|
|
|
137
139
|
sendRequest: <U extends CompatibleZodType>(request: any, resultSchema: U, options?: ToolRequestOptions) => Promise<InferCompatibleZodType<U>>;
|
|
138
140
|
/** Requests user input from the connected client */
|
|
139
141
|
elicit: (request: ElicitRequest, options?: ToolRequestOptions) => Promise<ElicitResult>;
|
|
142
|
+
/** Requests an LLM completion from the connected client */
|
|
143
|
+
sample: (request: SampleRequest, options?: ToolRequestOptions) => Promise<SampleResult>;
|
|
140
144
|
/**
|
|
141
145
|
* Multi round-trip input responses carried by a retried request
|
|
142
146
|
* (protocol 2026-07-28). Read with `acceptedContent()` / `inputResponse()`
|