xmcp 0.6.7 → 0.6.9
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/cli.js +36 -15
- package/dist/compiler/config/index.d.ts +7 -0
- package/dist/compiler/config/schemas/template.d.ts +5 -0
- package/dist/host-bridge.d.ts +4 -0
- package/dist/host-bridge.js +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +5 -5
- package/dist/runtime/adapter-express.js +21 -19
- package/dist/runtime/adapter-nestjs.js +21 -19
- package/dist/runtime/adapter-nextjs.js +21 -19
- package/dist/runtime/contexts/client-info-context.d.ts +8 -0
- package/dist/runtime/http.js +26 -24
- package/dist/runtime/stdio.js +32 -30
- package/dist/runtime/utils/mcp-app-protocol.d.ts +14 -0
- package/dist/runtime/utils/mcp-app-types.d.ts +103 -0
- package/dist/runtime/utils/mcp-host-bridge.d.ts +43 -0
- package/dist/runtime/utils/server.d.ts +3 -1
- package/dist/types/ui-meta.d.ts +15 -0
- package/package.json +12 -1
- package/src/compiler/client/component-compiler.ts +26 -5
- package/src/compiler/config/injection.ts +1 -0
- package/src/compiler/config/schemas/template.ts +13 -0
- package/src/compiler/get-bundler-config/index.ts +1 -0
- package/src/host-bridge.ts +36 -0
- package/src/index.ts +36 -0
- package/src/runtime/adapters/nextjs/handler/server-lifecycle.ts +2 -1
- package/src/runtime/contexts/client-info-context.ts +16 -0
- package/src/runtime/transports/http/stateless-streamable-http.ts +11 -89
- package/src/runtime/transports/stdio/index.ts +40 -7
- package/src/runtime/utils/__tests__/client-info.test.ts +19 -0
- package/src/runtime/utils/__tests__/tool-extra.test.ts +39 -0
- package/src/runtime/utils/client-info.ts +7 -0
- package/src/runtime/utils/mcp-app-protocol.ts +16 -0
- package/src/runtime/utils/mcp-app-types.ts +113 -0
- package/src/runtime/utils/mcp-host-bridge.ts +473 -0
- package/src/runtime/utils/react/generate-html.ts +12 -4
- package/src/runtime/utils/server.ts +3 -2
- package/src/runtime/utils/transformers/tool.ts +10 -1
- package/src/runtime/utils/ui/__tests__/split-meta.test.ts +42 -0
- package/src/runtime/utils/ui/split-meta.ts +4 -1
- package/src/types/ui-meta.ts +17 -1
package/dist/runtime/http.js
CHANGED
|
@@ -27,13 +27,13 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
27
27
|
]))`;continue}else if("$"===r[e]){i+=`($|(?=[\r
|
|
28
28
|
]))`;continue}}if(a.s&&"."===r[e]){i+=o?`${r[e]}\r
|
|
29
29
|
`:`[${r[e]}\r
|
|
30
|
-
]`;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 cy(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===b.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((a,r)=>({...a,[r]:cw(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",r]})??s6(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let a={type:"object",additionalProperties:cw(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return a;if(e.keyType?._def.typeName===b.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=cd(e.keyType._def,t);return{...a,propertyNames:i}}if(e.keyType?._def.typeName===b.ZodEnum)return{...a,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===b.ZodBranded&&e.keyType._def.type._def.typeName===b.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=ce(e.keyType._def,t);return{...a,propertyNames:i}}return a}let cb={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"},cx=(e,t)=>{let a=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,a)=>cw(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 cw(e,t,a=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,a);if(i!==s8)return i}if(r&&!a){let e=c_(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 b.ZodString:return cd(e,a);case b.ZodNumber:let r={type:"number"};if(!e.checks)return r;for(let t of e.checks)switch(t.kind){case"int":r.type="integer",s3(r,"type",t.message,a);break;case"min":"jsonSchema7"===a.target?t.inclusive?s7(r,"minimum",t.value,t.message,a):s7(r,"exclusiveMinimum",t.value,t.message,a):(t.inclusive||(r.exclusiveMinimum=!0),s7(r,"minimum",t.value,t.message,a));break;case"max":"jsonSchema7"===a.target?t.inclusive?s7(r,"maximum",t.value,t.message,a):s7(r,"exclusiveMaximum",t.value,t.message,a):(t.inclusive||(r.exclusiveMaximum=!0),s7(r,"maximum",t.value,t.message,a));break;case"multipleOf":s7(r,"multipleOf",t.value,t.message,a)}return r;case b.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=cw(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 cw(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 b.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?s7(i,"minimum",t.value,t.message,a):s7(i,"exclusiveMinimum",t.value,t.message,a):(t.inclusive||(i.exclusiveMinimum=!0),s7(i,"minimum",t.value,t.message,a));break;case"max":"jsonSchema7"===a.target?t.inclusive?s7(i,"maximum",t.value,t.message,a):s7(i,"exclusiveMaximum",t.value,t.message,a):(t.inclusive||(i.exclusiveMaximum=!0),s7(i,"maximum",t.value,t.message,a));break;case"multipleOf":s7(i,"multipleOf",t.value,t.message,a)}return i;case b.ZodBoolean:return{type:"boolean"};case b.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":s7(s,"minimum",e.value,e.message,o);break;case"max":s7(s,"maximum",e.value,e.message,o)}return s}}(e,a);case b.ZodUndefined:return{not:s6(a)};case b.ZodNull:return"openApi3"===a.target?{enum:["null"],nullable:!0}:{type:"null"};case b.ZodArray:let n;return n={type:"array"},e.type?._def&&e.type?._def?.typeName!==b.ZodAny&&(n.items=cw(e.type._def,{...a,currentPath:[...a.currentPath,"items"]})),e.minLength&&s7(n,"minItems",e.minLength.value,e.minLength.message,a),e.maxLength&&s7(n,"maxItems",e.maxLength.value,e.maxLength.message,a),e.exactLength&&(s7(n,"minItems",e.exactLength.value,e.exactLength.message,a),s7(n,"maxItems",e.exactLength.value,e.exactLength.message,a)),n;case b.ZodUnion:case b.ZodDiscriminatedUnion:if("openApi3"===a.target)return cx(e,a);let o=e.options instanceof Map?Array.from(e.options.values()):e.options;if(o.every(e=>e._def.typeName in cb&&(!e._def.checks||!e._def.checks.length))){let e=o.reduce((e,t)=>{let a=cb[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 cx(e,a);case b.ZodIntersection:let s,c,l;return s=[cw(e.left._def,{...a,currentPath:[...a.currentPath,"allOf","0"]}),cw(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 b.ZodTuple:return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((e,t)=>cw(e._def,{...a,currentPath:[...a.currentPath,"items",`${t}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[]),additionalItems:cw(e.rest._def,{...a,currentPath:[...a.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,t)=>cw(e._def,{...a,currentPath:[...a.currentPath,"items",`${t}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[])};case b.ZodRecord:return cy(e,a);case b.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 b.ZodEnum:return{type:"string",enum:Array.from(e.values)};case b.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 b.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:cb[e.innerType._def.typeName],nullable:!0}:{type:[cb[e.innerType._def.typeName],"null"]};if("openApi3"===a.target){let t=cw(e.innerType._def,{...a,currentPath:[...a.currentPath]});return t&&"$ref"in t?{allOf:[t],nullable:!0}:t&&{...t,nullable:!0}}let f=cw(e.innerType._def,{...a,currentPath:[...a.currentPath,"anyOf","0"]});return f&&{anyOf:[f,{type:"null"}]};case b.ZodOptional:if(a.currentPath.toString()===a.propertyPath?.toString())return cw(e.innerType._def,a);let h=cw(e.innerType._def,{...a,currentPath:[...a.currentPath,"anyOf","1"]});return h?{anyOf:[{not:s6(a)},h]}:s6(a);case b.ZodMap:if("record"===a.mapStrategy)return cy(e,a);return{type:"array",maxItems:125,items:{type:"array",items:[cw(e.keyType._def,{...a,currentPath:[...a.currentPath,"items","items","0"]})||s6(a),cw(e.valueType._def,{...a,currentPath:[...a.currentPath,"items","items","1"]})||s6(a)],minItems:2,maxItems:2}};case b.ZodSet:let v;return v={type:"array",uniqueItems:!0,items:cw(e.valueType._def,{...a,currentPath:[...a.currentPath,"items"]})},e.minSize&&s7(v,"minItems",e.minSize.value,e.minSize.message,a),e.maxSize&&s7(v,"maxItems",e.maxSize.value,e.maxSize.message,a),v;case b.ZodLazy:return()=>e.getter()._def;case b.ZodPromise:return cw(e.type._def,a);case b.ZodNaN:case b.ZodNever:return"openAi"===a.target?void 0:{not:s6({...a,currentPath:[...a.currentPath,"not"]})};case b.ZodEffects:return"input"===a.effectStrategy?cw(e.schema._def,a):s6(a);case b.ZodAny:case b.ZodUnknown:return s6(a);case b.ZodDefault:return{...cw(e.innerType._def,a),default:e.defaultValue()};case b.ZodBranded:return ce(e,a);case b.ZodReadonly:case b.ZodCatch:return cw(e.innerType._def,a);case b.ZodPipeline:if("input"===a.pipeStrategy)return cw(e.in._def,a);if("output"===a.pipeStrategy)return cw(e.out._def,a);let g=cw(e.in._def,{...a,currentPath:[...a.currentPath,"allOf","0"]}),y=cw(e.out._def,{...a,currentPath:[...a.currentPath,"allOf",g?"1":"0"]});return{allOf:[g,y].filter(e=>void 0!==e)};case b.ZodFunction:case b.ZodVoid:case b.ZodSymbol:default:return}})(e,e.typeName,t),o="function"==typeof n?cw(n(),t):n;if(o&&ck(e,t,o),t.postProcess){let a=t.postProcess(o,e,t);return i.jsonSchema=o,a}return i.jsonSchema=o,o}let c_=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:s5(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`),s6(t);return"seen"===t.$refStrategy?s6(t):void 0}},ck=(e,t,a)=>(e.description&&(a.description=e.description,t.markdownDescription&&(a.markdownDescription=e.description)),a);function cE(e,t){if(ic(e)){var a;return function(e,t){if(e instanceof r1){let a=new ir(t),r={};for(let t of e._idmap.entries()){let[e,r]=t;a.process(r)}let i={},n={registry:e,uri:t?.uri,defs:r};for(let r of e._idmap.entries()){let[e,o]=r;i[e]=a.emit(o,{...t,external:n})}return Object.keys(r).length>0&&(i.__shared={["draft-2020-12"===a.target?"$defs":"definitions"]:r}),{schemas:i}}let a=new ir(t);return a.process(e),a.emit(e,t)}(e,{target:(a=t?.target)&&"jsonSchema7"!==a&&"draft-7"!==a&&("jsonSchema2019-09"===a||"draft-2020-12"===a)?"draft-2020-12":"draft-7",io:t?.pipeStrategy??"input"})}return((e,t)=>{let a,r,i=(r=void 0!==(a="string"==typeof t?{...s9,name:t}:{...s9,...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]:cw(a._def,{...i,currentPath:[...i.basePath,i.definitionPath,t]},!0)??s6(i)}),{}):void 0,o="string"==typeof t?t:t?.nameStrategy==="title"?void 0:t?.name,s=cw(e._def,void 0===o?i:{...i,currentPath:[...i.basePath,i.definitionPath,o]},!1)??s6(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,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function c$(e){let t=id(e),a=t?.method;if(!a)throw Error("Schema is missing a method literal");let r=iv(a);if("string"!=typeof r)throw Error("Schema method literal must be a string");return r}function cS(e,t){let a=ip(e,t);if(!a.success)throw a.error;return a.data}class cj{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(n3,e=>{this._oncancel(e)}),this.setNotificationHandler(og,e=>{this._onprogress(e)}),this.setRequestHandler(of,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(oS,async(e,t)=>{let a=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!a)throw new s1(_.InvalidParams,"Failed to retrieve task: Task not found");return{...a}}),this.setRequestHandler(oT,async(e,t)=>{let a=async()=>{let r=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(r,t.sessionId);){if("response"===e.type||"error"===e.type){let t=e.message,a=t.id,r=this._requestResolvers.get(a);if(r)this._requestResolvers.delete(a),r("response"===e.type?t:new s1(t.error.code,t.error.message,t.error.data));else{let t="response"===e.type?"Response":"Error";this._onerror(Error(`${t} handler missing for request ${a}`))}continue}await this._transport?.send(e.message,{relatedRequestId:t.requestId})}}let i=await this._taskStore.getTask(r,t.sessionId);if(!i)throw new s1(_.InvalidParams,`Task not found: ${r}`);if(!s2(i.status))return await this._waitForTaskUpdate(r,t.signal),await a();if(s2(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[nD]:{taskId:r}}}}return await a()};return await a()}),this.setRequestHandler(oO,async(e,t)=>{try{let{tasks:a,nextCursor:r}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:a,nextCursor:r,_meta:{}}}catch(e){throw new s1(_.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(oP,async(e,t)=>{try{let a=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!a)throw new s1(_.InvalidParams,`Task not found: ${e.params.taskId}`);if(s2(a.status))throw new s1(_.InvalidParams,`Cannot cancel task in terminal status: ${a.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,"cancelled","Client cancelled task execution.",t.sessionId),this._clearTaskQueue(e.params.taskId);let r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new s1(_.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){if(e instanceof s1)throw e;throw new s1(_.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;let t=this._requestHandlerAbortControllers.get(e.params.requestId);t?.abort(e.params.reason)}_setupTimeout(e,t,a,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:a,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let a=Date.now()-t.startTime;if(t.maxTotalTimeout&&a>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),s1.fromError(_.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:a});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let a=this.transport?.onerror;this._transport.onerror=e=>{a?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{if(r?.(e,t),n2.safeParse(e).success||n8.safeParse(e).success)this._onresponse(e);else if(n1(e))this._onrequest(e,t);else n4.safeParse(e).success?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;for(let e of(this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear(),this._requestHandlerAbortControllers.values()))e.abort();this._requestHandlerAbortControllers.clear();let t=s1.fromError(_.ConnectionClosed,"Connection closed");for(let a of(this._transport=void 0,this.onclose?.(),e.values()))a(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;void 0!==t&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let a,r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,i=this._transport,n=e.params?._meta?.[nD]?.taskId;if(void 0===r){let t={jsonrpc:"2.0",id:e.id,error:{code:_.MethodNotFound,message:"Method not found"}};n&&this._taskMessageQueue?this._enqueueTaskMessage(n,{type:"error",message:t,timestamp:Date.now()},i?.sessionId).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`))):i?.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)));return}let o=new AbortController;this._requestHandlerAbortControllers.set(e.id,o);let s=(a=e.params,nK.safeParse(a).success)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,i?.sessionId):void 0,l={signal:o.signal,sessionId:i?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(o.signal.aborted)return;let a={relatedRequestId:e.id};n&&(a.relatedTask={taskId:n}),await this.notification(t,a)},sendRequest:async(t,a,r)=>{if(o.signal.aborted)throw new s1(_.ConnectionClosed,"Request was cancelled");let i={...r,relatedRequestId:e.id};n&&!i.relatedTask&&(i.relatedTask={taskId:n});let s=i.relatedTask?.taskId??n;return s&&c&&await c.updateTaskStatus(s,"input_required"),await this.request(t,a,i)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:n,taskStore:c,taskRequestedTtl:s?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,l)).then(async t=>{if(o.signal.aborted)return;let a={result:t,jsonrpc:"2.0",id:e.id};n&&this._taskMessageQueue?await this._enqueueTaskMessage(n,{type:"response",message:a,timestamp:Date.now()},i?.sessionId):await i?.send(a)},async t=>{if(o.signal.aborted)return;let a={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:_.InternalError,message:t.message??"Internal error",...void 0!==t.data&&{data:t.data}}};n&&this._taskMessageQueue?await this._enqueueTaskMessage(n,{type:"error",message:a,timestamp:Date.now()},i?.sessionId):await i?.send(a)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...a}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i)return void this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));let n=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&n&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),n(e);return}i(a)}_onresponse(e){let t=Number(e.id),a=this._requestResolvers.get(t);if(a){this._requestResolvers.delete(t),a(n2.safeParse(e).success?e:new s1(e.error.code,e.error.message,e.error.data));return}let r=this._responseHandlers.get(t);if(void 0===r)return void this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));this._responseHandlers.delete(t),this._cleanupTimeout(t);let i=!1;if(n2.safeParse(e).success&&e.result&&"object"==typeof e.result){let a=e.result;if(a.task&&"object"==typeof a.task){let e=a.task;"string"==typeof e.taskId&&(i=!0,this._taskProgressTokens.set(e.taskId,t))}}i||this._progressHandlers.delete(t),r(n2.safeParse(e).success?e:s1.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}async *requestStream(e,t,a){let r,{task:i}=a??{};if(!i){try{let r=await this.request(e,t,a);yield{type:"result",result:r}}catch(e){yield{type:"error",error:e instanceof s1?e:new s1(_.InternalError,String(e))}}return}try{let i=await this.request(e,ok,a);if(i.task)r=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new s1(_.InternalError,"Task creation did not return a task");for(;;){let e=await this.getTask({taskId:r},a);if(yield{type:"taskStatus",task:e},s2(e.status)){if("completed"===e.status){let e=await this.getTaskResult({taskId:r},t,a);yield{type:"result",result:e}}else"failed"===e.status?yield{type:"error",error:new s1(_.InternalError,`Task ${r} failed`)}:"cancelled"===e.status&&(yield{type:"error",error:new s1(_.InternalError,`Task ${r} was cancelled`)});return}if("input_required"===e.status){let e=await this.getTaskResult({taskId:r},t,a);yield{type:"result",result:e};return}let i=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,i)),a?.signal?.throwIfAborted()}}catch(e){yield{type:"error",error:e instanceof s1?e:new s1(_.InternalError,String(e))}}}request(e,t,a){let{relatedRequestId:r,resumptionToken:i,onresumptiontoken:n,task:o,relatedTask:s}=a??{};return new Promise((c,l)=>{let p=e=>{l(e)};if(!this._transport)return void p(Error("Not connected"));if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),o&&this.assertTaskCapability(e.method)}catch(e){p(e);return}a?.signal?.throwIfAborted();let u=this._requestMessageId++,d={...e,jsonrpc:"2.0",id:u};a?.onprogress&&(this._progressHandlers.set(u,a.onprogress),d.params={...e.params,_meta:{...e.params?._meta||{},progressToken:u}}),o&&(d.params={...d.params,task:o}),s&&(d.params={...d.params,_meta:{...d.params?._meta||{},[nD]:s}});let m=e=>{this._responseHandlers.delete(u),this._progressHandlers.delete(u),this._cleanupTimeout(u),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:u,reason:String(e)}},{relatedRequestId:r,resumptionToken:i,onresumptiontoken:n}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),l(e instanceof s1?e:new s1(_.RequestTimeout,String(e)))};this._responseHandlers.set(u,e=>{if(!a?.signal?.aborted){if(e instanceof Error)return l(e);try{let a=ip(t,e.result);a.success?c(a.data):l(a.error)}catch(e){l(e)}}}),a?.signal?.addEventListener("abort",()=>{m(a?.signal?.reason)});let f=a?.timeout??6e4;this._setupTimeout(u,f,a?.maxTotalTimeout,()=>m(s1.fromError(_.RequestTimeout,"Request timed out",{timeout:f})),a?.resetTimeoutOnProgress??!1);let h=s?.taskId;if(h){let e=e=>{let t=this._responseHandlers.get(u);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${u}`))};this._requestResolvers.set(u,e),this._enqueueTaskMessage(h,{type:"request",message:d,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(u),l(e)})}else this._transport.send(d,{relatedRequestId:r,resumptionToken:i,onresumptiontoken:n}).catch(e=>{this._cleanupTimeout(u),l(e)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},oj,t)}async getTaskResult(e,t,a){return this.request({method:"tasks/result",params:e},t,a)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},oC,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},oA,t)}async notification(e,t){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(e.method);let a=t?.relatedTask?.taskId;if(a){let r={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[nD]:t.relatedTask}}};await this._enqueueTaskMessage(a,{type:"notification",message:r,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};t?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[nD]:t.relatedTask}}}),this._transport?.send(a,t).catch(e=>this._onerror(e))});return}let r={...e,jsonrpc:"2.0"};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[nD]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let a=c$(e);this.assertRequestHandlerCapability(a),this._requestHandlers.set(a,(a,r)=>Promise.resolve(t(cS(e,a),r)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let a=c$(e);this._notificationHandlers.set(a,a=>Promise.resolve(t(cS(e,a))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);void 0!==t&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,a){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,a,r)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){for(let a of(await this._taskMessageQueue.dequeueAll(e,t)))if("request"===a.type&&n1(a.message)){let t=a.message.id,r=this._requestResolvers.get(t);r?(r(new s1(_.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(t)):this._onerror(Error(`Resolver missing for request ${t} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let a=this._options?.defaultTaskPollInterval??1e3;try{let t=await this._taskStore?.getTask(e);t?.pollInterval&&(a=t.pollInterval)}catch{}return new Promise((e,r)=>{if(t.aborted)return void r(new s1(_.InvalidRequest,"Request cancelled"));let i=setTimeout(e,a);t.addEventListener("abort",()=>{clearTimeout(i),r(new s1(_.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){let a=this._taskStore;if(!a)throw Error("No task store configured");return{createTask:async r=>{if(!e)throw Error("No request provided");return await a.createTask(r,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let r=await a.getTask(e,t);if(!r)throw new s1(_.InvalidParams,"Failed to retrieve task: Task not found");return r},storeTaskResult:async(e,r,i)=>{await a.storeTaskResult(e,r,i,t);let n=await a.getTask(e,t);if(n){let t=o$.parse({method:"notifications/tasks/status",params:n});await this.notification(t),s2(n.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>a.getTaskResult(e,t),updateTaskStatus:async(e,r,i)=>{let n=await a.getTask(e,t);if(!n)throw new s1(_.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(s2(n.status))throw new s1(_.InvalidParams,`Cannot update task "${e}" from terminal status "${n.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await a.updateTaskStatus(e,r,i,t);let o=await a.getTask(e,t);if(o){let t=o$.parse({method:"notifications/tasks/status",params:o});await this.notification(t),s2(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>a.listTasks(e,t)}}}function cT(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}var cO=a(8825),cC=a(1712);class cP{constructor(e){this._ajv=e??function(){let e=new cO({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return cC(e),e}()}getValidator(e){let t="$id"in e&&"string"==typeof e.$id?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}}class cA{constructor(e){this._server=e}requestStream(e,t,a){return this._server.requestStream(e,t,a)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,a){return this._server.getTaskResult({taskId:e},t,a)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}}class cI extends cj{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(sm.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let a=this._loggingLevels.get(t);return!!a&&this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(a)},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new cP,this.setRequestHandler(ol,e=>this._oninitialize(e)),this.setNotificationHandler(om,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(sh,async(e,t)=>{let a=t.sessionId||t.requestInfo?.headers["mcp-session-id"]||void 0,{level:r}=e.params,i=sm.safeParse(r);return i.success&&this._loggingLevels.set(a,i.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new cA(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=function(e,t){let a={...e};for(let e in t){let r=t[e];if(void 0===r)continue;let i=a[e];cT(i)&&cT(r)?a[e]={...i,...r}:a[e]=r}return a}(this._capabilities,e)}setRequestHandler(e,t){let a,r=id(e),i=r?.method;if(!i)throw Error("Schema is missing a method literal");if(ic(i)){let e=i._zod?.def;a=e?.value??i.value}else{let e=i._def;a=e?.value??i.value}if("string"!=typeof a)throw Error("Schema method literal must be a string");if("tools/call"===a){let a=async(e,a)=>{let r=ip(su,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new s1(_.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,n=await Promise.resolve(t(e,a));if(i.task){let e=ip(ok,n);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new s1(_.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=ip(sl,n);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new s1(_.InvalidParams,`Invalid tools/call result: ${e}`)}return o.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`)}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`)}}assertTaskCapability(e){var t=this._clientCapabilities?.tasks?.requests,a="Client";if(!t)throw Error(`${a} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw Error(`${a} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw Error(`${a} does not support task creation for elicitation/create (required for ${e})`)}}assertTaskHandlerCapability(e){if(this._capabilities){var t=this._capabilities.tasks?.requests,a="Server";if(!t)throw Error(`${a} does not support task creation (required for ${e})`);if("tools/call"===e&&!t.tools?.call)throw Error(`${a} does not support task creation for tools/call (required for ${e})`)}}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:nM.includes(t)?t:nL,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},n5)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.");if(e.messages.length>0){let t=e.messages[e.messages.length-1],a=Array.isArray(t.content)?t.content:[t.content],r=a.some(e=>"tool_result"===e.type),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,n=i?Array.isArray(i.content)?i.content:[i.content]:[],o=n.some(e=>"tool_use"===e.type);if(r){if(a.some(e=>"tool_result"!==e.type))throw Error("The last message must contain only tool_result content if any is present");if(!o)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(o){let e=new Set(n.filter(e=>"tool_use"===e.type).map(e=>e.id)),t=new Set(a.filter(e=>"tool_result"===e.type).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},sT,t):this.request({method:"sampling/createMessage",params:e},sj,t)}async elicitInput(e,t){switch(e.mode??"form"){case"url":if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");return this.request({method:"elicitation/create",params:e},sB,t);case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let a="form"===e.mode?e:{...e,mode:"form"},r=await this.request({method:"elicitation/create",params:a},sB,t);if("accept"===r.action&&r.content&&a.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(a.requestedSchema)(r.content);if(!e.valid)throw new s1(_.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){if(e instanceof s1)throw e;throw new s1(_.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},sX,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}let cR=Symbol.for("mcp.completable");function cN(e){return!!e&&"object"==typeof e&&cR in e}(k||(k={})).Completable="McpCompletable";class cz{static isTemplate(e){return/\{[^}\s]+\}/.test(e)}static validateLength(e,t,a){if(e.length>t)throw Error(`${a} exceeds maximum length of ${t} characters (got ${e.length})`)}get variableNames(){return this.parts.flatMap(e=>"string"==typeof e?[]:e.names)}constructor(e){cz.validateLength(e,1e6,"Template"),this.template=e,this.parts=this.parse(e)}toString(){return this.template}parse(e){let t=[],a="",r=0,i=0;for(;r<e.length;)if("{"===e[r]){a&&(t.push(a),a="");let n=e.indexOf("}",r);if(-1===n)throw Error("Unclosed template expression");if(++i>1e4)throw Error("Template contains too many expressions (max 10000)");let o=e.slice(r+1,n),s=this.getOperator(o),c=o.includes("*"),l=this.getNames(o),p=l[0];for(let e of l)cz.validateLength(e,1e6,"Variable name");t.push({name:p,operator:s,names:l,exploded:c}),r=n+1}else a+=e[r],r++;return a&&t.push(a),t}getOperator(e){return["+","#",".","/","?","&"].find(t=>e.startsWith(t))||""}getNames(e){let t=this.getOperator(e);return e.slice(t.length).split(",").map(e=>e.replace("*","").trim()).filter(e=>e.length>0)}encodeValue(e,t){return(cz.validateLength(e,1e6,"Variable value"),"+"===t||"#"===t)?encodeURI(e):encodeURIComponent(e)}expandPart(e,t){if("?"===e.operator||"&"===e.operator){let a=e.names.map(a=>{let r=t[a];if(void 0===r)return"";let i=Array.isArray(r)?r.map(t=>this.encodeValue(t,e.operator)).join(","):this.encodeValue(r.toString(),e.operator);return`${a}=${i}`}).filter(e=>e.length>0);return 0===a.length?"":("?"===e.operator?"?":"&")+a.join("&")}if(e.names.length>1){let a=e.names.map(e=>t[e]).filter(e=>void 0!==e);return 0===a.length?"":a.map(e=>Array.isArray(e)?e[0]:e).join(",")}let a=t[e.name];if(void 0===a)return"";let r=(Array.isArray(a)?a:[a]).map(t=>this.encodeValue(t,e.operator));switch(e.operator){case"":case"+":default:return r.join(",");case"#":return"#"+r.join(",");case".":return"."+r.join(".");case"/":return"/"+r.join("/")}}expand(e){let t="",a=!1;for(let r of this.parts){if("string"==typeof r){t+=r;continue}let i=this.expandPart(r,e);i&&(("?"===r.operator||"&"===r.operator)&&a?t+=i.replace("?","&"):t+=i,("?"===r.operator||"&"===r.operator)&&(a=!0))}return t}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}partToRegExp(e){let t,a=[];for(let t of e.names)cz.validateLength(t,1e6,"Variable name");if("?"===e.operator||"&"===e.operator){for(let t=0;t<e.names.length;t++){let r=e.names[t],i=0===t?"\\"+e.operator:"&";a.push({pattern:i+this.escapeRegExp(r)+"=([^&]+)",name:r})}return a}let r=e.name;switch(e.operator){case"":t=e.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)";break;case"+":case"#":t="(.+)";break;case".":t="\\.([^/,]+)";break;case"/":t="/"+(e.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)");break;default:t="([^/]+)"}return a.push({pattern:t,name:r}),a}match(e){cz.validateLength(e,1e6,"URI");let t="^",a=[];for(let e of this.parts)if("string"==typeof e)t+=this.escapeRegExp(e);else for(let{pattern:r,name:i}of this.partToRegExp(e))t+=r,a.push({name:i,exploded:e.exploded});t+="$",cz.validateLength(t,1e6,"Generated regex pattern");let r=new RegExp(t),i=e.match(r);if(!i)return null;let n={};for(let e=0;e<a.length;e++){let{name:t,exploded:r}=a[e],o=i[e+1],s=t.replace("*","");r&&o.includes(",")?n[s]=o.split(","):n[s]=o}return n}}let cq=/^[A-Za-z0-9._-]{1,128}$/;function cL(e){let t=function(e){let t=[];if(0===e.length)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!cq.test(e)){let a=e.split("").filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,a)=>a.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${a.map(e=>`"${e}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}(e);var a=t.warnings;if(a.length>0){for(let t of(console.warn(`Tool name validation warning for "${e}":`),a))console.warn(` - ${t}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}return t.isValid}class cM{constructor(e){this._mcpServer=e}registerToolTask(e,t,a){let r={taskSupport:"required",...t.execution};if("forbidden"===r.taskSupport)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,r,t._meta,a)}}class cD{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new cI(e,t)}get experimental(){return this._experimental||(this._experimental={tasks:new cM(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(cV(ss)),this.server.assertCanSetRequestHandler(cV(su)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(ss,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let a,r={name:e,title:t.title,description:t.description,inputSchema:(a=im(t.inputSchema))?cE(a,{strictUnions:!0,pipeStrategy:"input"}):cU,annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=im(t.outputSchema);e&&(r.outputSchema=cE(e,{strictUnions:!0,pipeStrategy:"output"}))}return r})})),this.server.setRequestHandler(su,async(e,t)=>{try{let a=this._registeredTools[e.params.name];if(!a)throw new s1(_.InvalidParams,`Tool ${e.params.name} not found`);if(!a.enabled)throw new s1(_.InvalidParams,`Tool ${e.params.name} disabled`);let r=!!e.params.task,i=a.execution?.taskSupport,n="createTask"in a.handler;if(("required"===i||"optional"===i)&&!n)throw new s1(_.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if("required"===i&&!r)throw new s1(_.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if("optional"===i&&!r&&n)return await this.handleAutomaticTaskPolling(a,e,t);let o=await this.validateToolInput(a,e.params.arguments,e.params.name),s=await this.executeToolHandler(a,o,t);if(r)return s;return await this.validateToolOutput(a,s,e.params.name),s}catch(e){if(e instanceof s1&&e.code===_.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,t,a){if(!e.inputSchema)return;let r=im(e.inputSchema)??e.inputSchema,i=await iu(r,t);if(!i.success){let e=ih("error"in i?i.error:"Unknown error");throw new s1(_.InvalidParams,`Input validation error: Invalid arguments for tool ${a}: ${e}`)}return i.data}async validateToolOutput(e,t,a){if(!e.outputSchema||!("content"in t)||t.isError)return;if(!t.structuredContent)throw new s1(_.InvalidParams,`Output validation error: Tool ${a} has an output schema but no structured content was provided`);let r=im(e.outputSchema),i=await iu(r,t.structuredContent);if(!i.success){let e=ih("error"in i?i.error:"Unknown error");throw new s1(_.InvalidParams,`Output validation error: Invalid structured content for tool ${a}: ${e}`)}}async executeToolHandler(e,t,a){let r=e.handler;if("createTask"in r){if(!a.taskStore)throw Error("No task store provided.");let i={...a,taskStore:a.taskStore};return e.inputSchema?await Promise.resolve(r.createTask(t,i)):await Promise.resolve(r.createTask(i))}return e.inputSchema?await Promise.resolve(r(t,a)):await Promise.resolve(r(a))}async handleAutomaticTaskPolling(e,t,a){if(!a.taskStore)throw Error("No task store provided for task-capable tool.");let r=await this.validateToolInput(e,t.params.arguments,t.params.name),i=e.handler,n={...a,taskStore:a.taskStore},o=r?await Promise.resolve(i.createTask(r,n)):await Promise.resolve(i.createTask(n)),s=o.task.taskId,c=o.task,l=c.pollInterval??5e3;for(;"completed"!==c.status&&"failed"!==c.status&&"cancelled"!==c.status;){await new Promise(e=>setTimeout(e,l));let e=await a.taskStore.getTask(s);if(!e)throw new s1(_.InternalError,`Task ${s} not found during polling`);c=e}return await a.taskStore.getTaskResult(s)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(cV(sG)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(sG,async e=>{switch(e.params.ref.type){case"ref/prompt":if("ref/prompt"!==e.params.ref.type)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`);return this.handlePromptCompletion(e,e.params.ref);case"ref/resource":if("ref/resource"!==e.params.ref.type)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`);return this.handleResourceCompletion(e,e.params.ref);default:throw new s1(_.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,t){let a,r=this._registeredPrompts[t.name];if(!r)throw new s1(_.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new s1(_.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return cK;let i=id(r.argsSchema),n=i?.[e.params.argument.name];if(!cN(n))return cK;let o=(a=n[cR],a?.complete);return o?cJ(await o(e.params.argument.value,e.params.context)):cK}async handleResourceCompletion(e,t){let a=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!a){if(this._registeredResources[t.uri])return cK;throw new s1(_.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=a.resourceTemplate.completeCallback(e.params.argument.name);return r?cJ(await r(e.params.argument.value,e.params.context)):cK}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(cV(oF)),this.server.assertCanSetRequestHandler(cV(oZ)),this.server.assertCanSetRequestHandler(cV(oV)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(oF,async(e,t)=>{let a=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates))if(e.resourceTemplate.listCallback)for(let a of(await e.resourceTemplate.listCallback(t)).resources)r.push({...e.metadata,...a});return{resources:[...a,...r]}}),this.server.setRequestHandler(oZ,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(oV,async(e,t)=>{let a=new URL(e.params.uri),r=this._registeredResources[a.toString()];if(r){if(!r.enabled)throw new s1(_.InvalidParams,`Resource ${a} disabled`);return r.readCallback(a,t)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(a.toString());if(r)return e.readCallback(a,r,t)}throw new s1(_.InvalidParams,`Resource ${a} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(cV(o1)),this.server.assertCanSetRequestHandler(cV(o8)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(o1,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>{let a;return{name:e,title:t.title,description:t.description,arguments:t.argsSchema?(a=id(t.argsSchema))?Object.entries(a).map(([e,t])=>({name:e,description:t.description,required:!(ic(t)?t._zod?.def?.type==="optional":"function"==typeof t.isOptional?t.isOptional():t._def?.typeName==="ZodOptional")})):[]:void 0}})})),this.server.setRequestHandler(o8,async(e,t)=>{let a=this._registeredPrompts[e.params.name];if(!a)throw new s1(_.InvalidParams,`Prompt ${e.params.name} not found`);if(!a.enabled)throw new s1(_.InvalidParams,`Prompt ${e.params.name} disabled`);if(a.argsSchema){let r=im(a.argsSchema),i=await iu(r,e.params.arguments);if(!i.success){let t=ih("error"in i?i.error:"Unknown error");throw new s1(_.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let n=i.data,o=a.callback;return await Promise.resolve(o(n,t))}{let e=a.callback;return await Promise.resolve(e(t))}}),this._promptHandlersInitialized=!0)}resource(e,t,...a){let r;"object"==typeof a[0]&&(r=a.shift());let i=a[0];if("string"==typeof t){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let a=this._createRegisteredResource(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let a=this._createRegisteredResourceTemplate(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}registerResource(e,t,a,r){if("string"==typeof t){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,a.title,t,a,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,a.title,t,a,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,t,a,r,i){let n={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>n.update({enabled:!1}),enable:()=>n.update({enabled:!0}),remove:()=>n.update({uri:null}),update:e=>{void 0!==e.uri&&e.uri!==a&&(delete this._registeredResources[a],e.uri&&(this._registeredResources[e.uri]=n)),void 0!==e.name&&(n.name=e.name),void 0!==e.title&&(n.title=e.title),void 0!==e.metadata&&(n.metadata=e.metadata),void 0!==e.callback&&(n.readCallback=e.callback),void 0!==e.enabled&&(n.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[a]=n,n}_createRegisteredResourceTemplate(e,t,a,r,i){let n={resourceTemplate:a,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>n.update({enabled:!1}),enable:()=>n.update({enabled:!0}),remove:()=>n.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=n)),void 0!==t.title&&(n.title=t.title),void 0!==t.template&&(n.resourceTemplate=t.template),void 0!==t.metadata&&(n.metadata=t.metadata),void 0!==t.callback&&(n.readCallback=t.callback),void 0!==t.enabled&&(n.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=n;let o=a.uriTemplate.variableNames;return Array.isArray(o)&&o.some(e=>!!a.completeCallback(e))&&this.setCompletionRequestHandler(),n}_createRegisteredPrompt(e,t,a,r,i){let n={title:t,description:a,argsSchema:void 0===r?void 0:il(r),callback:i,enabled:!0,disable:()=>n.update({enabled:!1}),enable:()=>n.update({enabled:!0}),remove:()=>n.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=n)),void 0!==t.title&&(n.title=t.title),void 0!==t.description&&(n.description=t.description),void 0!==t.argsSchema&&(n.argsSchema=il(t.argsSchema)),void 0!==t.callback&&(n.callback=t.callback),void 0!==t.enabled&&(n.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=n,r&&Object.values(r).some(e=>cN(e instanceof nS?e._def?.innerType:e))&&this.setCompletionRequestHandler(),n}_createRegisteredTool(e,t,a,r,i,n,o,s,c){cL(e);let l={title:t,description:a,inputSchema:cB(r),outputSchema:cB(i),annotations:n,execution:o,_meta:s,handler:c,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&("string"==typeof t.name&&cL(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=l)),void 0!==t.title&&(l.title=t.title),void 0!==t.description&&(l.description=t.description),void 0!==t.paramsSchema&&(l.inputSchema=il(t.paramsSchema)),void 0!==t.outputSchema&&(l.outputSchema=il(t.outputSchema)),void 0!==t.callback&&(l.handler=t.callback),void 0!==t.annotations&&(l.annotations=t.annotations),void 0!==t._meta&&(l._meta=t._meta),void 0!==t.enabled&&(l.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...t){let a,r,i,n;if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);if("string"==typeof t[0]&&(a=t.shift()),t.length>1){let e=t[0];cH(e)?(r=t.shift(),t.length>1&&"object"==typeof t[0]&&null!==t[0]&&!cH(t[0])&&(n=t.shift())):"object"==typeof e&&null!==e&&(n=t.shift())}let o=t[0];return this._createRegisteredTool(e,void 0,a,r,i,n,{taskSupport:"forbidden"},void 0,o)}registerTool(e,t,a){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:n,outputSchema:o,annotations:s,_meta:c}=t;return this._createRegisteredTool(e,r,i,n,o,s,{taskSupport:"forbidden"},c,a)}prompt(e,...t){let a,r;if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);"string"==typeof t[0]&&(a=t.shift()),t.length>1&&(r=t.shift());let i=t[0],n=this._createRegisteredPrompt(e,void 0,a,r,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),n}registerPrompt(e,t,a){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:n}=t,o=this._createRegisteredPrompt(e,r,i,n,a);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}isConnected(){return void 0!==this.server.transport}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}}class cF{constructor(e,t){this._callbacks=t,this._uriTemplate="string"==typeof e?new cz(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}}let cU={type:"object",properties:{}};function cZ(e){return null!==e&&"object"==typeof e&&"parse"in e&&"function"==typeof e.parse&&"safeParse"in e&&"function"==typeof e.safeParse}function cH(e){return"object"==typeof e&&null!==e&&!("_def"in e||"_zod"in e||cZ(e))&&(0===Object.keys(e).length||Object.values(e).some(cZ))}function cB(e){if(e)return cH(e)?il(e):e}function cV(e){let t=id(e),a=t?.method;if(!a)throw Error("Schema is missing a method literal");let r=iv(a);if("string"==typeof r)return r;throw Error("Schema method literal must be a string")}function cJ(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}let cK={completion:{values:[],hasMore:!1}};var cG=a(290);let cW=(e,t)=>{globalThis[e]=t},cY=e=>globalThis[e];function cQ({name:e}){let t=Symbol.for(`xmcp-context-${e}`),a=Symbol.for(`xmcp-context-${e}-fallback-store`);if(cY(t))return cY(t);let r=new cG.AsyncLocalStorage,i=globalThis[a]??{current:null};cW(a,i);let n={provider:(e,t)=>(i.current=e,r.run(e,t)),getContext:()=>{let t=r.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 a=r.getStore()??i.current;if(!a)throw Error(`setContext() can only be used within the ${e} context.`);Object.assign(a,t)}};return cW(t,n),n}let cX=cQ({name:"http-request-context"}),c0=cX.setContext,c1=cX.getContext,c4=cX.provider,c2=new Set(["message","mode","requestedSchema"]),c8=new Set(["elicitationId","message","mode","url"]),c9=new Set(["properties","required","type"]),c5=new Set(["default","description","format","maxLength","minLength","title","type"]),c6=new Set(["default","description","enum","enumNames","title","type"]),c3=new Set(["default","description","title","type"]),c7=new Set(["default","description","maximum","minimum","title","type"]),le=new Set(["date","date-time","email","uri"]);async function lt(e,t,a){let r=function(e){let t=e.mode??"form";if("url"===t)return function(e){let t;lr(e,"Elicitation request must be a plain object."),la(e,c8,"URL elicitation"),li(e.message,"URL elicitation requires a string message."),ln(e.elicitationId,"URL elicitation requires a non-empty elicitationId."),ln(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),sD.parse(e);if("form"!==t)throw Error(`Unsupported elicitation mode "${String(e.mode)}". Expected "form" or "url".`);return function(e){lr(e,"Elicitation request must be a plain object."),la(e,c2,"Form elicitation"),li(e.message,"Form elicitation requires a string message.");let t=e.requestedSchema;if(lr(t,"Form elicitation requires a flat object schema."),la(t,c9,"Form elicitation schema"),"object"!==t.type)throw Error('Form elicitation schema must use type "object".');for(let[e,a]of(lr(t.properties,"Form elicitation schema requires a properties object."),Object.entries(t.properties)))!function(e,t){if(lr(t,`Form elicitation field "${e}" must be a plain object.`),lo(t.title,`Form elicitation field "${e}" title must be a string.`),lo(t.description,`Form elicitation field "${e}" description must be a string.`),"string"===t.type&&"enum"in t){var a,r;if(la(t,c6,`Form elicitation field "${e}"`),lc(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&&lc(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(lo(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)){la(t,c5,`Form elicitation field "${e}"`),ls(t.minLength,`Form elicitation field "${e}" minLength must be a number.`),ls(t.maxLength,`Form elicitation field "${e}" maxLength must be a number.`),lo(t.default,`Form elicitation field "${e}" default must be a string.`);let a=t.format;if(lo(a,`Form elicitation field "${e}" format must be a string.`),void 0!==a&&!le.has(a))throw Error(`Form elicitation field "${e}" format must be one of: ${Array.from(le).join(", ")}.`);return}if("boolean"===t.type){if(la(t,c3,`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){la(t,c7,`Form elicitation field "${e}"`),ls(t.minimum,`Form elicitation field "${e}" minimum must be a number.`),ls(t.maximum,`Form elicitation field "${e}" maximum must be a number.`),ls(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),sM.parse({...e,mode:"form"})}(t),i=await e.sendRequest({method:"elicitation/create",params:r},sB,a);return{...i,content:i.content??void 0}}function la(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 lr(e,t){if("object"!=typeof e||null===e||Array.isArray(e))throw Error(t)}function li(e,t){if("string"!=typeof e)throw Error(t)}function ln(e,t){if("string"!=typeof e||0===e.trim().length)throw Error(t)}function lo(e,t){if(void 0!==e&&"string"!=typeof e)throw Error(t)}function ls(e,t){if(void 0!==e&&"number"!=typeof e)throw Error(t)}function lc(e,t){if(!Array.isArray(e)||e.some(e=>"string"!=typeof e))throw Error(t)}let ll={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 lp(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=ll[e.type];return t?t(e):{valid:!0}}function lu(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 ld(e){return!!(e&&"object"==typeof e&&Object.keys(e).some(e=>e.startsWith("ui/")))}function lm(e){return e.endsWith(".tsx")}let lf=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 lh(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 lv=["ui/resourceUri"],lg=["prefersBorder","domain","csp","connectDomains","resourceDomains"];function ly(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 lb(e){return(e.split("/").pop()||e).replace(/\.[^/.]+$/,"")}function lx(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 lw(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 l_(e){return Error(`[xmcp] Invalid prompt file: ${e}
|
|
31
|
-
-> Default export must be a prompt handler function.`)}async function
|
|
32
|
-
-> ${a}`)});let i=a.length;e.warn(`[xmcp] ${i} prompt${1===i?"":"s"} skipped due to empty files or missing default exports`)}}();function
|
|
33
|
-
-> Default export must be a resource handler function.`)}async function
|
|
34
|
-
-> ${a}`)});let i=a.length;e.warn(`[xmcp] ${i} resource${1===i?"":"s"} skipped due to empty files or missing default exports`)}}();function
|
|
35
|
-
-> Default export must be a tool handler function.`)}async function
|
|
36
|
-
-> ${a}`)});let i=a.length;e.warn(`[xmcp] ${i} tool${1===i?"":"s"} skipped due to empty files or missing default exports`)}}(),
|
|
30
|
+
]`;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 cy(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===b.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((a,r)=>({...a,[r]:cw(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",r]})??s6(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let a={type:"object",additionalProperties:cw(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return a;if(e.keyType?._def.typeName===b.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=cd(e.keyType._def,t);return{...a,propertyNames:i}}if(e.keyType?._def.typeName===b.ZodEnum)return{...a,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===b.ZodBranded&&e.keyType._def.type._def.typeName===b.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=ce(e.keyType._def,t);return{...a,propertyNames:i}}return a}let cb={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"},cx=(e,t)=>{let a=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,a)=>cw(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 cw(e,t,a=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,a);if(i!==s8)return i}if(r&&!a){let e=c_(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 b.ZodString:return cd(e,a);case b.ZodNumber:let r={type:"number"};if(!e.checks)return r;for(let t of e.checks)switch(t.kind){case"int":r.type="integer",s3(r,"type",t.message,a);break;case"min":"jsonSchema7"===a.target?t.inclusive?s7(r,"minimum",t.value,t.message,a):s7(r,"exclusiveMinimum",t.value,t.message,a):(t.inclusive||(r.exclusiveMinimum=!0),s7(r,"minimum",t.value,t.message,a));break;case"max":"jsonSchema7"===a.target?t.inclusive?s7(r,"maximum",t.value,t.message,a):s7(r,"exclusiveMaximum",t.value,t.message,a):(t.inclusive||(r.exclusiveMaximum=!0),s7(r,"maximum",t.value,t.message,a));break;case"multipleOf":s7(r,"multipleOf",t.value,t.message,a)}return r;case b.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=cw(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 cw(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 b.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?s7(i,"minimum",t.value,t.message,a):s7(i,"exclusiveMinimum",t.value,t.message,a):(t.inclusive||(i.exclusiveMinimum=!0),s7(i,"minimum",t.value,t.message,a));break;case"max":"jsonSchema7"===a.target?t.inclusive?s7(i,"maximum",t.value,t.message,a):s7(i,"exclusiveMaximum",t.value,t.message,a):(t.inclusive||(i.exclusiveMaximum=!0),s7(i,"maximum",t.value,t.message,a));break;case"multipleOf":s7(i,"multipleOf",t.value,t.message,a)}return i;case b.ZodBoolean:return{type:"boolean"};case b.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":s7(s,"minimum",e.value,e.message,o);break;case"max":s7(s,"maximum",e.value,e.message,o)}return s}}(e,a);case b.ZodUndefined:return{not:s6(a)};case b.ZodNull:return"openApi3"===a.target?{enum:["null"],nullable:!0}:{type:"null"};case b.ZodArray:let n;return n={type:"array"},e.type?._def&&e.type?._def?.typeName!==b.ZodAny&&(n.items=cw(e.type._def,{...a,currentPath:[...a.currentPath,"items"]})),e.minLength&&s7(n,"minItems",e.minLength.value,e.minLength.message,a),e.maxLength&&s7(n,"maxItems",e.maxLength.value,e.maxLength.message,a),e.exactLength&&(s7(n,"minItems",e.exactLength.value,e.exactLength.message,a),s7(n,"maxItems",e.exactLength.value,e.exactLength.message,a)),n;case b.ZodUnion:case b.ZodDiscriminatedUnion:if("openApi3"===a.target)return cx(e,a);let o=e.options instanceof Map?Array.from(e.options.values()):e.options;if(o.every(e=>e._def.typeName in cb&&(!e._def.checks||!e._def.checks.length))){let e=o.reduce((e,t)=>{let a=cb[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 cx(e,a);case b.ZodIntersection:let s,c,l;return s=[cw(e.left._def,{...a,currentPath:[...a.currentPath,"allOf","0"]}),cw(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 b.ZodTuple:return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((e,t)=>cw(e._def,{...a,currentPath:[...a.currentPath,"items",`${t}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[]),additionalItems:cw(e.rest._def,{...a,currentPath:[...a.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,t)=>cw(e._def,{...a,currentPath:[...a.currentPath,"items",`${t}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[])};case b.ZodRecord:return cy(e,a);case b.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 b.ZodEnum:return{type:"string",enum:Array.from(e.values)};case b.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 b.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:cb[e.innerType._def.typeName],nullable:!0}:{type:[cb[e.innerType._def.typeName],"null"]};if("openApi3"===a.target){let t=cw(e.innerType._def,{...a,currentPath:[...a.currentPath]});return t&&"$ref"in t?{allOf:[t],nullable:!0}:t&&{...t,nullable:!0}}let f=cw(e.innerType._def,{...a,currentPath:[...a.currentPath,"anyOf","0"]});return f&&{anyOf:[f,{type:"null"}]};case b.ZodOptional:if(a.currentPath.toString()===a.propertyPath?.toString())return cw(e.innerType._def,a);let h=cw(e.innerType._def,{...a,currentPath:[...a.currentPath,"anyOf","1"]});return h?{anyOf:[{not:s6(a)},h]}:s6(a);case b.ZodMap:if("record"===a.mapStrategy)return cy(e,a);return{type:"array",maxItems:125,items:{type:"array",items:[cw(e.keyType._def,{...a,currentPath:[...a.currentPath,"items","items","0"]})||s6(a),cw(e.valueType._def,{...a,currentPath:[...a.currentPath,"items","items","1"]})||s6(a)],minItems:2,maxItems:2}};case b.ZodSet:let v;return v={type:"array",uniqueItems:!0,items:cw(e.valueType._def,{...a,currentPath:[...a.currentPath,"items"]})},e.minSize&&s7(v,"minItems",e.minSize.value,e.minSize.message,a),e.maxSize&&s7(v,"maxItems",e.maxSize.value,e.maxSize.message,a),v;case b.ZodLazy:return()=>e.getter()._def;case b.ZodPromise:return cw(e.type._def,a);case b.ZodNaN:case b.ZodNever:return"openAi"===a.target?void 0:{not:s6({...a,currentPath:[...a.currentPath,"not"]})};case b.ZodEffects:return"input"===a.effectStrategy?cw(e.schema._def,a):s6(a);case b.ZodAny:case b.ZodUnknown:return s6(a);case b.ZodDefault:return{...cw(e.innerType._def,a),default:e.defaultValue()};case b.ZodBranded:return ce(e,a);case b.ZodReadonly:case b.ZodCatch:return cw(e.innerType._def,a);case b.ZodPipeline:if("input"===a.pipeStrategy)return cw(e.in._def,a);if("output"===a.pipeStrategy)return cw(e.out._def,a);let g=cw(e.in._def,{...a,currentPath:[...a.currentPath,"allOf","0"]}),y=cw(e.out._def,{...a,currentPath:[...a.currentPath,"allOf",g?"1":"0"]});return{allOf:[g,y].filter(e=>void 0!==e)};case b.ZodFunction:case b.ZodVoid:case b.ZodSymbol:default:return}})(e,e.typeName,t),o="function"==typeof n?cw(n(),t):n;if(o&&ck(e,t,o),t.postProcess){let a=t.postProcess(o,e,t);return i.jsonSchema=o,a}return i.jsonSchema=o,o}let c_=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:s5(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`),s6(t);return"seen"===t.$refStrategy?s6(t):void 0}},ck=(e,t,a)=>(e.description&&(a.description=e.description,t.markdownDescription&&(a.markdownDescription=e.description)),a);function cE(e,t){if(ic(e)){var a;return function(e,t){if(e instanceof r1){let a=new ir(t),r={};for(let t of e._idmap.entries()){let[e,r]=t;a.process(r)}let i={},n={registry:e,uri:t?.uri,defs:r};for(let r of e._idmap.entries()){let[e,o]=r;i[e]=a.emit(o,{...t,external:n})}return Object.keys(r).length>0&&(i.__shared={["draft-2020-12"===a.target?"$defs":"definitions"]:r}),{schemas:i}}let a=new ir(t);return a.process(e),a.emit(e,t)}(e,{target:(a=t?.target)&&"jsonSchema7"!==a&&"draft-7"!==a&&("jsonSchema2019-09"===a||"draft-2020-12"===a)?"draft-2020-12":"draft-7",io:t?.pipeStrategy??"input"})}return((e,t)=>{let a,r,i=(r=void 0!==(a="string"==typeof t?{...s9,name:t}:{...s9,...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]:cw(a._def,{...i,currentPath:[...i.basePath,i.definitionPath,t]},!0)??s6(i)}),{}):void 0,o="string"==typeof t?t:t?.nameStrategy==="title"?void 0:t?.name,s=cw(e._def,void 0===o?i:{...i,currentPath:[...i.basePath,i.definitionPath,o]},!1)??s6(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,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function c$(e){let t=id(e),a=t?.method;if(!a)throw Error("Schema is missing a method literal");let r=iv(a);if("string"!=typeof r)throw Error("Schema method literal must be a string");return r}function cS(e,t){let a=ip(e,t);if(!a.success)throw a.error;return a.data}class cj{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(n3,e=>{this._oncancel(e)}),this.setNotificationHandler(og,e=>{this._onprogress(e)}),this.setRequestHandler(of,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(oS,async(e,t)=>{let a=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!a)throw new s1(_.InvalidParams,"Failed to retrieve task: Task not found");return{...a}}),this.setRequestHandler(oT,async(e,t)=>{let a=async()=>{let r=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(r,t.sessionId);){if("response"===e.type||"error"===e.type){let t=e.message,a=t.id,r=this._requestResolvers.get(a);if(r)this._requestResolvers.delete(a),r("response"===e.type?t:new s1(t.error.code,t.error.message,t.error.data));else{let t="response"===e.type?"Response":"Error";this._onerror(Error(`${t} handler missing for request ${a}`))}continue}await this._transport?.send(e.message,{relatedRequestId:t.requestId})}}let i=await this._taskStore.getTask(r,t.sessionId);if(!i)throw new s1(_.InvalidParams,`Task not found: ${r}`);if(!s2(i.status))return await this._waitForTaskUpdate(r,t.signal),await a();if(s2(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[nD]:{taskId:r}}}}return await a()};return await a()}),this.setRequestHandler(oO,async(e,t)=>{try{let{tasks:a,nextCursor:r}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:a,nextCursor:r,_meta:{}}}catch(e){throw new s1(_.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(oP,async(e,t)=>{try{let a=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!a)throw new s1(_.InvalidParams,`Task not found: ${e.params.taskId}`);if(s2(a.status))throw new s1(_.InvalidParams,`Cannot cancel task in terminal status: ${a.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,"cancelled","Client cancelled task execution.",t.sessionId),this._clearTaskQueue(e.params.taskId);let r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new s1(_.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){if(e instanceof s1)throw e;throw new s1(_.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;let t=this._requestHandlerAbortControllers.get(e.params.requestId);t?.abort(e.params.reason)}_setupTimeout(e,t,a,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:a,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let a=Date.now()-t.startTime;if(t.maxTotalTimeout&&a>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),s1.fromError(_.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:a});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let a=this.transport?.onerror;this._transport.onerror=e=>{a?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{if(r?.(e,t),n2.safeParse(e).success||n8.safeParse(e).success)this._onresponse(e);else if(n1(e))this._onrequest(e,t);else n4.safeParse(e).success?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;for(let e of(this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear(),this._requestHandlerAbortControllers.values()))e.abort();this._requestHandlerAbortControllers.clear();let t=s1.fromError(_.ConnectionClosed,"Connection closed");for(let a of(this._transport=void 0,this.onclose?.(),e.values()))a(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;void 0!==t&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let a,r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,i=this._transport,n=e.params?._meta?.[nD]?.taskId;if(void 0===r){let t={jsonrpc:"2.0",id:e.id,error:{code:_.MethodNotFound,message:"Method not found"}};n&&this._taskMessageQueue?this._enqueueTaskMessage(n,{type:"error",message:t,timestamp:Date.now()},i?.sessionId).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`))):i?.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)));return}let o=new AbortController;this._requestHandlerAbortControllers.set(e.id,o);let s=(a=e.params,nK.safeParse(a).success)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,i?.sessionId):void 0,l={signal:o.signal,sessionId:i?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(o.signal.aborted)return;let a={relatedRequestId:e.id};n&&(a.relatedTask={taskId:n}),await this.notification(t,a)},sendRequest:async(t,a,r)=>{if(o.signal.aborted)throw new s1(_.ConnectionClosed,"Request was cancelled");let i={...r,relatedRequestId:e.id};n&&!i.relatedTask&&(i.relatedTask={taskId:n});let s=i.relatedTask?.taskId??n;return s&&c&&await c.updateTaskStatus(s,"input_required"),await this.request(t,a,i)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:n,taskStore:c,taskRequestedTtl:s?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,l)).then(async t=>{if(o.signal.aborted)return;let a={result:t,jsonrpc:"2.0",id:e.id};n&&this._taskMessageQueue?await this._enqueueTaskMessage(n,{type:"response",message:a,timestamp:Date.now()},i?.sessionId):await i?.send(a)},async t=>{if(o.signal.aborted)return;let a={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:_.InternalError,message:t.message??"Internal error",...void 0!==t.data&&{data:t.data}}};n&&this._taskMessageQueue?await this._enqueueTaskMessage(n,{type:"error",message:a,timestamp:Date.now()},i?.sessionId):await i?.send(a)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...a}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i)return void this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));let n=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&n&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),n(e);return}i(a)}_onresponse(e){let t=Number(e.id),a=this._requestResolvers.get(t);if(a){this._requestResolvers.delete(t),a(n2.safeParse(e).success?e:new s1(e.error.code,e.error.message,e.error.data));return}let r=this._responseHandlers.get(t);if(void 0===r)return void this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));this._responseHandlers.delete(t),this._cleanupTimeout(t);let i=!1;if(n2.safeParse(e).success&&e.result&&"object"==typeof e.result){let a=e.result;if(a.task&&"object"==typeof a.task){let e=a.task;"string"==typeof e.taskId&&(i=!0,this._taskProgressTokens.set(e.taskId,t))}}i||this._progressHandlers.delete(t),r(n2.safeParse(e).success?e:s1.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}async *requestStream(e,t,a){let r,{task:i}=a??{};if(!i){try{let r=await this.request(e,t,a);yield{type:"result",result:r}}catch(e){yield{type:"error",error:e instanceof s1?e:new s1(_.InternalError,String(e))}}return}try{let i=await this.request(e,ok,a);if(i.task)r=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new s1(_.InternalError,"Task creation did not return a task");for(;;){let e=await this.getTask({taskId:r},a);if(yield{type:"taskStatus",task:e},s2(e.status)){if("completed"===e.status){let e=await this.getTaskResult({taskId:r},t,a);yield{type:"result",result:e}}else"failed"===e.status?yield{type:"error",error:new s1(_.InternalError,`Task ${r} failed`)}:"cancelled"===e.status&&(yield{type:"error",error:new s1(_.InternalError,`Task ${r} was cancelled`)});return}if("input_required"===e.status){let e=await this.getTaskResult({taskId:r},t,a);yield{type:"result",result:e};return}let i=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,i)),a?.signal?.throwIfAborted()}}catch(e){yield{type:"error",error:e instanceof s1?e:new s1(_.InternalError,String(e))}}}request(e,t,a){let{relatedRequestId:r,resumptionToken:i,onresumptiontoken:n,task:o,relatedTask:s}=a??{};return new Promise((c,l)=>{let p=e=>{l(e)};if(!this._transport)return void p(Error("Not connected"));if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),o&&this.assertTaskCapability(e.method)}catch(e){p(e);return}a?.signal?.throwIfAborted();let u=this._requestMessageId++,d={...e,jsonrpc:"2.0",id:u};a?.onprogress&&(this._progressHandlers.set(u,a.onprogress),d.params={...e.params,_meta:{...e.params?._meta||{},progressToken:u}}),o&&(d.params={...d.params,task:o}),s&&(d.params={...d.params,_meta:{...d.params?._meta||{},[nD]:s}});let m=e=>{this._responseHandlers.delete(u),this._progressHandlers.delete(u),this._cleanupTimeout(u),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:u,reason:String(e)}},{relatedRequestId:r,resumptionToken:i,onresumptiontoken:n}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),l(e instanceof s1?e:new s1(_.RequestTimeout,String(e)))};this._responseHandlers.set(u,e=>{if(!a?.signal?.aborted){if(e instanceof Error)return l(e);try{let a=ip(t,e.result);a.success?c(a.data):l(a.error)}catch(e){l(e)}}}),a?.signal?.addEventListener("abort",()=>{m(a?.signal?.reason)});let f=a?.timeout??6e4;this._setupTimeout(u,f,a?.maxTotalTimeout,()=>m(s1.fromError(_.RequestTimeout,"Request timed out",{timeout:f})),a?.resetTimeoutOnProgress??!1);let h=s?.taskId;if(h){let e=e=>{let t=this._responseHandlers.get(u);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${u}`))};this._requestResolvers.set(u,e),this._enqueueTaskMessage(h,{type:"request",message:d,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(u),l(e)})}else this._transport.send(d,{relatedRequestId:r,resumptionToken:i,onresumptiontoken:n}).catch(e=>{this._cleanupTimeout(u),l(e)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},oj,t)}async getTaskResult(e,t,a){return this.request({method:"tasks/result",params:e},t,a)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},oC,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},oA,t)}async notification(e,t){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(e.method);let a=t?.relatedTask?.taskId;if(a){let r={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[nD]:t.relatedTask}}};await this._enqueueTaskMessage(a,{type:"notification",message:r,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};t?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[nD]:t.relatedTask}}}),this._transport?.send(a,t).catch(e=>this._onerror(e))});return}let r={...e,jsonrpc:"2.0"};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[nD]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let a=c$(e);this.assertRequestHandlerCapability(a),this._requestHandlers.set(a,(a,r)=>Promise.resolve(t(cS(e,a),r)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let a=c$(e);this._notificationHandlers.set(a,a=>Promise.resolve(t(cS(e,a))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);void 0!==t&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,a){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,a,r)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){for(let a of(await this._taskMessageQueue.dequeueAll(e,t)))if("request"===a.type&&n1(a.message)){let t=a.message.id,r=this._requestResolvers.get(t);r?(r(new s1(_.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(t)):this._onerror(Error(`Resolver missing for request ${t} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let a=this._options?.defaultTaskPollInterval??1e3;try{let t=await this._taskStore?.getTask(e);t?.pollInterval&&(a=t.pollInterval)}catch{}return new Promise((e,r)=>{if(t.aborted)return void r(new s1(_.InvalidRequest,"Request cancelled"));let i=setTimeout(e,a);t.addEventListener("abort",()=>{clearTimeout(i),r(new s1(_.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){let a=this._taskStore;if(!a)throw Error("No task store configured");return{createTask:async r=>{if(!e)throw Error("No request provided");return await a.createTask(r,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let r=await a.getTask(e,t);if(!r)throw new s1(_.InvalidParams,"Failed to retrieve task: Task not found");return r},storeTaskResult:async(e,r,i)=>{await a.storeTaskResult(e,r,i,t);let n=await a.getTask(e,t);if(n){let t=o$.parse({method:"notifications/tasks/status",params:n});await this.notification(t),s2(n.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>a.getTaskResult(e,t),updateTaskStatus:async(e,r,i)=>{let n=await a.getTask(e,t);if(!n)throw new s1(_.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(s2(n.status))throw new s1(_.InvalidParams,`Cannot update task "${e}" from terminal status "${n.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await a.updateTaskStatus(e,r,i,t);let o=await a.getTask(e,t);if(o){let t=o$.parse({method:"notifications/tasks/status",params:o});await this.notification(t),s2(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>a.listTasks(e,t)}}}function cT(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}var cO=a(8825),cC=a(1712);class cP{constructor(e){this._ajv=e??function(){let e=new cO({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return cC(e),e}()}getValidator(e){let t="$id"in e&&"string"==typeof e.$id?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}}class cA{constructor(e){this._server=e}requestStream(e,t,a){return this._server.requestStream(e,t,a)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,a){return this._server.getTaskResult({taskId:e},t,a)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}}class cI extends cj{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(sm.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let a=this._loggingLevels.get(t);return!!a&&this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(a)},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new cP,this.setRequestHandler(ol,e=>this._oninitialize(e)),this.setNotificationHandler(om,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(sh,async(e,t)=>{let a=t.sessionId||t.requestInfo?.headers["mcp-session-id"]||void 0,{level:r}=e.params,i=sm.safeParse(r);return i.success&&this._loggingLevels.set(a,i.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new cA(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=function(e,t){let a={...e};for(let e in t){let r=t[e];if(void 0===r)continue;let i=a[e];cT(i)&&cT(r)?a[e]={...i,...r}:a[e]=r}return a}(this._capabilities,e)}setRequestHandler(e,t){let a,r=id(e),i=r?.method;if(!i)throw Error("Schema is missing a method literal");if(ic(i)){let e=i._zod?.def;a=e?.value??i.value}else{let e=i._def;a=e?.value??i.value}if("string"!=typeof a)throw Error("Schema method literal must be a string");if("tools/call"===a){let a=async(e,a)=>{let r=ip(su,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new s1(_.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,n=await Promise.resolve(t(e,a));if(i.task){let e=ip(ok,n);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new s1(_.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=ip(sl,n);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new s1(_.InvalidParams,`Invalid tools/call result: ${e}`)}return o.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`)}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`)}}assertTaskCapability(e){var t=this._clientCapabilities?.tasks?.requests,a="Client";if(!t)throw Error(`${a} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw Error(`${a} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw Error(`${a} does not support task creation for elicitation/create (required for ${e})`)}}assertTaskHandlerCapability(e){if(this._capabilities){var t=this._capabilities.tasks?.requests,a="Server";if(!t)throw Error(`${a} does not support task creation (required for ${e})`);if("tools/call"===e&&!t.tools?.call)throw Error(`${a} does not support task creation for tools/call (required for ${e})`)}}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:nM.includes(t)?t:nL,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},n5)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.");if(e.messages.length>0){let t=e.messages[e.messages.length-1],a=Array.isArray(t.content)?t.content:[t.content],r=a.some(e=>"tool_result"===e.type),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,n=i?Array.isArray(i.content)?i.content:[i.content]:[],o=n.some(e=>"tool_use"===e.type);if(r){if(a.some(e=>"tool_result"!==e.type))throw Error("The last message must contain only tool_result content if any is present");if(!o)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(o){let e=new Set(n.filter(e=>"tool_use"===e.type).map(e=>e.id)),t=new Set(a.filter(e=>"tool_result"===e.type).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},sT,t):this.request({method:"sampling/createMessage",params:e},sj,t)}async elicitInput(e,t){switch(e.mode??"form"){case"url":if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");return this.request({method:"elicitation/create",params:e},sB,t);case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let a="form"===e.mode?e:{...e,mode:"form"},r=await this.request({method:"elicitation/create",params:a},sB,t);if("accept"===r.action&&r.content&&a.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(a.requestedSchema)(r.content);if(!e.valid)throw new s1(_.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){if(e instanceof s1)throw e;throw new s1(_.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},sX,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}let cR=Symbol.for("mcp.completable");function cN(e){return!!e&&"object"==typeof e&&cR in e}(k||(k={})).Completable="McpCompletable";class cz{static isTemplate(e){return/\{[^}\s]+\}/.test(e)}static validateLength(e,t,a){if(e.length>t)throw Error(`${a} exceeds maximum length of ${t} characters (got ${e.length})`)}get variableNames(){return this.parts.flatMap(e=>"string"==typeof e?[]:e.names)}constructor(e){cz.validateLength(e,1e6,"Template"),this.template=e,this.parts=this.parse(e)}toString(){return this.template}parse(e){let t=[],a="",r=0,i=0;for(;r<e.length;)if("{"===e[r]){a&&(t.push(a),a="");let n=e.indexOf("}",r);if(-1===n)throw Error("Unclosed template expression");if(++i>1e4)throw Error("Template contains too many expressions (max 10000)");let o=e.slice(r+1,n),s=this.getOperator(o),c=o.includes("*"),l=this.getNames(o),p=l[0];for(let e of l)cz.validateLength(e,1e6,"Variable name");t.push({name:p,operator:s,names:l,exploded:c}),r=n+1}else a+=e[r],r++;return a&&t.push(a),t}getOperator(e){return["+","#",".","/","?","&"].find(t=>e.startsWith(t))||""}getNames(e){let t=this.getOperator(e);return e.slice(t.length).split(",").map(e=>e.replace("*","").trim()).filter(e=>e.length>0)}encodeValue(e,t){return(cz.validateLength(e,1e6,"Variable value"),"+"===t||"#"===t)?encodeURI(e):encodeURIComponent(e)}expandPart(e,t){if("?"===e.operator||"&"===e.operator){let a=e.names.map(a=>{let r=t[a];if(void 0===r)return"";let i=Array.isArray(r)?r.map(t=>this.encodeValue(t,e.operator)).join(","):this.encodeValue(r.toString(),e.operator);return`${a}=${i}`}).filter(e=>e.length>0);return 0===a.length?"":("?"===e.operator?"?":"&")+a.join("&")}if(e.names.length>1){let a=e.names.map(e=>t[e]).filter(e=>void 0!==e);return 0===a.length?"":a.map(e=>Array.isArray(e)?e[0]:e).join(",")}let a=t[e.name];if(void 0===a)return"";let r=(Array.isArray(a)?a:[a]).map(t=>this.encodeValue(t,e.operator));switch(e.operator){case"":case"+":default:return r.join(",");case"#":return"#"+r.join(",");case".":return"."+r.join(".");case"/":return"/"+r.join("/")}}expand(e){let t="",a=!1;for(let r of this.parts){if("string"==typeof r){t+=r;continue}let i=this.expandPart(r,e);i&&(("?"===r.operator||"&"===r.operator)&&a?t+=i.replace("?","&"):t+=i,("?"===r.operator||"&"===r.operator)&&(a=!0))}return t}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}partToRegExp(e){let t,a=[];for(let t of e.names)cz.validateLength(t,1e6,"Variable name");if("?"===e.operator||"&"===e.operator){for(let t=0;t<e.names.length;t++){let r=e.names[t],i=0===t?"\\"+e.operator:"&";a.push({pattern:i+this.escapeRegExp(r)+"=([^&]+)",name:r})}return a}let r=e.name;switch(e.operator){case"":t=e.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)";break;case"+":case"#":t="(.+)";break;case".":t="\\.([^/,]+)";break;case"/":t="/"+(e.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)");break;default:t="([^/]+)"}return a.push({pattern:t,name:r}),a}match(e){cz.validateLength(e,1e6,"URI");let t="^",a=[];for(let e of this.parts)if("string"==typeof e)t+=this.escapeRegExp(e);else for(let{pattern:r,name:i}of this.partToRegExp(e))t+=r,a.push({name:i,exploded:e.exploded});t+="$",cz.validateLength(t,1e6,"Generated regex pattern");let r=new RegExp(t),i=e.match(r);if(!i)return null;let n={};for(let e=0;e<a.length;e++){let{name:t,exploded:r}=a[e],o=i[e+1],s=t.replace("*","");r&&o.includes(",")?n[s]=o.split(","):n[s]=o}return n}}let cq=/^[A-Za-z0-9._-]{1,128}$/;function cL(e){let t=function(e){let t=[];if(0===e.length)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!cq.test(e)){let a=e.split("").filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,a)=>a.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${a.map(e=>`"${e}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}(e);var a=t.warnings;if(a.length>0){for(let t of(console.warn(`Tool name validation warning for "${e}":`),a))console.warn(` - ${t}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}return t.isValid}class cM{constructor(e){this._mcpServer=e}registerToolTask(e,t,a){let r={taskSupport:"required",...t.execution};if("forbidden"===r.taskSupport)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,r,t._meta,a)}}class cD{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new cI(e,t)}get experimental(){return this._experimental||(this._experimental={tasks:new cM(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(cV(ss)),this.server.assertCanSetRequestHandler(cV(su)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(ss,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let a,r={name:e,title:t.title,description:t.description,inputSchema:(a=im(t.inputSchema))?cE(a,{strictUnions:!0,pipeStrategy:"input"}):cU,annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=im(t.outputSchema);e&&(r.outputSchema=cE(e,{strictUnions:!0,pipeStrategy:"output"}))}return r})})),this.server.setRequestHandler(su,async(e,t)=>{try{let a=this._registeredTools[e.params.name];if(!a)throw new s1(_.InvalidParams,`Tool ${e.params.name} not found`);if(!a.enabled)throw new s1(_.InvalidParams,`Tool ${e.params.name} disabled`);let r=!!e.params.task,i=a.execution?.taskSupport,n="createTask"in a.handler;if(("required"===i||"optional"===i)&&!n)throw new s1(_.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if("required"===i&&!r)throw new s1(_.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if("optional"===i&&!r&&n)return await this.handleAutomaticTaskPolling(a,e,t);let o=await this.validateToolInput(a,e.params.arguments,e.params.name),s=await this.executeToolHandler(a,o,t);if(r)return s;return await this.validateToolOutput(a,s,e.params.name),s}catch(e){if(e instanceof s1&&e.code===_.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,t,a){if(!e.inputSchema)return;let r=im(e.inputSchema)??e.inputSchema,i=await iu(r,t);if(!i.success){let e=ih("error"in i?i.error:"Unknown error");throw new s1(_.InvalidParams,`Input validation error: Invalid arguments for tool ${a}: ${e}`)}return i.data}async validateToolOutput(e,t,a){if(!e.outputSchema||!("content"in t)||t.isError)return;if(!t.structuredContent)throw new s1(_.InvalidParams,`Output validation error: Tool ${a} has an output schema but no structured content was provided`);let r=im(e.outputSchema),i=await iu(r,t.structuredContent);if(!i.success){let e=ih("error"in i?i.error:"Unknown error");throw new s1(_.InvalidParams,`Output validation error: Invalid structured content for tool ${a}: ${e}`)}}async executeToolHandler(e,t,a){let r=e.handler;if("createTask"in r){if(!a.taskStore)throw Error("No task store provided.");let i={...a,taskStore:a.taskStore};return e.inputSchema?await Promise.resolve(r.createTask(t,i)):await Promise.resolve(r.createTask(i))}return e.inputSchema?await Promise.resolve(r(t,a)):await Promise.resolve(r(a))}async handleAutomaticTaskPolling(e,t,a){if(!a.taskStore)throw Error("No task store provided for task-capable tool.");let r=await this.validateToolInput(e,t.params.arguments,t.params.name),i=e.handler,n={...a,taskStore:a.taskStore},o=r?await Promise.resolve(i.createTask(r,n)):await Promise.resolve(i.createTask(n)),s=o.task.taskId,c=o.task,l=c.pollInterval??5e3;for(;"completed"!==c.status&&"failed"!==c.status&&"cancelled"!==c.status;){await new Promise(e=>setTimeout(e,l));let e=await a.taskStore.getTask(s);if(!e)throw new s1(_.InternalError,`Task ${s} not found during polling`);c=e}return await a.taskStore.getTaskResult(s)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(cV(sG)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(sG,async e=>{switch(e.params.ref.type){case"ref/prompt":if("ref/prompt"!==e.params.ref.type)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`);return this.handlePromptCompletion(e,e.params.ref);case"ref/resource":if("ref/resource"!==e.params.ref.type)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`);return this.handleResourceCompletion(e,e.params.ref);default:throw new s1(_.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,t){let a,r=this._registeredPrompts[t.name];if(!r)throw new s1(_.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new s1(_.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return cK;let i=id(r.argsSchema),n=i?.[e.params.argument.name];if(!cN(n))return cK;let o=(a=n[cR],a?.complete);return o?cJ(await o(e.params.argument.value,e.params.context)):cK}async handleResourceCompletion(e,t){let a=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!a){if(this._registeredResources[t.uri])return cK;throw new s1(_.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=a.resourceTemplate.completeCallback(e.params.argument.name);return r?cJ(await r(e.params.argument.value,e.params.context)):cK}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(cV(oF)),this.server.assertCanSetRequestHandler(cV(oZ)),this.server.assertCanSetRequestHandler(cV(oV)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(oF,async(e,t)=>{let a=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates))if(e.resourceTemplate.listCallback)for(let a of(await e.resourceTemplate.listCallback(t)).resources)r.push({...e.metadata,...a});return{resources:[...a,...r]}}),this.server.setRequestHandler(oZ,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(oV,async(e,t)=>{let a=new URL(e.params.uri),r=this._registeredResources[a.toString()];if(r){if(!r.enabled)throw new s1(_.InvalidParams,`Resource ${a} disabled`);return r.readCallback(a,t)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(a.toString());if(r)return e.readCallback(a,r,t)}throw new s1(_.InvalidParams,`Resource ${a} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(cV(o1)),this.server.assertCanSetRequestHandler(cV(o8)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(o1,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>{let a;return{name:e,title:t.title,description:t.description,arguments:t.argsSchema?(a=id(t.argsSchema))?Object.entries(a).map(([e,t])=>({name:e,description:t.description,required:!(ic(t)?t._zod?.def?.type==="optional":"function"==typeof t.isOptional?t.isOptional():t._def?.typeName==="ZodOptional")})):[]:void 0}})})),this.server.setRequestHandler(o8,async(e,t)=>{let a=this._registeredPrompts[e.params.name];if(!a)throw new s1(_.InvalidParams,`Prompt ${e.params.name} not found`);if(!a.enabled)throw new s1(_.InvalidParams,`Prompt ${e.params.name} disabled`);if(a.argsSchema){let r=im(a.argsSchema),i=await iu(r,e.params.arguments);if(!i.success){let t=ih("error"in i?i.error:"Unknown error");throw new s1(_.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let n=i.data,o=a.callback;return await Promise.resolve(o(n,t))}{let e=a.callback;return await Promise.resolve(e(t))}}),this._promptHandlersInitialized=!0)}resource(e,t,...a){let r;"object"==typeof a[0]&&(r=a.shift());let i=a[0];if("string"==typeof t){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let a=this._createRegisteredResource(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let a=this._createRegisteredResourceTemplate(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}registerResource(e,t,a,r){if("string"==typeof t){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,a.title,t,a,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,a.title,t,a,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,t,a,r,i){let n={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>n.update({enabled:!1}),enable:()=>n.update({enabled:!0}),remove:()=>n.update({uri:null}),update:e=>{void 0!==e.uri&&e.uri!==a&&(delete this._registeredResources[a],e.uri&&(this._registeredResources[e.uri]=n)),void 0!==e.name&&(n.name=e.name),void 0!==e.title&&(n.title=e.title),void 0!==e.metadata&&(n.metadata=e.metadata),void 0!==e.callback&&(n.readCallback=e.callback),void 0!==e.enabled&&(n.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[a]=n,n}_createRegisteredResourceTemplate(e,t,a,r,i){let n={resourceTemplate:a,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>n.update({enabled:!1}),enable:()=>n.update({enabled:!0}),remove:()=>n.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=n)),void 0!==t.title&&(n.title=t.title),void 0!==t.template&&(n.resourceTemplate=t.template),void 0!==t.metadata&&(n.metadata=t.metadata),void 0!==t.callback&&(n.readCallback=t.callback),void 0!==t.enabled&&(n.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=n;let o=a.uriTemplate.variableNames;return Array.isArray(o)&&o.some(e=>!!a.completeCallback(e))&&this.setCompletionRequestHandler(),n}_createRegisteredPrompt(e,t,a,r,i){let n={title:t,description:a,argsSchema:void 0===r?void 0:il(r),callback:i,enabled:!0,disable:()=>n.update({enabled:!1}),enable:()=>n.update({enabled:!0}),remove:()=>n.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=n)),void 0!==t.title&&(n.title=t.title),void 0!==t.description&&(n.description=t.description),void 0!==t.argsSchema&&(n.argsSchema=il(t.argsSchema)),void 0!==t.callback&&(n.callback=t.callback),void 0!==t.enabled&&(n.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=n,r&&Object.values(r).some(e=>cN(e instanceof nS?e._def?.innerType:e))&&this.setCompletionRequestHandler(),n}_createRegisteredTool(e,t,a,r,i,n,o,s,c){cL(e);let l={title:t,description:a,inputSchema:cB(r),outputSchema:cB(i),annotations:n,execution:o,_meta:s,handler:c,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&("string"==typeof t.name&&cL(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=l)),void 0!==t.title&&(l.title=t.title),void 0!==t.description&&(l.description=t.description),void 0!==t.paramsSchema&&(l.inputSchema=il(t.paramsSchema)),void 0!==t.outputSchema&&(l.outputSchema=il(t.outputSchema)),void 0!==t.callback&&(l.handler=t.callback),void 0!==t.annotations&&(l.annotations=t.annotations),void 0!==t._meta&&(l._meta=t._meta),void 0!==t.enabled&&(l.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...t){let a,r,i,n;if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);if("string"==typeof t[0]&&(a=t.shift()),t.length>1){let e=t[0];cH(e)?(r=t.shift(),t.length>1&&"object"==typeof t[0]&&null!==t[0]&&!cH(t[0])&&(n=t.shift())):"object"==typeof e&&null!==e&&(n=t.shift())}let o=t[0];return this._createRegisteredTool(e,void 0,a,r,i,n,{taskSupport:"forbidden"},void 0,o)}registerTool(e,t,a){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:n,outputSchema:o,annotations:s,_meta:c}=t;return this._createRegisteredTool(e,r,i,n,o,s,{taskSupport:"forbidden"},c,a)}prompt(e,...t){let a,r;if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);"string"==typeof t[0]&&(a=t.shift()),t.length>1&&(r=t.shift());let i=t[0],n=this._createRegisteredPrompt(e,void 0,a,r,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),n}registerPrompt(e,t,a){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:n}=t,o=this._createRegisteredPrompt(e,r,i,n,a);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}isConnected(){return void 0!==this.server.transport}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}}class cF{constructor(e,t){this._callbacks=t,this._uriTemplate="string"==typeof e?new cz(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}}let cU={type:"object",properties:{}};function cZ(e){return null!==e&&"object"==typeof e&&"parse"in e&&"function"==typeof e.parse&&"safeParse"in e&&"function"==typeof e.safeParse}function cH(e){return"object"==typeof e&&null!==e&&!("_def"in e||"_zod"in e||cZ(e))&&(0===Object.keys(e).length||Object.values(e).some(cZ))}function cB(e){if(e)return cH(e)?il(e):e}function cV(e){let t=id(e),a=t?.method;if(!a)throw Error("Schema is missing a method literal");let r=iv(a);if("string"==typeof r)return r;throw Error("Schema method literal must be a string")}function cJ(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}let cK={completion:{values:[],hasMore:!1}};var cG=a(290);let cW=(e,t)=>{globalThis[e]=t},cY=e=>globalThis[e];function cQ({name:e}){let t=Symbol.for(`xmcp-context-${e}`),a=Symbol.for(`xmcp-context-${e}-fallback-store`);if(cY(t))return cY(t);let r=new cG.AsyncLocalStorage,i=globalThis[a]??{current:null};cW(a,i);let n={provider:(e,t)=>(i.current=e,r.run(e,t)),getContext:()=>{let t=r.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 a=r.getStore()??i.current;if(!a)throw Error(`setContext() can only be used within the ${e} context.`);Object.assign(a,t)}};return cW(t,n),n}let cX=cQ({name:"http-request-context"}),c0=cX.setContext,c1=cX.getContext,c4=cX.provider,c2=cQ({name:"client-info-context"});c2.setContext;let c8=c2.getContext;c2.provider;let c9=new Set(["message","mode","requestedSchema"]),c5=new Set(["elicitationId","message","mode","url"]),c6=new Set(["properties","required","type"]),c3=new Set(["default","description","format","maxLength","minLength","title","type"]),c7=new Set(["default","description","enum","enumNames","title","type"]),le=new Set(["default","description","title","type"]),lt=new Set(["default","description","maximum","minimum","title","type"]),la=new Set(["date","date-time","email","uri"]);async function lr(e,t,a){let r=function(e){let t=e.mode??"form";if("url"===t)return function(e){let t;ln(e,"Elicitation request must be a plain object."),li(e,c5,"URL elicitation"),lo(e.message,"URL elicitation requires a string message."),ls(e.elicitationId,"URL elicitation requires a non-empty elicitationId."),ls(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),sD.parse(e);if("form"!==t)throw Error(`Unsupported elicitation mode "${String(e.mode)}". Expected "form" or "url".`);return function(e){ln(e,"Elicitation request must be a plain object."),li(e,c9,"Form elicitation"),lo(e.message,"Form elicitation requires a string message.");let t=e.requestedSchema;if(ln(t,"Form elicitation requires a flat object schema."),li(t,c6,"Form elicitation schema"),"object"!==t.type)throw Error('Form elicitation schema must use type "object".');for(let[e,a]of(ln(t.properties,"Form elicitation schema requires a properties object."),Object.entries(t.properties)))!function(e,t){if(ln(t,`Form elicitation field "${e}" must be a plain object.`),lc(t.title,`Form elicitation field "${e}" title must be a string.`),lc(t.description,`Form elicitation field "${e}" description must be a string.`),"string"===t.type&&"enum"in t){var a,r;if(li(t,c7,`Form elicitation field "${e}"`),lp(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&&lp(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(lc(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)){li(t,c3,`Form elicitation field "${e}"`),ll(t.minLength,`Form elicitation field "${e}" minLength must be a number.`),ll(t.maxLength,`Form elicitation field "${e}" maxLength must be a number.`),lc(t.default,`Form elicitation field "${e}" default must be a string.`);let a=t.format;if(lc(a,`Form elicitation field "${e}" format must be a string.`),void 0!==a&&!la.has(a))throw Error(`Form elicitation field "${e}" format must be one of: ${Array.from(la).join(", ")}.`);return}if("boolean"===t.type){if(li(t,le,`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){li(t,lt,`Form elicitation field "${e}"`),ll(t.minimum,`Form elicitation field "${e}" minimum must be a number.`),ll(t.maximum,`Form elicitation field "${e}" maximum must be a number.`),ll(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),sM.parse({...e,mode:"form"})}(t),i=await e.sendRequest({method:"elicitation/create",params:r},sB,a);return{...i,content:i.content??void 0}}function li(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 ln(e,t){if("object"!=typeof e||null===e||Array.isArray(e))throw Error(t)}function lo(e,t){if("string"!=typeof e)throw Error(t)}function ls(e,t){if("string"!=typeof e||0===e.trim().length)throw Error(t)}function lc(e,t){if(void 0!==e&&"string"!=typeof e)throw Error(t)}function ll(e,t){if(void 0!==e&&"number"!=typeof e)throw Error(t)}function lp(e,t){if(!Array.isArray(e)||e.some(e=>"string"!=typeof e))throw Error(t)}let lu={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 ld(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=lu[e.type];return t?t(e):{valid:!0}}function lm(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 lf(e){return!!(e&&"object"==typeof e&&Object.keys(e).some(e=>e.startsWith("ui/")))}function lh(e){return e.endsWith(".tsx")}let lv=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 lg(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 ly=["ui/resourceUri","resourceUri","visibility"],lb=["prefersBorder","domain","csp","permissions","connectDomains","resourceDomains","frameDomains","baseUriDomains"];function lx(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 lw(e){return(e.split("/").pop()||e).replace(/\.[^/.]+$/,"")}function l_(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 lk(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 lE(e){return Error(`[xmcp] Invalid prompt file: ${e}
|
|
31
|
+
-> Default export must be a prompt handler function.`)}async function l$(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 lE(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 lE(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 lS=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}
|
|
32
|
+
-> ${a}`)});let i=a.length;e.warn(`[xmcp] ${i} prompt${1===i?"":"s"} skipped due to empty files or missing default exports`)}}();function lj(e){return Error(`[xmcp] Invalid resource file: ${e}
|
|
33
|
+
-> Default export must be a resource handler function.`)}async function lT(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 lj(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 lj(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 lO=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}
|
|
34
|
+
-> ${a}`)});let i=a.length;e.warn(`[xmcp] ${i} resource${1===i?"":"s"} skipped due to empty files or missing default exports`)}}();function lC(e){return Error(`[xmcp] Invalid tool file: ${e}
|
|
35
|
+
-> Default export must be a tool handler function.`)}async function lP(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 lC(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 lC(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 lA=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}
|
|
36
|
+
-> ${a}`)});let i=a.length;e.warn(`[xmcp] ${i} tool${1===i?"":"s"} skipped due to empty files or missing default exports`)}}(),lI=INJECTED_TOOLS,lR=INJECTED_PROMPTS,lN=INJECTED_RESOURCES,lz=SERVER_INFO;async function lq(e,t,r,i){return lv.clear(),t.forEach((t,a)=>{var r;let i,n,o={name:lw(a),description:"No description provided"},{default:s,metadata:c,schema:l,outputSchema:p}=t;if("object"==typeof c&&null!==c&&Object.assign(o,c),"function"==typeof s&&"__x402"in s){let e=global.__XMCP_X402_REGISTRY;e&&e.set(o.name,s.__x402)}let u={};if(lx(l)?u=l:null!=l&&console.warn(`Invalid schema for tool "${o.name}" at ${a}. Expected Record<string, z.ZodType>`),null!=p)if(lx(p))i=p;else throw Error(`Invalid outputSchema for tool "${o.name}" at ${a}. 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 d=lh(a),m=!!(r=o._meta)&&"object"==typeof r&&"ui"in r&&"object"==typeof r.ui||d,f=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={},a={};if(e.ui&&"object"==typeof e.ui){let r=e.ui,i={},n={};for(let[e,t]of Object.entries(r))ly.includes(e)?i[e]=t:lb.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}}(f);f=t.toolMeta;let r=t.resourceMeta;r.ui=r.ui||{},r.ui.csp=r.ui.csp||{},r.ui.csp.resourceDomains=r.ui.csp.resourceDomains||[],r.ui.csp.resourceDomains.includes("https://esm.sh")||r.ui.csp.resourceDomains.push("https://esm.sh"),lv.add(o.name,{name:o.name,uri:e,handler:s,mimeType:"text/html;profile=mcp-app",_meta:r,toolPath:d?a:void 0})}let h=lg(f),v=m?h:void 0;n=lh(a)&&m?async(e,t)=>({content:[{type:"text",text:""}],_meta:v,structuredContent:{args:e}}):function(e,t,a,r="unknown-tool"){return async(i,n)=>{let o=e(i,function(e){let t;try{t=c1().clientInfo}catch{}if(!t)try{t=c8().clientInfo}catch{}return{...e,clientInfo:t,elicit:(t,a)=>lr(e,t,a)}}(n));if(o instanceof Promise&&(o=await o),"string"==typeof o||"number"==typeof o){if(a){let e=Object.entries(a);if(1===e.length){let[t,a]=e[0];try{return a.parse(o),{content:[{type:"text",text:"number"==typeof o?`${o}`:o}],structuredContent:{[t]:o}}}catch{}}}return lf(t)?{content:[{type:"text",text:""}],structuredContent:{args:i},_meta:t}:{content:[{type:"text",text:"number"==typeof o?`${o}`:o}]}}if(!a||!o||"object"!=typeof o||Array.isArray(o)||"structuredContent"in o||"content"in o&&Array.isArray(o.content)||"_meta"in o||"isError"in o||(lm(o,a,r,"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(lf(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}
|
|
37
37
|
|
|
38
38
|
Expected CallToolResult format:
|
|
39
39
|
{
|
|
@@ -83,7 +83,7 @@ Or both for backwards compatibility:
|
|
|
83
83
|
{
|
|
84
84
|
content: [{ type: "text", text: "fallback" }],
|
|
85
85
|
structuredContent: { your: "data" }
|
|
86
|
-
}`)}if(l&&!s&&!c){let{isError:e,...t}=o,a=Object.keys(t).length>0?`Tool execution failed: ${JSON.stringify(t)}`:"Tool execution failed";o.content=[{type:"text",text:a}],s=!0}if(a&&c&&!l&&
|
|
86
|
+
}`)}if(l&&!s&&!c){let{isError:e,...t}=o,a=Object.keys(t).length>0?`Tool execution failed: ${JSON.stringify(t)}`:"Tool execution failed";o.content=[{type:"text",text:a}],s=!0}if(a&&c&&!l&&lm(o.structuredContent,a,r,"returned structuredContent that does not match outputSchema"),!s&&c&&(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],a=ld(t);if(!a.valid)throw Error(`Invalid content item at index ${e}: ${a.error}
|
|
87
87
|
|
|
88
88
|
Content item: ${JSON.stringify(t,null,2)}
|
|
89
89
|
|
|
@@ -100,7 +100,7 @@ Expected format:
|
|
|
100
100
|
key: "value",
|
|
101
101
|
nested: { data: "here" }
|
|
102
102
|
}
|
|
103
|
-
}`)}}return o}}(s,v,i,o.name);let g={title:o.annotations?.title,description:o.description,inputSchema:np(u),outputSchema:i?np(i).strict():void 0,annotations:o.annotations,_meta:h};e.registerTool(o.name,g,n)}),r.forEach((t,a)=>{let r=
|
|
103
|
+
}`)}}return o}}(s,v,i,o.name);let g={title:o.annotations?.title,description:o.description,inputSchema:np(u),outputSchema:i?np(i).strict():void 0,annotations:o.annotations,_meta:h};e.registerTool(o.name,g,n)}),r.forEach((t,a)=>{let r=lw(a),i={name:r,title:r,description:"No description provided"},{default:n,metadata:o,schema:s}=t;"object"==typeof o&&null!==o&&Object.assign(i,o);let c=function(e,t="assistant"){return async(a,r)=>{let i,n=e(a,r);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=ld(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, or number. Got ${t}: ${a}
|
|
104
104
|
|
|
105
105
|
Validation error: ${e.error}
|
|
106
106
|
|
|
@@ -111,7 +111,7 @@ Expected formats:
|
|
|
111
111
|
- Image content: { type: "image", data: "base64data", mimeType: "image/jpeg" }
|
|
112
112
|
- Audio content: { type: "audio", data: "base64data", mimeType: "audio/mpeg" }
|
|
113
113
|
- Resource link: { type: "resource_link", name: "resource name", uri: "resource://uri" }
|
|
114
|
-
- 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}]}}}(n,i.role||"assistant");
|
|
114
|
+
- 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}]}}}(n,i.role||"assistant");lx(s)?Object.assign({},s):null!=s&&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,argsSchema:s},c)}),[...lv.getAll()].forEach(([t,r])=>{let i=r.mimeType||"text/html;profile=mcp-app",n=r?._meta?lg(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}=lk(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}=lk(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}").
|
|
115
115
|
React tool bundles are generated automatically when you run "xmcp build" (or "xmcp dev").
|
|
116
116
|
Please re-run the build so the framework can regenerate the bundle.`);let c=s.js,l=s.css,p=(e=`
|
|
117
117
|
<script type="module">
|
|
@@ -127,11 +127,13 @@ Please re-run the build so the framework can regenerate the bundle.`);let c=s.js
|
|
|
127
127
|
window.parent.postMessage({
|
|
128
128
|
jsonrpc: "2.0",
|
|
129
129
|
id: nextId++,
|
|
130
|
-
method: "ui/initialize",
|
|
130
|
+
method: ${JSON.stringify("ui/initialize")},
|
|
131
131
|
params: {
|
|
132
|
-
appCapabilities: {
|
|
132
|
+
appCapabilities: {
|
|
133
|
+
availableDisplayModes: ["inline", "fullscreen", "pip"]
|
|
134
|
+
},
|
|
133
135
|
appInfo: { name: "xmcp React Widget", version: "1.0.0" },
|
|
134
|
-
protocolVersion: "
|
|
136
|
+
protocolVersion: ${JSON.stringify("2026-01-26")}
|
|
135
137
|
}
|
|
136
138
|
}, "*");
|
|
137
139
|
|
|
@@ -144,7 +146,7 @@ Please re-run the build so the framework can regenerate the bundle.`);let c=s.js
|
|
|
144
146
|
if (data?.result?.hostContext && data?.id === 1) {
|
|
145
147
|
window.parent.postMessage({
|
|
146
148
|
jsonrpc: "2.0",
|
|
147
|
-
method: "ui/notifications/initialized",
|
|
149
|
+
method: ${JSON.stringify("ui/notifications/initialized")},
|
|
148
150
|
params: {}
|
|
149
151
|
}, "*");
|
|
150
152
|
}
|
|
@@ -164,7 +166,7 @@ Please re-run the build so the framework can regenerate the bundle.`);let c=s.js
|
|
|
164
166
|
<div id="root"></div>
|
|
165
167
|
${e}
|
|
166
168
|
</body>
|
|
167
|
-
</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:
|
|
169
|
+
</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:lw(a),description:"No description provided"},{default:i,metadata:n,schema:o}=t;"object"==typeof n&&null!==n&&Object.assign(r,n);let s={};lx(o)?s=o:null!=o&&console.warn(`Invalid schema for resource "${r.name}" at ${a}. Expected Record<string, z.ZodType>`);let c=l_(a);if(!c)return void console.warn(`Skipping resource "${r.name}" at ${a}: Invalid file path format`);let l=c.uriTemplate;r.mimeType&&r.mimeType.includes("html")&&(l=l.endsWith(".html")?l:`${l}.html`);let p=function(e,t,a={}){let r=l_(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}
|
|
168
170
|
|
|
169
171
|
Expected ReadResourceResult format:
|
|
170
172
|
{
|
|
@@ -173,7 +175,7 @@ Expected ReadResourceResult format:
|
|
|
173
175
|
{ uri: "resource://uri", mimeType: "application/json", text: "json content" },
|
|
174
176
|
{ uri: "resource://uri", blob: base64data }
|
|
175
177
|
]
|
|
176
|
-
}`)}return n.contents.forEach(e=>{e.uri||(e.uri=t.href)}),n}}(i,a,s);if("direct"===c.type)e.registerResource(r.name,l,r,p);else{let t=new cF(l,{list:void 0}),a=async(e,t,a)=>{let r={};for(let e of c.parameters){let a=t[e],i=s[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,t,r,a)}}),e}async function lz(){let{toolModules:e,skippedTools:t}=await lO(lP);return lC(t),e}async function lq(){let{promptModules:e,skippedPrompts:t}=await lk(lA);return lE(t),e}async function lL(){let{resourceModules:e,skippedResources:t}=await lS(lI);return lj(t),e}async function lM(){let e=new cD(lR),t=lz(),a=lq(),r=lL(),[i,n,o]=await Promise.all([t,a,r]);return lN(e,i,n,o)}var lD=a(8611),lF=a.n(lD);let lU=require("http2");var lZ=a(2203),lH=a(6982),lB=class extends Error{constructor(e,t){super(e,t),this.name="RequestError"}},lV=global.Request,lJ=class extends lV{constructor(e,t){"object"==typeof e&&lG in e&&(e=e[lG]()),void 0!==t?.body?.getReader&&(t.duplex??="half"),super(e,t)}},lK=Symbol("wrapBodyStream"),lG=Symbol("getRequestCache"),lW=Symbol("requestCache"),lY=Symbol("incomingKey"),lQ=Symbol("urlKey"),lX=Symbol("headersKey"),l0=Symbol("abortControllerKey"),l1=Symbol("getAbortController"),l4={get method(){return this[lY].method||"GET"},get url(){return this[lQ]},get headers(){return this[lX]||=(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[lY])},[l1](){return this[lG](),this[l0]},[lG](){return this[l0]||=new AbortController,this[lW]||=((e,t,a,r,i)=>{let n={method:e,headers:a,signal:i.signal};if("TRACE"===e){n.method="GET";let e=new lJ(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[lK]){let e;n.body=new ReadableStream({async pull(t){try{e||=lZ.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=lZ.Readable.toWeb(r);return new lJ(t,n)})(this.method,this[lQ],this.headers,this[lY],this[l0])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(e=>{Object.defineProperty(l4,e,{get(){return this[lG]()[e]}})}),["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(l4,e,{value:function(){return this[lG]()[e]()}})}),Object.setPrototypeOf(l4,lJ.prototype);var l2=Symbol("responseCache"),l8=Symbol("getResponseCache"),l9=Symbol("cache"),l5=global.Response,l6=class e{#e;#t;[l8](){return delete this[l9],this[l2]||=new l5(this.#e,this.#t)}constructor(t,a){let r;if(this.#e=t,a instanceof e){const e=a[l2];if(e){this.#t=e,this[l8]();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)&&(r||=a?.headers||{"content-type":"text/plain; charset=UTF-8"},this[l9]=[a?.status||200,t,r])}get headers(){let e=this[l9];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2])),e[2]):this[l8]().headers}get status(){return this[l9]?.[0]??this[l8]().status}get ok(){let e=this.status;return e>=200&&e<300}};async function l3(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function l7(e,t,a){let r=t=>{e.cancel(t).catch(()=>{})};return t.on("close",r),t.on("error",r),(a??e.read()).then(o,i),e.closed.finally(()=>{t.off("close",r),t.off("error",r)});function i(e){e&&t.destroy(e)}function n(){e.read().then(o,i)}function o({done:a,value:r}){try{if(a)t.end();else{if(t.write(r))return e.read().then(o,i);t.once("drain",n)}}catch(e){i(e)}}}["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(e=>{Object.defineProperty(l6.prototype,e,{get(){return this[l8]()[e]}})}),["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(l6.prototype,e,{value:function(){return this[l8]()[e]()}})}),Object.setPrototypeOf(l6,l5),Object.setPrototypeOf(l6.prototype,l5.prototype);var pe=e=>{let t={};e instanceof Headers||(e=new Headers(e??void 0));let a=[];for(let[r,i]of e)"set-cookie"===r?a.push(i):t[r]=i;return a.length>0&&(t["set-cookie"]=a),t["content-type"]??="text/plain; charset=UTF-8",t};void 0===global.crypto&&(global.crypto=lH);var pt=Symbol("outgoingEnded"),pa=e=>new Response(null,{status:e instanceof Error&&("TimeoutError"===e.name||"TimeoutError"===e.constructor.name)?504:500}),pr=(e,t)=>{let a=e instanceof Error?e:Error("unknown error",{cause:e});"ERR_STREAM_PREMATURE_CLOSE"===a.code?console.info("The user aborted a request."):(console.error(e),t.headersSent||t.writeHead(500,{"Content-Type":"text/plain"}),t.end(`Error: ${a.message}`),t.destroy(a))},pi=e=>{"flushHeaders"in e&&e.writable&&e.flushHeaders()},pn=async(e,t)=>{let[a,r,i]=e[l9];i instanceof Headers&&(i=pe(i)),"string"==typeof r?i["Content-Length"]=Buffer.byteLength(r):r instanceof Uint8Array?i["Content-Length"]=r.byteLength:r instanceof Blob&&(i["Content-Length"]=r.size),t.writeHead(a,i),"string"==typeof r||r instanceof Uint8Array?t.end(r):r instanceof Blob?t.end(new Uint8Array(await r.arrayBuffer())):(pi(t),await (function(e,t){if(e.locked)throw TypeError("ReadableStream is locked.");if(!t.destroyed)return l7(e.getReader(),t)})(r,t)?.catch(e=>pr(e,t))),t[pt]?.()},po=async(e,t,a={})=>{if("function"==typeof e.then)if(a.errorHandler)try{e=await e}catch(r){let t=await a.errorHandler(r);if(!t)return;e=t}else e=await e.catch(pa);if(l9 in e)return pn(e,t);let r=pe(e.headers);if(e.body){let a,i=e.body.getReader(),n=[],o=!1;if("chunked"!==r["transfer-encoding"]){let e=2;for(let t=0;t<e;t++){a||=i.read();let r=await l3(a).catch(e=>{console.error(e),o=!0});if(!r){if(1===t){await new Promise(e=>setTimeout(e)),e=3;continue}break}if(a=void 0,r.value&&n.push(r.value),r.done){o=!0;break}}!o||"content-length"in r||(r["content-length"]=n.reduce((e,t)=>e+t.length,0))}t.writeHead(e.status,r),n.forEach(e=>{t.write(e)}),o?t.end():(0===n.length&&pi(t),await l7(i,t,a))}else r["x-hono-already-sent"]||(t.writeHead(e.status,r),t.end());t[pt]?.()},ps=(e,t={})=>{let a=t.autoCleanupIncoming??!0;return!1!==t.overrideGlobalObjects&&global.Request!==lJ&&(Object.defineProperty(global,"Request",{value:lJ}),Object.defineProperty(global,"Response",{value:l6})),async(r,i)=>{let n,o;try{o=((e,t)=>{let a,r=Object.create(l4);r[lY]=e;let i=e.url||"";if("/"!==i[0]&&(i.startsWith("http://")||i.startsWith("https://"))){if(e instanceof lU.Http2ServerRequest)throw new lB("Absolute URL for :path is not allowed in HTTP/2");try{let e=new URL(i);r[lQ]=e.href}catch(e){throw new lB("Invalid absolute URL",{cause:e})}return r}let n=(e instanceof lU.Http2ServerRequest?e.authority:e.headers.host)||t;if(!n)throw new lB("Missing host header");if(e instanceof lU.Http2ServerRequest){if("http"!==(a=e.scheme)&&"https"!==a)throw new lB("Unsupported scheme")}else a=e.socket&&e.socket.encrypted?"https":"http";let o=new URL(`${a}://${n}${i}`);if(o.hostname.length!==n.length&&o.hostname!==n.replace(/:\d+$/,""))throw new lB("Invalid host header");return r[lQ]=o.href,r})(r,t.hostname);let s=!a||"GET"===r.method||"HEAD"===r.method;if(!s&&(r[lK]=!0,r.on("end",()=>{s=!0}),r instanceof lU.Http2ServerRequest&&(i[pt]=()=>{s||setTimeout(()=>{s||setTimeout(()=>{r.destroy(),i.destroy()})})})),i.on("close",()=>{o[l0]&&(r.errored?o[l0].abort(r.errored.toString()):i.writableFinished||o[l0].abort("Client connection prematurely closed.")),s||setTimeout(()=>{s||setTimeout(()=>{r.destroy()})})}),n=e(o,{incoming:r,outgoing:i}),l9 in n)return pn(n,i)}catch(e){if(n)return pr(e,i);if(t.errorHandler){if(!(n=await t.errorHandler(o||e instanceof lB?e:new lB(e.message,{cause:e}))))return}else n=o?pa(e):new Response(null,{status:400})}try{return await po(n,i,t)}catch(e){return pr(e,i)}}};class pc{constructor(e={}){this._started=!1,this._hasHandledRequest=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId="_GET_stream",this.sessionIdGenerator=e.sessionIdGenerator,this._enableJsonResponse=e.enableJsonResponse??!1,this._eventStore=e.eventStore,this._onsessioninitialized=e.onsessioninitialized,this._onsessionclosed=e.onsessionclosed,this._allowedHosts=e.allowedHosts,this._allowedOrigins=e.allowedOrigins,this._enableDnsRebindingProtection=e.enableDnsRebindingProtection??!1,this._retryInterval=e.retryInterval}async start(){if(this._started)throw Error("Transport already started");this._started=!0}createJsonErrorResponse(e,t,a,r){let i={code:t,message:a};return r?.data!==void 0&&(i.data=r.data),new Response(JSON.stringify({jsonrpc:"2.0",error:i,id:null}),{status:e,headers:{"Content-Type":"application/json",...r?.headers}})}validateRequestHeaders(e){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let t=e.headers.get("host");if(!t||!this._allowedHosts.includes(t)){let e=`Invalid Host header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let t=e.headers.get("origin");if(t&&!this._allowedOrigins.includes(t)){let e=`Invalid Origin header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}}}async handleRequest(e,t){if(!this.sessionIdGenerator&&this._hasHandledRequest)throw Error("Stateless transport cannot be reused across requests. Create a new transport per request.");this._hasHandledRequest=!0;let a=this.validateRequestHeaders(e);if(a)return a;switch(e.method){case"POST":return this.handlePostRequest(e,t);case"GET":return this.handleGetRequest(e);case"DELETE":return this.handleDeleteRequest(e);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(e,t,a,r){if(!this._eventStore||r<"2025-11-25")return;let i=await this._eventStore.storeEvent(a,{}),n=`id: ${i}
|
|
178
|
+
}`)}return n.contents.forEach(e=>{e.uri||(e.uri=t.href)}),n}}(i,a,s);if("direct"===c.type)e.registerResource(r.name,l,r,p);else{let t=new cF(l,{list:void 0}),a=async(e,t,a)=>{let r={};for(let e of c.parameters){let a=t[e],i=s[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,t,r,a)}}),e}async function lL(){let{toolModules:e,skippedTools:t}=await lP(lI);return lA(t),e}async function lM(){let{promptModules:e,skippedPrompts:t}=await l$(lR);return lS(t),e}async function lD(){let{resourceModules:e,skippedResources:t}=await lT(lN);return lO(t),e}async function lF(){let{instructions:e,...t}=lz,a=new cD(t,{instructions:e}),r=lL(),i=lM(),n=lD(),[o,s,c]=await Promise.all([r,i,n]);return lq(a,o,s,c)}var lU=a(8611),lZ=a.n(lU);let lH=require("http2");var lB=a(2203),lV=a(6982),lJ=class extends Error{constructor(e,t){super(e,t),this.name="RequestError"}},lK=global.Request,lG=class extends lK{constructor(e,t){"object"==typeof e&&lY in e&&(e=e[lY]()),void 0!==t?.body?.getReader&&(t.duplex??="half"),super(e,t)}},lW=Symbol("wrapBodyStream"),lY=Symbol("getRequestCache"),lQ=Symbol("requestCache"),lX=Symbol("incomingKey"),l0=Symbol("urlKey"),l1=Symbol("headersKey"),l4=Symbol("abortControllerKey"),l2=Symbol("getAbortController"),l8={get method(){return this[lX].method||"GET"},get url(){return this[l0]},get headers(){return this[l1]||=(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[lX])},[l2](){return this[lY](),this[l4]},[lY](){return this[l4]||=new AbortController,this[lQ]||=((e,t,a,r,i)=>{let n={method:e,headers:a,signal:i.signal};if("TRACE"===e){n.method="GET";let e=new lG(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[lW]){let e;n.body=new ReadableStream({async pull(t){try{e||=lB.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=lB.Readable.toWeb(r);return new lG(t,n)})(this.method,this[l0],this.headers,this[lX],this[l4])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(e=>{Object.defineProperty(l8,e,{get(){return this[lY]()[e]}})}),["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(l8,e,{value:function(){return this[lY]()[e]()}})}),Object.defineProperty(l8,Symbol.for("nodejs.util.inspect.custom"),{value:function(e,t,a){let r={method:this.method,url:this.url,headers:this.headers,nativeRequest:this[lQ]};return`Request (lightweight) ${a(r,{...t,depth:null==e?null:e-1})}`}}),Object.setPrototypeOf(l8,lG.prototype);var l9=Symbol("responseCache"),l5=Symbol("getResponseCache"),l6=Symbol("cache"),l3=global.Response,l7=class e{#e;#t;[l5](){return delete this[l6],this[l9]||=new l3(this.#e,this.#t)}constructor(t,a){let r;if(this.#e=t,a instanceof e){const e=a[l9];if(e){this.#t=e,this[l5]();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[l6]=[a?.status||200,t,r||a?.headers])}get headers(){let e=this[l6];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":"text/plain; charset=UTF-8"})),e[2]):this[l5]().headers}get status(){return this[l6]?.[0]??this[l5]().status}get ok(){let e=this.status;return e>=200&&e<300}};async function pe(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function pt(e,t,a){let r=t=>{e.cancel(t).catch(()=>{})};return t.on("close",r),t.on("error",r),(a??e.read()).then(o,i),e.closed.finally(()=>{t.off("close",r),t.off("error",r)});function i(e){e&&t.destroy(e)}function n(){e.read().then(o,i)}function o({done:a,value:r}){try{if(a)t.end();else{if(t.write(r))return e.read().then(o,i);t.once("drain",n)}}catch(e){i(e)}}}["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(e=>{Object.defineProperty(l7.prototype,e,{get(){return this[l5]()[e]}})}),["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(l7.prototype,e,{value:function(){return this[l5]()[e]()}})}),Object.defineProperty(l7.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[l9]};return`Response (lightweight) ${a(r,{...t,depth:null==e?null:e-1})}`}}),Object.setPrototypeOf(l7,l3),Object.setPrototypeOf(l7.prototype,l3.prototype);var pa=e=>{let t={};e instanceof Headers||(e=new Headers(e??void 0));let a=[];for(let[r,i]of e)"set-cookie"===r?a.push(i):t[r]=i;return a.length>0&&(t["set-cookie"]=a),t["content-type"]??="text/plain; charset=UTF-8",t};void 0===global.crypto&&(global.crypto=lV);var pr=Symbol("outgoingEnded"),pi=Symbol("incomingDraining"),pn=e=>{if(e.destroyed||e[pi])return;if(e[pi]=!0,e instanceof lH.Http2ServerRequest){try{e.stream?.close?.(lH.constants.NGHTTP2_NO_ERROR)}catch{}return}let t=0,a=()=>{clearTimeout(i),e.off("data",n),e.off("end",a),e.off("error",a)},r=()=>{a();let t=e.socket;t&&!t.destroyed&&t.destroySoon()},i=setTimeout(r,500);i.unref?.();let n=e=>{(t+=e.length)>0x4000000&&r()};e.on("data",n),e.on("end",a),e.on("error",a),e.resume()},po=e=>new Response(null,{status:e instanceof Error&&("TimeoutError"===e.name||"TimeoutError"===e.constructor.name)?504:500}),ps=(e,t)=>{let a=e instanceof Error?e:Error("unknown error",{cause:e});"ERR_STREAM_PREMATURE_CLOSE"===a.code?console.info("The user aborted a request."):(console.error(e),t.headersSent||t.writeHead(500,{"Content-Type":"text/plain"}),t.end(`Error: ${a.message}`),t.destroy(a))},pc=e=>{"flushHeaders"in e&&e.writable&&e.flushHeaders()},pl=async(e,t)=>{let[a,r,i]=e[l6],n=!1;if(i){if(i instanceof Headers)n=i.has("content-length"),i=pa(i);else if(Array.isArray(i)){let e=new Headers(i);n=e.has("content-length"),i=pa(e)}else for(let e in i)if(14===e.length&&"content-length"===e.toLowerCase()){n=!0;break}}else i={"content-type":"text/plain; charset=UTF-8"};!n&&("string"==typeof r?i["Content-Length"]=Buffer.byteLength(r):r instanceof Uint8Array?i["Content-Length"]=r.byteLength:r instanceof Blob&&(i["Content-Length"]=r.size)),t.writeHead(a,i),"string"==typeof r||r instanceof Uint8Array?t.end(r):r instanceof Blob?t.end(new Uint8Array(await r.arrayBuffer())):(pc(t),await (function(e,t){if(e.locked)throw TypeError("ReadableStream is locked.");if(!t.destroyed)return pt(e.getReader(),t)})(r,t)?.catch(e=>ps(e,t))),t[pr]?.()},pp=async(e,t,a={})=>{if("function"==typeof e.then)if(a.errorHandler)try{e=await e}catch(r){let t=await a.errorHandler(r);if(!t)return;e=t}else e=await e.catch(po);if(l6 in e)return pl(e,t);let r=pa(e.headers);if(e.body){let a,i=e.body.getReader(),n=[],o=!1;if("chunked"!==r["transfer-encoding"]){let e=2;for(let t=0;t<e;t++){a||=i.read();let r=await pe(a).catch(e=>{console.error(e),o=!0});if(!r){if(1===t){await new Promise(e=>setTimeout(e)),e=3;continue}break}if(a=void 0,r.value&&n.push(r.value),r.done){o=!0;break}}!o||"content-length"in r||(r["content-length"]=n.reduce((e,t)=>e+t.length,0))}t.writeHead(e.status,r),n.forEach(e=>{t.write(e)}),o?t.end():(0===n.length&&pc(t),await pt(i,t,a))}else r["x-hono-already-sent"]||(t.writeHead(e.status,r),t.end());t[pr]?.()},pu=(e,t={})=>{let a=t.autoCleanupIncoming??!0;return!1!==t.overrideGlobalObjects&&global.Request!==lG&&(Object.defineProperty(global,"Request",{value:lG}),Object.defineProperty(global,"Response",{value:l7})),async(r,i)=>{let n,o;try{o=((e,t)=>{let a,r=Object.create(l8);r[lX]=e;let i=e.url||"";if("/"!==i[0]&&(i.startsWith("http://")||i.startsWith("https://"))){if(e instanceof lH.Http2ServerRequest)throw new lJ("Absolute URL for :path is not allowed in HTTP/2");try{let e=new URL(i);r[l0]=e.href}catch(e){throw new lJ("Invalid absolute URL",{cause:e})}return r}let n=(e instanceof lH.Http2ServerRequest?e.authority:e.headers.host)||t;if(!n)throw new lJ("Missing host header");if(e instanceof lH.Http2ServerRequest){if("http"!==(a=e.scheme)&&"https"!==a)throw new lJ("Unsupported scheme")}else a=e.socket&&e.socket.encrypted?"https":"http";let o=new URL(`${a}://${n}${i}`);if(o.hostname.length!==n.length&&o.hostname!==n.replace(/:\d+$/,""))throw new lJ("Invalid host header");return r[l0]=o.href,r})(r,t.hostname);let s=!a||"GET"===r.method||"HEAD"===r.method;if(s||(r[lW]=!0,r.on("end",()=>{s=!0}),r instanceof lH.Http2ServerRequest&&(i[pr]=()=>{s||setTimeout(()=>{s||setTimeout(()=>{pn(r)})})}),i.on("finish",()=>{s||pn(r)})),i.on("close",()=>{o[l4]&&(r.errored?o[l4].abort(r.errored.toString()):i.writableFinished||o[l4].abort("Client connection prematurely closed.")),s||setTimeout(()=>{s||setTimeout(()=>{pn(r)})})}),n=e(o,{incoming:r,outgoing:i}),l6 in n)return pl(n,i)}catch(e){if(n)return ps(e,i);if(t.errorHandler){if(!(n=await t.errorHandler(o||e instanceof lJ?e:new lJ(e.message,{cause:e}))))return}else n=o?po(e):new Response(null,{status:400})}try{return await pp(n,i,t)}catch(e){return ps(e,i)}}};class pd{constructor(e={}){this._started=!1,this._hasHandledRequest=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId="_GET_stream",this.sessionIdGenerator=e.sessionIdGenerator,this._enableJsonResponse=e.enableJsonResponse??!1,this._eventStore=e.eventStore,this._onsessioninitialized=e.onsessioninitialized,this._onsessionclosed=e.onsessionclosed,this._allowedHosts=e.allowedHosts,this._allowedOrigins=e.allowedOrigins,this._enableDnsRebindingProtection=e.enableDnsRebindingProtection??!1,this._retryInterval=e.retryInterval}async start(){if(this._started)throw Error("Transport already started");this._started=!0}createJsonErrorResponse(e,t,a,r){let i={code:t,message:a};return r?.data!==void 0&&(i.data=r.data),new Response(JSON.stringify({jsonrpc:"2.0",error:i,id:null}),{status:e,headers:{"Content-Type":"application/json",...r?.headers}})}validateRequestHeaders(e){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let t=e.headers.get("host");if(!t||!this._allowedHosts.includes(t)){let e=`Invalid Host header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let t=e.headers.get("origin");if(t&&!this._allowedOrigins.includes(t)){let e=`Invalid Origin header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}}}async handleRequest(e,t){if(!this.sessionIdGenerator&&this._hasHandledRequest)throw Error("Stateless transport cannot be reused across requests. Create a new transport per request.");this._hasHandledRequest=!0;let a=this.validateRequestHeaders(e);if(a)return a;switch(e.method){case"POST":return this.handlePostRequest(e,t);case"GET":return this.handleGetRequest(e);case"DELETE":return this.handleDeleteRequest(e);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(e,t,a,r){if(!this._eventStore||r<"2025-11-25")return;let i=await this._eventStore.storeEvent(a,{}),n=`id: ${i}
|
|
177
179
|
data:
|
|
178
180
|
|
|
179
181
|
`;void 0!==this._retryInterval&&(n=`id: ${i}
|
|
@@ -184,7 +186,7 @@ data:
|
|
|
184
186
|
`;return r&&(i+=`id: ${r}
|
|
185
187
|
`),i+=`data: ${JSON.stringify(a)}
|
|
186
188
|
|
|
187
|
-
`,e.enqueue(t.encode(i)),!0}catch{return!1}}handleUnsupportedRequest(){return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}),{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(e,t){try{let a,r,i,n=e.headers.get("accept");if(!n?.includes("application/json")||!n.includes("text/event-stream"))return this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept both application/json and text/event-stream");let o=e.headers.get("content-type");if(!o||!o.includes("application/json"))return this.createJsonErrorResponse(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let s={headers:Object.fromEntries(e.headers.entries())};if(t?.parsedBody!==void 0)a=t.parsedBody;else try{a=await e.json()}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}try{r=Array.isArray(a)?a.map(e=>n9.parse(e)):[n9.parse(a)]}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}let c=r.some(op);if(c){if(this._initialized&&void 0!==this.sessionId)return this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(r.length>1)return this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!c){let t=this.validateSession(e);if(t)return t;let a=this.validateProtocolVersion(e);if(a)return a}if(!r.some(n1)){for(let e of r)this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:s});return new Response(null,{status:202})}let l=crypto.randomUUID(),p=r.find(e=>op(e)),u=p?p.params.protocolVersion:e.headers.get("mcp-protocol-version")??"2025-03-26";if(this._enableJsonResponse)return new Promise(e=>{for(let t of(this._streamMapping.set(l,{resolveJson:e,cleanup:()=>{this._streamMapping.delete(l)}}),r))n1(t)&&this._requestToStreamMapping.set(t.id,l);for(let e of r)this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:s})});let d=new TextEncoder,m=new ReadableStream({start:e=>{i=e},cancel:()=>{this._streamMapping.delete(l)}}),f={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};for(let e of(void 0!==this.sessionId&&(f["mcp-session-id"]=this.sessionId),r))n1(e)&&(this._streamMapping.set(l,{controller:i,encoder:d,cleanup:()=>{this._streamMapping.delete(l);try{i.close()}catch{}}}),this._requestToStreamMapping.set(e.id,l));for(let e of(await this.writePrimingEvent(i,d,l,u),r)){let a,r;n1(e)&&this._eventStore&&u>="2025-11-25"&&(a=()=>{this.closeSSEStream(e.id)},r=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:s,closeSSEStream:a,closeStandaloneSSEStream:r})}return new Response(m,{status:200,headers:f})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(e)})}}async handleDeleteRequest(e){let t=this.validateSession(e);if(t)return t;let a=this.validateProtocolVersion(e);return a||(await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200}))}validateSession(e){if(void 0===this.sessionIdGenerator)return;if(!this._initialized)return this.createJsonErrorResponse(400,-32e3,"Bad Request: Server not initialized");let t=e.headers.get("mcp-session-id");return t?t!==this.sessionId?this.createJsonErrorResponse(404,-32001,"Session not found"):void 0:this.createJsonErrorResponse(400,-32e3,"Bad Request: Mcp-Session-Id header is required")}validateProtocolVersion(e){let t=e.headers.get("mcp-protocol-version");if(null!==t&&!nM.includes(t))return this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${t} (supported versions: ${nM.join(", ")})`)}async close(){this._streamMapping.forEach(({cleanup:e})=>{e()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(e){let t=this._requestToStreamMapping.get(e);if(!t)return;let a=this._streamMapping.get(t);a&&a.cleanup()}closeStandaloneSSEStream(){let e=this._streamMapping.get(this._standaloneSseStreamId);e&&e.cleanup()}async send(e,t){let a=t?.relatedRequestId;if((n2.safeParse(e).success||n8.safeParse(e).success)&&(a=e.id),void 0===a){let t;if(n2.safeParse(e).success||n8.safeParse(e).success)throw Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");this._eventStore&&(t=await this._eventStore.storeEvent(this._standaloneSseStreamId,e));let a=this._streamMapping.get(this._standaloneSseStreamId);if(void 0===a)return;a.controller&&a.encoder&&this.writeSSEEvent(a.controller,a.encoder,e,t);return}let r=this._requestToStreamMapping.get(a);if(!r)throw Error(`No connection established for request ID: ${String(a)}`);let i=this._streamMapping.get(r);if(!this._enableJsonResponse&&i?.controller&&i?.encoder){let t;this._eventStore&&(t=await this._eventStore.storeEvent(r,e)),this.writeSSEEvent(i.controller,i.encoder,e,t)}if(n2.safeParse(e).success||n8.safeParse(e).success){this._requestResponseMap.set(a,e);let t=Array.from(this._requestToStreamMapping.entries()).filter(([e,t])=>t===r).map(([e])=>e);if(t.every(e=>this._requestResponseMap.has(e))){if(!i)throw Error(`No connection established for request ID: ${String(a)}`);if(this._enableJsonResponse&&i.resolveJson){let e={"Content-Type":"application/json"};void 0!==this.sessionId&&(e["mcp-session-id"]=this.sessionId);let a=t.map(e=>this._requestResponseMap.get(e));1===a.length?i.resolveJson(new Response(JSON.stringify(a[0]),{status:200,headers:e})):i.resolveJson(new Response(JSON.stringify(a),{status:200,headers:e}))}else i.cleanup();for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e)}}}}class
|
|
189
|
+
`,e.enqueue(t.encode(i)),!0}catch{return!1}}handleUnsupportedRequest(){return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}),{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(e,t){try{let a,r,i,n=e.headers.get("accept");if(!n?.includes("application/json")||!n.includes("text/event-stream"))return this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept both application/json and text/event-stream");let o=e.headers.get("content-type");if(!o||!o.includes("application/json"))return this.createJsonErrorResponse(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let s={headers:Object.fromEntries(e.headers.entries())};if(t?.parsedBody!==void 0)a=t.parsedBody;else try{a=await e.json()}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}try{r=Array.isArray(a)?a.map(e=>n9.parse(e)):[n9.parse(a)]}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}let c=r.some(op);if(c){if(this._initialized&&void 0!==this.sessionId)return this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(r.length>1)return this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!c){let t=this.validateSession(e);if(t)return t;let a=this.validateProtocolVersion(e);if(a)return a}if(!r.some(n1)){for(let e of r)this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:s});return new Response(null,{status:202})}let l=crypto.randomUUID(),p=r.find(e=>op(e)),u=p?p.params.protocolVersion:e.headers.get("mcp-protocol-version")??"2025-03-26";if(this._enableJsonResponse)return new Promise(e=>{for(let t of(this._streamMapping.set(l,{resolveJson:e,cleanup:()=>{this._streamMapping.delete(l)}}),r))n1(t)&&this._requestToStreamMapping.set(t.id,l);for(let e of r)this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:s})});let d=new TextEncoder,m=new ReadableStream({start:e=>{i=e},cancel:()=>{this._streamMapping.delete(l)}}),f={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};for(let e of(void 0!==this.sessionId&&(f["mcp-session-id"]=this.sessionId),r))n1(e)&&(this._streamMapping.set(l,{controller:i,encoder:d,cleanup:()=>{this._streamMapping.delete(l);try{i.close()}catch{}}}),this._requestToStreamMapping.set(e.id,l));for(let e of(await this.writePrimingEvent(i,d,l,u),r)){let a,r;n1(e)&&this._eventStore&&u>="2025-11-25"&&(a=()=>{this.closeSSEStream(e.id)},r=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:s,closeSSEStream:a,closeStandaloneSSEStream:r})}return new Response(m,{status:200,headers:f})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(e)})}}async handleDeleteRequest(e){let t=this.validateSession(e);if(t)return t;let a=this.validateProtocolVersion(e);return a||(await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200}))}validateSession(e){if(void 0===this.sessionIdGenerator)return;if(!this._initialized)return this.createJsonErrorResponse(400,-32e3,"Bad Request: Server not initialized");let t=e.headers.get("mcp-session-id");return t?t!==this.sessionId?this.createJsonErrorResponse(404,-32001,"Session not found"):void 0:this.createJsonErrorResponse(400,-32e3,"Bad Request: Mcp-Session-Id header is required")}validateProtocolVersion(e){let t=e.headers.get("mcp-protocol-version");if(null!==t&&!nM.includes(t))return this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${t} (supported versions: ${nM.join(", ")})`)}async close(){this._streamMapping.forEach(({cleanup:e})=>{e()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(e){let t=this._requestToStreamMapping.get(e);if(!t)return;let a=this._streamMapping.get(t);a&&a.cleanup()}closeStandaloneSSEStream(){let e=this._streamMapping.get(this._standaloneSseStreamId);e&&e.cleanup()}async send(e,t){let a=t?.relatedRequestId;if((n2.safeParse(e).success||n8.safeParse(e).success)&&(a=e.id),void 0===a){let t;if(n2.safeParse(e).success||n8.safeParse(e).success)throw Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");this._eventStore&&(t=await this._eventStore.storeEvent(this._standaloneSseStreamId,e));let a=this._streamMapping.get(this._standaloneSseStreamId);if(void 0===a)return;a.controller&&a.encoder&&this.writeSSEEvent(a.controller,a.encoder,e,t);return}let r=this._requestToStreamMapping.get(a);if(!r)throw Error(`No connection established for request ID: ${String(a)}`);let i=this._streamMapping.get(r);if(!this._enableJsonResponse&&i?.controller&&i?.encoder){let t;this._eventStore&&(t=await this._eventStore.storeEvent(r,e)),this.writeSSEEvent(i.controller,i.encoder,e,t)}if(n2.safeParse(e).success||n8.safeParse(e).success){this._requestResponseMap.set(a,e);let t=Array.from(this._requestToStreamMapping.entries()).filter(([e,t])=>t===r).map(([e])=>e);if(t.every(e=>this._requestResponseMap.has(e))){if(!i)throw Error(`No connection established for request ID: ${String(a)}`);if(this._enableJsonResponse&&i.resolveJson){let e={"Content-Type":"application/json"};void 0!==this.sessionId&&(e["mcp-session-id"]=this.sessionId);let a=t.map(e=>this._requestResponseMap.get(e));1===a.length?i.resolveJson(new Response(JSON.stringify(a[0]),{status:200,headers:e})):i.resolveJson(new Response(JSON.stringify(a),{status:200,headers:e}))}else i.cleanup();for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e)}}}}class pm{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new pd(e),this._requestListener=pu(async e=>{let t=this._requestContext.get(e);return this._webStandardTransport.handleRequest(e,{authInfo:t?.authInfo,parsedBody:t?.parsedBody})},{overrideGlobalObjects:!1})}get sessionId(){return this._webStandardTransport.sessionId}set onclose(e){this._webStandardTransport.onclose=e}get onclose(){return this._webStandardTransport.onclose}set onerror(e){this._webStandardTransport.onerror=e}get onerror(){return this._webStandardTransport.onerror}set onmessage(e){this._webStandardTransport.onmessage=e}get onmessage(){return this._webStandardTransport.onmessage}async start(){return this._webStandardTransport.start()}async close(){return this._webStandardTransport.close()}async send(e,t){return this._webStandardTransport.send(e,t)}async handleRequest(e,t,a){let r=e.auth,i=pu(async e=>this._webStandardTransport.handleRequest(e,{authInfo:r,parsedBody:a}),{overrideGlobalObjects:!1});await i(e,t)}closeSSEStream(e){this._webStandardTransport.closeSSEStream(e)}closeStandaloneSSEStream(){this._webStandardTransport.closeStandaloneSSEStream()}}var pf=a(5711),ph=a.n(pf);let pv=require("node:crypto");function pg(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}class py{constructor(){pg(this,"onmessage",void 0),pg(this,"onerror",void 0),pg(this,"onclose",void 0)}}let pb="This MCP server was bootstrapped with xmcp.",px={cursor:`
|
|
188
190
|
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
|
|
189
191
|
<g clip-path="url(#cursor)">
|
|
190
192
|
<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" />
|
|
@@ -239,7 +241,7 @@ data:
|
|
|
239
241
|
</clipPath>
|
|
240
242
|
</defs>
|
|
241
243
|
</svg>
|
|
242
|
-
`},
|
|
244
|
+
`},pw=String.raw`
|
|
243
245
|
:root {
|
|
244
246
|
color-scheme: dark;
|
|
245
247
|
--brand-white: #f7f7f7;
|
|
@@ -538,7 +540,7 @@ data:
|
|
|
538
540
|
clip: rect(0, 0, 0, 0);
|
|
539
541
|
border: 0;
|
|
540
542
|
}
|
|
541
|
-
`,pv=(e=0)=>t=>`\u001B[${t+e}m`,pg=(e=0)=>t=>`\u001B[${38+e};5;${t}m`,py=(e=0)=>(t,a,r)=>`\u001B[${38+e};2;${t};${a};${r}m`,pb={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(pb.modifier),[...Object.keys(pb.color),...Object.keys(pb.bgColor)];let px=function(){let e=new Map;for(let[t,a]of Object.entries(pb)){for(let[t,r]of Object.entries(a))pb[t]={open:`\u001B[${r[0]}m`,close:`\u001B[${r[1]}m`},a[t]=pb[t],e.set(r[0],r[1]);Object.defineProperty(pb,t,{value:a,enumerable:!1})}return Object.defineProperty(pb,"codes",{value:e,enumerable:!1}),pb.color.close="\x1b[39m",pb.bgColor.close="\x1b[49m",pb.color.ansi=pv(),pb.color.ansi256=pg(),pb.color.ansi16m=py(),pb.bgColor.ansi=pv(10),pb.bgColor.ansi256=pg(10),pb.bgColor.ansi16m=py(10),Object.defineProperties(pb,{rgbToAnsi256:{value:(e,t,a)=>e===t&&t===a?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(a/255*5),enumerable:!1},hexToRgb:{value(e){let t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[a]=t;3===a.length&&(a=[...a].map(e=>e+e).join(""));let r=Number.parseInt(a,16);return[r>>16&255,r>>8&255,255&r]},enumerable:!1},hexToAnsi256:{value:e=>pb.rgbToAnsi256(...pb.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){let t,a,r;if(e<8)return 30+e;if(e<16)return 90+(e-8);if(e>=232)a=t=((e-232)*10+8)/255,r=t;else{let i=(e-=16)%36;t=Math.floor(e/36)/5,a=Math.floor(i/6)/5,r=i%6/5}let i=2*Math.max(t,a,r);if(0===i)return 30;let n=30+(Math.round(r)<<2|Math.round(a)<<1|Math.round(t));return 2===i&&(n+=60),n},enumerable:!1},rgbToAnsi:{value:(e,t,a)=>pb.ansi256ToAnsi(pb.rgbToAnsi256(e,t,a)),enumerable:!1},hexToAnsi:{value:e=>pb.ansi256ToAnsi(pb.hexToAnsi256(e)),enumerable:!1}}),pb}(),pw=require("node:process"),p_=require("node:os"),pk=require("node:tty");function pE(e,t=globalThis.Deno?globalThis.Deno.args:pw.argv){let a=e.startsWith("-")?"":1===e.length?"-":"--",r=t.indexOf(a+e),i=t.indexOf("--");return -1!==r&&(-1===i||r<i)}let{env:p$}=pw;function pS(e,a={}){var r;return 0!==(r=function(e,{streamIsTTY:a,sniffFlags:r=!0}={}){let i=function(){if("FORCE_COLOR"in p$)return"true"===p$.FORCE_COLOR?1:"false"===p$.FORCE_COLOR?0:0===p$.FORCE_COLOR.length?1:Math.min(Number.parseInt(p$.FORCE_COLOR,10),3)}();void 0!==i&&(t=i);let n=r?t:i;if(0===n)return 0;if(r){if(pE("color=16m")||pE("color=full")||pE("color=truecolor"))return 3;if(pE("color=256"))return 2}if("TF_BUILD"in p$&&"AGENT_NAME"in p$)return 1;if(e&&!a&&void 0===n)return 0;let o=n||0;if("dumb"===p$.TERM)return o;if("win32"===pw.platform){let e=p_.release().split(".");return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if("CI"in p$)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(e=>e in p$)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(e=>e in p$)||"codeship"===p$.CI_NAME?1:o;if("TEAMCITY_VERSION"in p$)return+!!/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(p$.TEAMCITY_VERSION);if("truecolor"===p$.COLORTERM||"xterm-kitty"===p$.TERM||"xterm-ghostty"===p$.TERM||"wezterm"===p$.TERM)return 3;if("TERM_PROGRAM"in p$){let e=Number.parseInt((p$.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(p$.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(p$.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(p$.TERM)||"COLORTERM"in p$?1:o}(e,{streamIsTTY:e&&e.isTTY,...a}))&&{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}pE("no-color")||pE("no-colors")||pE("color=false")||pE("color=never")?t=0:(pE("color")||pE("colors")||pE("color=true")||pE("color=always"))&&(t=1);let{stdout:pj,stderr:pT}={stdout:pS({isTTY:pk.isatty(1)}),stderr:pS({isTTY:pk.isatty(2)})},pO=Symbol("GENERATOR"),pC=Symbol("STYLER"),pP=Symbol("IS_EMPTY"),pA=["ansi","ansi","ansi256","ansi16m"],pI=Object.create(null);function pR(e){let t;return((e,t={})=>{if(t.level&&!(Number.isInteger(t.level)&&t.level>=0&&t.level<=3))throw Error("The `level` option should be an integer from 0 to 3");let a=pj?pj.level:0;e.level=void 0===t.level?a:t.level})(t=(...e)=>e.join(" "),e),Object.setPrototypeOf(t,pR.prototype),t}for(let[e,t]of(Object.setPrototypeOf(pR.prototype,Function.prototype),Object.entries(px)))pI[e]={get(){let a=pL(this,pq(t.open,t.close,this[pC]),this[pP]);return Object.defineProperty(this,e,{value:a}),a}};pI.visible={get(){let e=pL(this,this[pC],!0);return Object.defineProperty(this,"visible",{value:e}),e}};let pN=(e,t,a,...r)=>"rgb"===e?"ansi16m"===t?px[a].ansi16m(...r):"ansi256"===t?px[a].ansi256(px.rgbToAnsi256(...r)):px[a].ansi(px.rgbToAnsi(...r)):"hex"===e?pN("rgb",t,a,...px.hexToRgb(...r)):px[a][e](...r);for(let e of["rgb","hex","ansi256"])pI[e]={get(){let{level:t}=this;return function(...a){return pL(this,pq(pN(e,pA[t],"color",...a),px.color.close,this[pC]),this[pP])}}},pI["bg"+e[0].toUpperCase()+e.slice(1)]={get(){let{level:t}=this;return function(...a){return pL(this,pq(pN(e,pA[t],"bgColor",...a),px.bgColor.close,this[pC]),this[pP])}}};let pz=Object.defineProperties(()=>{},{...pI,level:{enumerable:!0,get(){return this[pO].level},set(e){this[pO].level=e}}}),pq=(e,t,a)=>{let r,i;return void 0===a?(r=e,i=t):(r=a.openAll+e,i=t+a.closeAll),{open:e,close:t,openAll:r,closeAll:i,parent:a}},pL=(e,t,a)=>{let r=(...e)=>pM(r,1===e.length?""+e[0]:e.join(" "));return Object.setPrototypeOf(r,pz),r[pO]=e,r[pC]=t,r[pP]=a,r},pM=(e,t)=>{if(e.level<=0||!t)return e[pP]?"":t;let a=e[pC];if(void 0===a)return t;let{openAll:r,closeAll:i}=a;if(t.includes("\x1b"))for(;void 0!==a;)t=function(e,t,a){let r=e.indexOf(t);if(-1===r)return e;let i=t.length,n=0,o="";do o+=e.slice(n,r)+t+a,n=r+i,r=e.indexOf(t,n);while(-1!==r);return o+e.slice(n)}(t,a.close,a.open),a=a.parent;let n=t.indexOf("\n");return -1!==n&&(t=function(e,t,a,r){let i=0,n="";do{let o="\r"===e[r-1];n+=e.slice(i,o?r-1:r)+t+(o?"\r\n":"\n")+a,i=r+1,r=e.indexOf("\n",i)}while(-1!==r);return n+e.slice(i)}(t,i,r,n)),r+t+i};Object.defineProperties(pR.prototype,pI);let pD=pR();pR({level:pT?pT.level:0});let pF=pD.bold.green("✔");pD.bold.black.bgWhite(" XMCP ");let pU=pD.bold.yellow("❯");var pZ=a(9278),pH=a.n(pZ);async function pB(e=3001,t="127.0.0.1"){return new Promise(a=>{let r;(r=pH().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(`${pU} Port ${pD.yellow(String(e))} is in use, trying ${pD.yellow(String(e+1))} instead.`),pB(e+1).then(a))})})}let pV=to({origin:tc([e4(),tn(e4()),e5()]).default("*"),methods:tc([e4(),tn(e4())]).default(["GET","POST"]),allowedHeaders:tc([e4(),tn(e4())]).default(["Content-Type","Authorization","mcp-session-id","mcp-protocol-version"]),exposedHeaders:tc([e4(),tn(e4())]).default(["Content-Type","Authorization","mcp-session-id"]),credentials:e5().default(!1),maxAge:e2().default(86400)}),pJ=pV.parse({}),pK=pV.partial().transform(e=>{let t=Object.fromEntries(Object.entries(e).filter(([e,t])=>void 0!==t)),a={...pJ,...t};if(Array.isArray(a.allowedHeaders)){let e=new Set(a.allowedHeaders);e.add("mcp-session-id"),e.add("mcp-protocol-version"),a.allowedHeaders=Array.from(e)}if(Array.isArray(a.exposedHeaders)){let e=new Set(a.exposedHeaders);e.add("mcp-session-id"),a.exposedHeaders=Array.from(e)}return a}),pG=to({port:e2().default(3001),host:e4().default("127.0.0.1"),bodySizeLimit:e2().default(0xa00000),debug:e5().default(!1),endpoint:e4().default("/mcp"),cors:pK}),pW=pG.partial().transform(e=>{let t=pG.parse({cors:{}}),a=Object.fromEntries(Object.entries(e).filter(([e,t])=>void 0!==t));return{...t,...a}});tc([e5(),pW]).transform(e=>"boolean"==typeof e?e?{}:null:e).pipe(tc([tg(null),pW]));let pY=to({debug:e5().default(!1),silent:e5().default(!1)}),pQ=pY.partial().transform(e=>{let t=pY.parse({}),a=Object.fromEntries(Object.entries(e).filter(([e,t])=>void 0!==t));return{...t,...a}});tc([e5(),pQ]).optional(),to({adapter:ty(["express","nextjs","nestjs"]).optional()});let pX=to({tools:tc([e5(),e4()]).default(!0),prompts:tc([e5(),e4()]).default(!0),resources:tc([e5(),e4()]).default(!0)});pX.partial().transform(e=>{let t=pX.parse({}),a=Object.fromEntries(Object.entries(e).filter(([e,t])=>void 0!==t));return{...t,...a}}),E.function().args(E.any()).returns(E.any()).optional();let p0=to({name:e4().default("xmcp server"),description:e4().default("This MCP server was bootstrapped with xmcp."),icons:tn(to({src:e4(),mimeType:e4().optional(),sizes:tn(e4()).optional(),theme:ty(["light","dark"]).optional()})).optional(),homePage:e4().optional()});p0.partial().transform(e=>{let t=p0.parse({}),a=Object.fromEntries(Object.entries(e).filter(([e,t])=>void 0!==t));return{...t,...a}});let p1=to({skipTypeCheck:e5().default(!1)});p1.partial().transform(e=>{let t=p1.parse({}),a=Object.fromEntries(Object.entries(e).filter(([e,t])=>void 0!==t));return{...t,...a}});let p4=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),p2=e=>{if(e&&"initialize"===e.method&&p4(e.params)){var t=e.params.clientInfo;if(!p4(t)||"string"!=typeof t.name||"string"!=typeof t.version)return;let a={name:t.name,version:t.version};return"string"==typeof t.title&&(a.title=t.title),"string"==typeof t.websiteUrl&&(a.websiteUrl=t.websiteUrl),"string"==typeof t.description&&(a.description=t.description),a}};function p8(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}class p9{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:"session"})}),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,`
|
|
543
|
+
`,p_=(e=0)=>t=>`\u001B[${t+e}m`,pk=(e=0)=>t=>`\u001B[${38+e};5;${t}m`,pE=(e=0)=>(t,a,r)=>`\u001B[${38+e};2;${t};${a};${r}m`,p$={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(p$.modifier),[...Object.keys(p$.color),...Object.keys(p$.bgColor)];let pS=function(){let e=new Map;for(let[t,a]of Object.entries(p$)){for(let[t,r]of Object.entries(a))p$[t]={open:`\u001B[${r[0]}m`,close:`\u001B[${r[1]}m`},a[t]=p$[t],e.set(r[0],r[1]);Object.defineProperty(p$,t,{value:a,enumerable:!1})}return Object.defineProperty(p$,"codes",{value:e,enumerable:!1}),p$.color.close="\x1b[39m",p$.bgColor.close="\x1b[49m",p$.color.ansi=p_(),p$.color.ansi256=pk(),p$.color.ansi16m=pE(),p$.bgColor.ansi=p_(10),p$.bgColor.ansi256=pk(10),p$.bgColor.ansi16m=pE(10),Object.defineProperties(p$,{rgbToAnsi256:{value:(e,t,a)=>e===t&&t===a?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(a/255*5),enumerable:!1},hexToRgb:{value(e){let t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[a]=t;3===a.length&&(a=[...a].map(e=>e+e).join(""));let r=Number.parseInt(a,16);return[r>>16&255,r>>8&255,255&r]},enumerable:!1},hexToAnsi256:{value:e=>p$.rgbToAnsi256(...p$.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){let t,a,r;if(e<8)return 30+e;if(e<16)return 90+(e-8);if(e>=232)a=t=((e-232)*10+8)/255,r=t;else{let i=(e-=16)%36;t=Math.floor(e/36)/5,a=Math.floor(i/6)/5,r=i%6/5}let i=2*Math.max(t,a,r);if(0===i)return 30;let n=30+(Math.round(r)<<2|Math.round(a)<<1|Math.round(t));return 2===i&&(n+=60),n},enumerable:!1},rgbToAnsi:{value:(e,t,a)=>p$.ansi256ToAnsi(p$.rgbToAnsi256(e,t,a)),enumerable:!1},hexToAnsi:{value:e=>p$.ansi256ToAnsi(p$.hexToAnsi256(e)),enumerable:!1}}),p$}(),pj=require("node:process"),pT=require("node:os"),pO=require("node:tty");function pC(e,t=globalThis.Deno?globalThis.Deno.args:pj.argv){let a=e.startsWith("-")?"":1===e.length?"-":"--",r=t.indexOf(a+e),i=t.indexOf("--");return -1!==r&&(-1===i||r<i)}let{env:pP}=pj;function pA(e,a={}){var r;return 0!==(r=function(e,{streamIsTTY:a,sniffFlags:r=!0}={}){let i=function(){if("FORCE_COLOR"in pP)return"true"===pP.FORCE_COLOR?1:"false"===pP.FORCE_COLOR?0:0===pP.FORCE_COLOR.length?1:Math.min(Number.parseInt(pP.FORCE_COLOR,10),3)}();void 0!==i&&(t=i);let n=r?t:i;if(0===n)return 0;if(r){if(pC("color=16m")||pC("color=full")||pC("color=truecolor"))return 3;if(pC("color=256"))return 2}if("TF_BUILD"in pP&&"AGENT_NAME"in pP)return 1;if(e&&!a&&void 0===n)return 0;let o=n||0;if("dumb"===pP.TERM)return o;if("win32"===pj.platform){let e=pT.release().split(".");return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if("CI"in pP)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(e=>e in pP)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(e=>e in pP)||"codeship"===pP.CI_NAME?1:o;if("TEAMCITY_VERSION"in pP)return+!!/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(pP.TEAMCITY_VERSION);if("truecolor"===pP.COLORTERM||"xterm-kitty"===pP.TERM||"xterm-ghostty"===pP.TERM||"wezterm"===pP.TERM)return 3;if("TERM_PROGRAM"in pP){let e=Number.parseInt((pP.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(pP.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(pP.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(pP.TERM)||"COLORTERM"in pP?1:o}(e,{streamIsTTY:e&&e.isTTY,...a}))&&{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}pC("no-color")||pC("no-colors")||pC("color=false")||pC("color=never")?t=0:(pC("color")||pC("colors")||pC("color=true")||pC("color=always"))&&(t=1);let{stdout:pI,stderr:pR}={stdout:pA({isTTY:pO.isatty(1)}),stderr:pA({isTTY:pO.isatty(2)})},pN=Symbol("GENERATOR"),pz=Symbol("STYLER"),pq=Symbol("IS_EMPTY"),pL=["ansi","ansi","ansi256","ansi16m"],pM=Object.create(null);function pD(e){let t;return((e,t={})=>{if(t.level&&!(Number.isInteger(t.level)&&t.level>=0&&t.level<=3))throw Error("The `level` option should be an integer from 0 to 3");let a=pI?pI.level:0;e.level=void 0===t.level?a:t.level})(t=(...e)=>e.join(" "),e),Object.setPrototypeOf(t,pD.prototype),t}for(let[e,t]of(Object.setPrototypeOf(pD.prototype,Function.prototype),Object.entries(pS)))pM[e]={get(){let a=pH(this,pZ(t.open,t.close,this[pz]),this[pq]);return Object.defineProperty(this,e,{value:a}),a}};pM.visible={get(){let e=pH(this,this[pz],!0);return Object.defineProperty(this,"visible",{value:e}),e}};let pF=(e,t,a,...r)=>"rgb"===e?"ansi16m"===t?pS[a].ansi16m(...r):"ansi256"===t?pS[a].ansi256(pS.rgbToAnsi256(...r)):pS[a].ansi(pS.rgbToAnsi(...r)):"hex"===e?pF("rgb",t,a,...pS.hexToRgb(...r)):pS[a][e](...r);for(let e of["rgb","hex","ansi256"])pM[e]={get(){let{level:t}=this;return function(...a){return pH(this,pZ(pF(e,pL[t],"color",...a),pS.color.close,this[pz]),this[pq])}}},pM["bg"+e[0].toUpperCase()+e.slice(1)]={get(){let{level:t}=this;return function(...a){return pH(this,pZ(pF(e,pL[t],"bgColor",...a),pS.bgColor.close,this[pz]),this[pq])}}};let pU=Object.defineProperties(()=>{},{...pM,level:{enumerable:!0,get(){return this[pN].level},set(e){this[pN].level=e}}}),pZ=(e,t,a)=>{let r,i;return void 0===a?(r=e,i=t):(r=a.openAll+e,i=t+a.closeAll),{open:e,close:t,openAll:r,closeAll:i,parent:a}},pH=(e,t,a)=>{let r=(...e)=>pB(r,1===e.length?""+e[0]:e.join(" "));return Object.setPrototypeOf(r,pU),r[pN]=e,r[pz]=t,r[pq]=a,r},pB=(e,t)=>{if(e.level<=0||!t)return e[pq]?"":t;let a=e[pz];if(void 0===a)return t;let{openAll:r,closeAll:i}=a;if(t.includes("\x1b"))for(;void 0!==a;)t=function(e,t,a){let r=e.indexOf(t);if(-1===r)return e;let i=t.length,n=0,o="";do o+=e.slice(n,r)+t+a,n=r+i,r=e.indexOf(t,n);while(-1!==r);return o+e.slice(n)}(t,a.close,a.open),a=a.parent;let n=t.indexOf("\n");return -1!==n&&(t=function(e,t,a,r){let i=0,n="";do{let o="\r"===e[r-1];n+=e.slice(i,o?r-1:r)+t+(o?"\r\n":"\n")+a,i=r+1,r=e.indexOf("\n",i)}while(-1!==r);return n+e.slice(i)}(t,i,r,n)),r+t+i};Object.defineProperties(pD.prototype,pM);let pV=pD();pD({level:pR?pR.level:0});let pJ=pV.bold.green("✔");pV.bold.black.bgWhite(" XMCP ");let pK=pV.bold.yellow("❯");var pG=a(9278),pW=a.n(pG);async function pY(e=3001,t="127.0.0.1"){return new Promise(a=>{let r;(r=pW().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(`${pK} Port ${pV.yellow(String(e))} is in use, trying ${pV.yellow(String(e+1))} instead.`),pY(e+1).then(a))})})}let pQ=to({origin:tc([e4(),tn(e4()),e5()]).default("*"),methods:tc([e4(),tn(e4())]).default(["GET","POST"]),allowedHeaders:tc([e4(),tn(e4())]).default(["Content-Type","Authorization","mcp-session-id","mcp-protocol-version"]),exposedHeaders:tc([e4(),tn(e4())]).default(["Content-Type","Authorization","mcp-session-id"]),credentials:e5().default(!1),maxAge:e2().default(86400)}),pX=pQ.parse({}),p0=pQ.partial().transform(e=>{let t=Object.fromEntries(Object.entries(e).filter(([e,t])=>void 0!==t)),a={...pX,...t};if(Array.isArray(a.allowedHeaders)){let e=new Set(a.allowedHeaders);e.add("mcp-session-id"),e.add("mcp-protocol-version"),a.allowedHeaders=Array.from(e)}if(Array.isArray(a.exposedHeaders)){let e=new Set(a.exposedHeaders);e.add("mcp-session-id"),a.exposedHeaders=Array.from(e)}return a}),p1=to({port:e2().default(3001),host:e4().default("127.0.0.1"),bodySizeLimit:e2().default(0xa00000),debug:e5().default(!1),endpoint:e4().default("/mcp"),cors:p0}),p4=p1.partial().transform(e=>{let t=p1.parse({cors:{}}),a=Object.fromEntries(Object.entries(e).filter(([e,t])=>void 0!==t));return{...t,...a}});tc([e5(),p4]).transform(e=>"boolean"==typeof e?e?{}:null:e).pipe(tc([tg(null),p4]));let p2=to({debug:e5().default(!1),silent:e5().default(!1)}),p8=p2.partial().transform(e=>{let t=p2.parse({}),a=Object.fromEntries(Object.entries(e).filter(([e,t])=>void 0!==t));return{...t,...a}});tc([e5(),p8]).optional(),to({adapter:ty(["express","nextjs","nestjs"]).optional()});let p9=to({tools:tc([e5(),e4()]).default(!0),prompts:tc([e5(),e4()]).default(!0),resources:tc([e5(),e4()]).default(!0)});p9.partial().transform(e=>{let t=p9.parse({}),a=Object.fromEntries(Object.entries(e).filter(([e,t])=>void 0!==t));return{...t,...a}}),E.function().args(E.any()).returns(E.any()).optional();let p5=to({name:e4().default("xmcp server"),description:e4().default("This MCP server was bootstrapped with xmcp."),icons:tn(to({src:e4(),mimeType:e4().optional(),sizes:tn(e4()).optional(),theme:ty(["light","dark"]).optional()})).optional(),instructions:e4().optional(),homePage:e4().optional()});p5.partial().transform(e=>{let t=p5.parse({}),a=Object.fromEntries(Object.entries(e).filter(([e,t])=>void 0!==t));return{...t,...a}});let p6=to({skipTypeCheck:e5().default(!1)});p6.partial().transform(e=>{let t=p6.parse({}),a=Object.fromEntries(Object.entries(e).filter(([e,t])=>void 0!==t));return{...t,...a}});let p3=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),p7=e=>{if(e&&"initialize"===e.method&&p3(e.params)){var t=e.params.clientInfo;if(!p3(t)||"string"!=typeof t.name||"string"!=typeof t.version)return;let a={name:t.name,version:t.version};return"string"==typeof t.title&&(a.title=t.title),"string"==typeof t.websiteUrl&&(a.websiteUrl=t.websiteUrl),"string"==typeof t.description&&(a.description=t.description),a}};function ue(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}class ut extends py{log(e,...t){this.debug&&console.log(`[StatelessHTTP] ${e}`,...t)}async start(){await this.transport.start()}async close(){await this.transport.close()}async send(e,t){await this.transport.send(e,t)}async handleRequest(e,t,a){this.log(`${e.method} ${e.url??e.headers.host??"/mcp"}`),await this.transport.handleRequest(e,t,a)}constructor(e,t){super(),ue(this,"debug",void 0),ue(this,"transport",void 0),this.debug=e,this.transport=new pm({sessionIdGenerator:void 0}),this.transport.onmessage=(e,t)=>{this.onmessage?.(e,t)},this.transport.onerror=e=>{this.onerror?.(e)},this.transport.onclose=()=>{this.onclose?.()}}}class ua{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,`
|
|
542
544
|
<!DOCTYPE html>
|
|
543
545
|
<html lang="en">
|
|
544
546
|
<head>
|
|
@@ -559,7 +561,7 @@ data:
|
|
|
559
561
|
rel="stylesheet"
|
|
560
562
|
/>
|
|
561
563
|
<style>
|
|
562
|
-
${
|
|
564
|
+
${pw}
|
|
563
565
|
</style>
|
|
564
566
|
</head>
|
|
565
567
|
<body>
|
|
@@ -569,7 +571,7 @@ ${ph}
|
|
|
569
571
|
<div class="section-header">
|
|
570
572
|
<h2 id="server-name" class="display text-gradient">xmcp server</h2>
|
|
571
573
|
<p id="server-description" class="lead">
|
|
572
|
-
${i||
|
|
574
|
+
${i||pb}
|
|
573
575
|
</p>
|
|
574
576
|
</div>
|
|
575
577
|
</div>
|
|
@@ -676,7 +678,7 @@ ${`
|
|
|
676
678
|
(templateConfig.serverName && templateConfig.serverName.trim()) || "xmcp server";
|
|
677
679
|
const resolvedDescription =
|
|
678
680
|
(templateConfig.serverDescription && templateConfig.serverDescription.trim()) ||
|
|
679
|
-
"${
|
|
681
|
+
"${pb}";
|
|
680
682
|
const endpointPath =
|
|
681
683
|
(templateConfig.endpoint && templateConfig.endpoint.trim()) || "/";
|
|
682
684
|
const normalizedEndpoint = endpointPath.startsWith("/")
|
|
@@ -698,7 +700,7 @@ ${`
|
|
|
698
700
|
elements.description.textContent = resolvedDescription;
|
|
699
701
|
}
|
|
700
702
|
|
|
701
|
-
const icons = ${JSON.stringify(
|
|
703
|
+
const icons = ${JSON.stringify(px)};
|
|
702
704
|
|
|
703
705
|
const connectionOptions = [
|
|
704
706
|
{
|
|
@@ -901,4 +903,4 @@ args = ["-y", "mcp-remote", "\${serverUrl}"]\`,
|
|
|
901
903
|
</script>
|
|
902
904
|
</body>
|
|
903
905
|
</html>
|
|
904
|
-
`))}),this.setupOpenAIAppsChallengeRoute(),this.app.use((e,t,a)=>{c4({id:(0,
|
|
906
|
+
`))}),this.setupOpenAIAppsChallengeRoute(),this.app.use((e,t,a)=>{c4({id:(0,pv.randomUUID)(),headers:e.headers},()=>{a()})})}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){try{let a=(e=>{for(let t of Array.isArray(e)?e:[e]){let e=p7(t);if(e)return e}})(e.body),r=await this.createServerFn(),i=new ut(this.debug,this.options.bodySizeLimit||"10mb");t.on("finish",()=>{global.__XMCP_CURRENT_TOOL_NAME=void 0}),t.on("close",()=>{i.close(),r.close(),global.__XMCP_CURRENT_TOOL_NAME=void 0}),c0({clientInfo:a}),await r.connect(i),await i.handleRequest(e,t,e.body)}catch(e){console.error("[HTTP-server] Error handling MCP request:",e),t.headersSent||t.status(500).json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:null})}}async start(){let e=this.options.host||"127.0.0.1",t=await pY(this.port,e);this.server.listen(t,e,()=>{console.log(`${pJ} 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.server.close(),process.exit(0)}constructor(e,t={},a=p0.parse({}),r){ue(this,"app",void 0),ue(this,"server",void 0),ue(this,"port",void 0),ue(this,"endpoint",void 0),ue(this,"debug",void 0),ue(this,"options",void 0),ue(this,"createServerFn",void 0),ue(this,"corsConfig",void 0),ue(this,"providers",void 0),this.options={...t},this.app=ph()(),this.server=lZ().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.app.use(ph().json({limit:this.options.bodySizeLimit||"10mb"})),this.setupInitialRoutes(),this.setupInitialMiddleware(),this.setupProviders(),this.setupEndpointRoute()}}function ur(e){return"function"==typeof e}function ui(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 un=cQ({name:"http-transport-context"});un.setContext,un.getContext;let uo=un.provider;var us=a(8583);a.n(us)().config();let uc=HTTP_CONFIG,ul=HTTP_CORS_CONFIG,up=TEMPLATE_CONFIG,uu=INJECTED_MIDDLEWARE;!async function(){let e={port:uc?.port,host:uc?.host,debug:uc?.debug,bodySizeLimit:uc?.bodySizeLimit?.toString(),endpoint:uc?.endpoint,template:up},t={origin:ul.origin,methods:ul.methods,allowedHeaders:ul.allowedHeaders,exposedHeaders:ul.exposedHeaders,credentials:ul.credentials,maxAge:ul.maxAge},a=[];if(uu){let e=await uu();e&&e.default&&(a=function(e){let t=[];if(Array.isArray(e))for(let a of e)ur(a)?t.push({middleware:a}):ui(a)&&t.push({middleware:a.middleware,router:a.router});else ur(e)?t.push({middleware:e}):ui(e)&&t.push({middleware:e.middleware,router:e.router});return t}(e.default))}uo({config:{http:uc}},async()=>{let r=new ua(lF,e,t,a);await r.start()})}()})(),{}})());
|