@stophy/mcp 1.0.4 → 1.0.5

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.
Files changed (2) hide show
  1. package/dist/index.js +1 -1
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -39,4 +39,4 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
39
39
  ]))`;continue}else if(W[B]==="$"){$+=`($|(?=[\r
40
40
  ]))`;continue}}if(Y.s&&W[B]==="."){$+=G?`${W[B]}\r
41
41
  `:`[${W[B]}\r
42
- ]`;continue}if($+=W[B],W[B]==="\\")J=!0;else if(G&&W[B]==="]")G=!1;else if(!G&&W[B]==="[")G=!0}try{new RegExp($)}catch{return console.warn(`Could not convert regex pattern at ${X.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),Q.source}return $}function u9(Q,X){if(X.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if(X.target==="openApi3"&&Q.keyType?._def.typeName===M.ZodEnum)return{type:"object",required:Q.keyType._def.values,properties:Q.keyType._def.values.reduce((W,$)=>({...W,[$]:g(Q.valueType._def,{...X,currentPath:[...X.currentPath,"properties",$]})??B0(X)}),{}),additionalProperties:X.rejectedAdditionalProperties};let Y={type:"object",additionalProperties:g(Q.valueType._def,{...X,currentPath:[...X.currentPath,"additionalProperties"]})??X.allowedAdditionalProperties};if(X.target==="openApi3")return Y;if(Q.keyType?._def.typeName===M.ZodString&&Q.keyType._def.checks?.length){let{type:W,...$}=f9(Q.keyType._def,X);return{...Y,propertyNames:$}}else if(Q.keyType?._def.typeName===M.ZodEnum)return{...Y,propertyNames:{enum:Q.keyType._def.values}};else if(Q.keyType?._def.typeName===M.ZodBranded&&Q.keyType._def.type._def.typeName===M.ZodString&&Q.keyType._def.type._def.checks?.length){let{type:W,...$}=h9(Q.keyType._def,X);return{...Y,propertyNames:$}}return Y}function $7(Q,X){if(X.mapStrategy==="record")return u9(Q,X);let Y=g(Q.keyType._def,{...X,currentPath:[...X.currentPath,"items","items","0"]})||B0(X),W=g(Q.valueType._def,{...X,currentPath:[...X.currentPath,"items","items","1"]})||B0(X);return{type:"array",maxItems:125,items:{type:"array",items:[Y,W],minItems:2,maxItems:2}}}function J7(Q){let X=Q.values,W=Object.keys(Q.values).filter((J)=>{return typeof X[X[J]]!=="number"}).map((J)=>X[J]),$=Array.from(new Set(W.map((J)=>typeof J)));return{type:$.length===1?$[0]==="string"?"string":"number":["string","number"],enum:W}}function G7(Q){return Q.target==="openAi"?void 0:{not:B0({...Q,currentPath:[...Q.currentPath,"not"]})}}function H7(Q){return Q.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var O4={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function z7(Q,X){if(X.target==="openApi3")return B7(Q,X);let Y=Q.options instanceof Map?Array.from(Q.options.values()):Q.options;if(Y.every((W)=>(W._def.typeName in O4)&&(!W._def.checks||!W._def.checks.length))){let W=Y.reduce(($,J)=>{let G=O4[J._def.typeName];return G&&!$.includes(G)?[...$,G]:$},[]);return{type:W.length>1?W:W[0]}}else if(Y.every((W)=>W._def.typeName==="ZodLiteral"&&!W.description)){let W=Y.reduce(($,J)=>{let G=typeof J._def.value;switch(G){case"string":case"number":case"boolean":return[...$,G];case"bigint":return[...$,"integer"];case"object":if(J._def.value===null)return[...$,"null"];case"symbol":case"undefined":case"function":default:return $}},[]);if(W.length===Y.length){let $=W.filter((J,G,H)=>H.indexOf(J)===G);return{type:$.length>1?$:$[0],enum:Y.reduce((J,G)=>{return J.includes(G._def.value)?J:[...J,G._def.value]},[])}}}else if(Y.every((W)=>W._def.typeName==="ZodEnum"))return{type:"string",enum:Y.reduce((W,$)=>[...W,...$._def.values.filter((J)=>!W.includes(J))],[])};return B7(Q,X)}var B7=(Q,X)=>{let Y=(Q.options instanceof Map?Array.from(Q.options.values()):Q.options).map((W,$)=>g(W._def,{...X,currentPath:[...X.currentPath,"anyOf",`${$}`]})).filter((W)=>!!W&&(!X.strictUnions||typeof W==="object"&&Object.keys(W).length>0));return Y.length?{anyOf:Y}:void 0};function A7(Q,X){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(Q.innerType._def.typeName)&&(!Q.innerType._def.checks||!Q.innerType._def.checks.length)){if(X.target==="openApi3")return{type:O4[Q.innerType._def.typeName],nullable:!0};return{type:[O4[Q.innerType._def.typeName],"null"]}}if(X.target==="openApi3"){let W=g(Q.innerType._def,{...X,currentPath:[...X.currentPath]});if(W&&"$ref"in W)return{allOf:[W],nullable:!0};return W&&{...W,nullable:!0}}let Y=g(Q.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","0"]});return Y&&{anyOf:[Y,{type:"null"}]}}function K7(Q,X){let Y={type:"number"};if(!Q.checks)return Y;for(let W of Q.checks)switch(W.kind){case"int":Y.type="integer",YY(Y,"type",W.message,X);break;case"min":if(X.target==="jsonSchema7")if(W.inclusive)n(Y,"minimum",W.value,W.message,X);else n(Y,"exclusiveMinimum",W.value,W.message,X);else{if(!W.inclusive)Y.exclusiveMinimum=!0;n(Y,"minimum",W.value,W.message,X)}break;case"max":if(X.target==="jsonSchema7")if(W.inclusive)n(Y,"maximum",W.value,W.message,X);else n(Y,"exclusiveMaximum",W.value,W.message,X);else{if(!W.inclusive)Y.exclusiveMaximum=!0;n(Y,"maximum",W.value,W.message,X)}break;case"multipleOf":n(Y,"multipleOf",W.value,W.message,X);break}return Y}function D7(Q,X){let Y=X.target==="openAi",W={type:"object",properties:{}},$=[],J=Q.shape();for(let H in J){let B=J[H];if(B===void 0||B._def===void 0)continue;let z=kL(B);if(z&&Y){if(B._def.typeName==="ZodOptional")B=B._def.innerType;if(!B.isNullable())B=B.nullable();z=!1}let A=g(B._def,{...X,currentPath:[...X.currentPath,"properties",H],propertyPath:[...X.currentPath,"properties",H]});if(A===void 0)continue;if(W.properties[H]=A,!z)$.push(H)}if($.length)W.required=$;let G=vL(Q,X);if(G!==void 0)W.additionalProperties=G;return W}function vL(Q,X){if(Q.catchall._def.typeName!=="ZodNever")return g(Q.catchall._def,{...X,currentPath:[...X.currentPath,"additionalProperties"]});switch(Q.unknownKeys){case"passthrough":return X.allowedAdditionalProperties;case"strict":return X.rejectedAdditionalProperties;case"strip":return X.removeAdditionalStrategy==="strict"?X.allowedAdditionalProperties:X.rejectedAdditionalProperties}}function kL(Q){try{return Q.isOptional()}catch{return!0}}var L7=(Q,X)=>{if(X.currentPath.toString()===X.propertyPath?.toString())return g(Q.innerType._def,X);let Y=g(Q.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","1"]});return Y?{anyOf:[{not:B0(X)},Y]}:B0(X)};var q7=(Q,X)=>{if(X.pipeStrategy==="input")return g(Q.in._def,X);else if(X.pipeStrategy==="output")return g(Q.out._def,X);let Y=g(Q.in._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),W=g(Q.out._def,{...X,currentPath:[...X.currentPath,"allOf",Y?"1":"0"]});return{allOf:[Y,W].filter(($)=>$!==void 0)}};function F7(Q,X){return g(Q.type._def,X)}function V7(Q,X){let W={type:"array",uniqueItems:!0,items:g(Q.valueType._def,{...X,currentPath:[...X.currentPath,"items"]})};if(Q.minSize)n(W,"minItems",Q.minSize.value,Q.minSize.message,X);if(Q.maxSize)n(W,"maxItems",Q.maxSize.value,Q.maxSize.message,X);return W}function U7(Q,X){if(Q.rest)return{type:"array",minItems:Q.items.length,items:Q.items.map((Y,W)=>g(Y._def,{...X,currentPath:[...X.currentPath,"items",`${W}`]})).reduce((Y,W)=>W===void 0?Y:[...Y,W],[]),additionalItems:g(Q.rest._def,{...X,currentPath:[...X.currentPath,"additionalItems"]})};else return{type:"array",minItems:Q.items.length,maxItems:Q.items.length,items:Q.items.map((Y,W)=>g(Y._def,{...X,currentPath:[...X.currentPath,"items",`${W}`]})).reduce((Y,W)=>W===void 0?Y:[...Y,W],[])}}function O7(Q){return{not:B0(Q)}}function N7(Q){return B0(Q)}var w7=(Q,X)=>{return g(Q.innerType._def,X)};var M7=(Q,X,Y)=>{switch(X){case M.ZodString:return f9(Q,Y);case M.ZodNumber:return K7(Q,Y);case M.ZodObject:return D7(Q,Y);case M.ZodBigInt:return rJ(Q,Y);case M.ZodBoolean:return tJ();case M.ZodDate:return WY(Q,Y);case M.ZodUndefined:return O7(Y);case M.ZodNull:return H7(Y);case M.ZodArray:return oJ(Q,Y);case M.ZodUnion:case M.ZodDiscriminatedUnion:return z7(Q,Y);case M.ZodIntersection:return X7(Q,Y);case M.ZodTuple:return U7(Q,Y);case M.ZodRecord:return u9(Q,Y);case M.ZodLiteral:return Y7(Q,Y);case M.ZodEnum:return Q7(Q);case M.ZodNativeEnum:return J7(Q);case M.ZodNullable:return A7(Q,Y);case M.ZodOptional:return L7(Q,Y);case M.ZodMap:return $7(Q,Y);case M.ZodSet:return V7(Q,Y);case M.ZodLazy:return()=>Q.getter()._def;case M.ZodPromise:return F7(Q,Y);case M.ZodNaN:case M.ZodNever:return G7(Y);case M.ZodEffects:return eJ(Q,Y);case M.ZodAny:return B0(Y);case M.ZodUnknown:return N7(Y);case M.ZodDefault:return sJ(Q,Y);case M.ZodBranded:return h9(Q,Y);case M.ZodReadonly:return w7(Q,Y);case M.ZodCatch:return aJ(Q,Y);case M.ZodPipeline:return q7(Q,Y);case M.ZodFunction:case M.ZodVoid:case M.ZodSymbol:return;default:return((W)=>{return})(X)}};function g(Q,X,Y=!1){let W=X.seen.get(Q);if(X.override){let H=X.override?.(Q,X,W,Y);if(H!==iJ)return H}if(W&&!Y){let H=_L(W,X);if(H!==void 0)return H}let $={def:Q,path:X.currentPath,jsonSchema:void 0};X.seen.set(Q,$);let J=M7(Q,Q.typeName,X),G=typeof J==="function"?g(J(),X):J;if(G)xL(Q,X,G);if(X.postProcess){let H=X.postProcess(G,Q,X);return $.jsonSchema=G,H}return $.jsonSchema=G,G}var _L=(Q,X)=>{switch(X.$refStrategy){case"root":return{$ref:Q.path.join("/")};case"relative":return{$ref:y9(X.currentPath,Q.path)};case"none":case"seen":{if(Q.path.length<X.currentPath.length&&Q.path.every((Y,W)=>X.currentPath[W]===Y))return console.warn(`Recursive reference detected at ${X.currentPath.join("/")}! Defaulting to any`),B0(X);return X.$refStrategy==="seen"?B0(X):void 0}}},xL=(Q,X,Y)=>{if(Q.description){if(Y.description=Q.description,X.markdownDescription)Y.markdownDescription=Q.description}return Y};var GY=(Q,X)=>{let Y=dJ(X),W=typeof X==="object"&&X.definitions?Object.entries(X.definitions).reduce((B,[z,A])=>({...B,[z]:g(A._def,{...Y,currentPath:[...Y.basePath,Y.definitionPath,z]},!0)??B0(Y)}),{}):void 0,$=typeof X==="string"?X:X?.nameStrategy==="title"?void 0:X?.name,J=g(Q._def,$===void 0?Y:{...Y,currentPath:[...Y.basePath,Y.definitionPath,$]},!1)??B0(Y),G=typeof X==="object"&&X.name!==void 0&&X.nameStrategy==="title"?X.name:void 0;if(G!==void 0)J.title=G;if(Y.flags.hasReferencedOpenAiAnyType){if(!W)W={};if(!W[Y.openAiAnyTypeName])W[Y.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:Y.$refStrategy==="relative"?"1":[...Y.basePath,Y.definitionPath,Y.openAiAnyTypeName].join("/")}}}let H=$===void 0?W?{...J,[Y.definitionPath]:W}:J:{$ref:[...Y.$refStrategy==="relative"?[]:Y.basePath,Y.definitionPath,$].join("/"),[Y.definitionPath]:{...W,[$]:J}};if(Y.target==="jsonSchema7")H.$schema="http://json-schema.org/draft-07/schema#";else if(Y.target==="jsonSchema2019-09"||Y.target==="openAi")H.$schema="https://json-schema.org/draft/2019-09/schema#";if(Y.target==="openAi"&&(("anyOf"in H)||("oneOf"in H)||("allOf"in H)||("type"in H)&&Array.isArray(H.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return H};function gL(Q){if(!Q)return"draft-7";if(Q==="jsonSchema7"||Q==="draft-7")return"draft-7";if(Q==="jsonSchema2019-09"||Q==="draft-2020-12")return"draft-2020-12";return"draft-7"}function HY(Q,X){if(u0(Q))return EX(Q,{target:gL(X?.target),io:X?.pipeStrategy??"input"});return GY(Q,{strictUnions:X?.strictUnions??!0,pipeStrategy:X?.pipeStrategy??"input"})}function BY(Q){let Y=P1(Q)?.method;if(!Y)throw Error("Schema is missing a method literal");let W=g9(Y);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function zY(Q,X){let Y=S1(Q,X);if(!Y.success)throw Y.error;return Y.data}var yL=60000;class AY{constructor(Q){if(this._options=Q,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(L9,(X)=>{this._oncancel(X)}),this.setNotificationHandler(F9,(X)=>{this._onprogress(X)}),this.setRequestHandler(q9,(X)=>({})),this._taskStore=Q?.taskStore,this._taskMessageQueue=Q?.taskMessageQueue,this._taskStore)this.setRequestHandler(V9,async(X,Y)=>{let W=await this._taskStore.getTask(X.params.taskId,Y.sessionId);if(!W)throw new C(v.InvalidParams,"Failed to retrieve task: Task not found");return{...W}}),this.setRequestHandler(O9,async(X,Y)=>{let W=async()=>{let $=X.params.taskId;if(this._taskMessageQueue){let G;while(G=await this._taskMessageQueue.dequeue($,Y.sessionId)){if(G.type==="response"||G.type==="error"){let H=G.message,B=H.id,z=this._requestResolvers.get(B);if(z)if(this._requestResolvers.delete(B),G.type==="response")z(H);else{let A=H,D=new C(A.error.code,A.error.message,A.error.data);z(D)}else{let A=G.type==="response"?"Response":"Error";this._onerror(Error(`${A} handler missing for request ${B}`))}continue}await this._transport?.send(G.message,{relatedRequestId:Y.requestId})}}let J=await this._taskStore.getTask($,Y.sessionId);if(!J)throw new C(v.InvalidParams,`Task not found: ${$}`);if(!I1(J.status))return await this._waitForTaskUpdate($,Y.signal),await W();if(I1(J.status)){let G=await this._taskStore.getTaskResult($,Y.sessionId);return this._clearTaskQueue($),{...G,_meta:{...G._meta,[N1]:{taskId:$}}}}return await W()};return await W()}),this.setRequestHandler(N9,async(X,Y)=>{try{let{tasks:W,nextCursor:$}=await this._taskStore.listTasks(X.params?.cursor,Y.sessionId);return{tasks:W,nextCursor:$,_meta:{}}}catch(W){throw new C(v.InvalidParams,`Failed to list tasks: ${W instanceof Error?W.message:String(W)}`)}}),this.setRequestHandler(M9,async(X,Y)=>{try{let W=await this._taskStore.getTask(X.params.taskId,Y.sessionId);if(!W)throw new C(v.InvalidParams,`Task not found: ${X.params.taskId}`);if(I1(W.status))throw new C(v.InvalidParams,`Cannot cancel task in terminal status: ${W.status}`);await this._taskStore.updateTaskStatus(X.params.taskId,"cancelled","Client cancelled task execution.",Y.sessionId),this._clearTaskQueue(X.params.taskId);let $=await this._taskStore.getTask(X.params.taskId,Y.sessionId);if(!$)throw new C(v.InvalidParams,`Task not found after cancellation: ${X.params.taskId}`);return{_meta:{},...$}}catch(W){if(W instanceof C)throw W;throw new C(v.InvalidRequest,`Failed to cancel task: ${W instanceof Error?W.message:String(W)}`)}})}async _oncancel(Q){if(!Q.params.requestId)return;this._requestHandlerAbortControllers.get(Q.params.requestId)?.abort(Q.params.reason)}_setupTimeout(Q,X,Y,W,$=!1){this._timeoutInfo.set(Q,{timeoutId:setTimeout(W,X),startTime:Date.now(),timeout:X,maxTotalTimeout:Y,resetTimeoutOnProgress:$,onTimeout:W})}_resetTimeout(Q){let X=this._timeoutInfo.get(Q);if(!X)return!1;let Y=Date.now()-X.startTime;if(X.maxTotalTimeout&&Y>=X.maxTotalTimeout)throw this._timeoutInfo.delete(Q),C.fromError(v.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:X.maxTotalTimeout,totalElapsed:Y});return clearTimeout(X.timeoutId),X.timeoutId=setTimeout(X.onTimeout,X.timeout),!0}_cleanupTimeout(Q){let X=this._timeoutInfo.get(Q);if(X)clearTimeout(X.timeoutId),this._timeoutInfo.delete(Q)}async connect(Q){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=Q;let X=this.transport?.onclose;this._transport.onclose=()=>{X?.(),this._onclose()};let Y=this.transport?.onerror;this._transport.onerror=($)=>{Y?.($),this._onerror($)};let W=this._transport?.onmessage;this._transport.onmessage=($,J)=>{if(W?.($,J),Y4($)||UJ($))this._onresponse($);else if(xX($))this._onrequest($,J);else if(VJ($))this._onnotification($);else this._onerror(Error(`Unknown message type: ${JSON.stringify($)}`))},await this._transport.start()}_onclose(){let Q=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let Y of this._timeoutInfo.values())clearTimeout(Y.timeoutId);this._timeoutInfo.clear();for(let Y of this._requestHandlerAbortControllers.values())Y.abort();this._requestHandlerAbortControllers.clear();let X=C.fromError(v.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let Y of Q.values())Y(X)}_onerror(Q){this.onerror?.(Q)}_onnotification(Q){let X=this._notificationHandlers.get(Q.method)??this.fallbackNotificationHandler;if(X===void 0)return;Promise.resolve().then(()=>X(Q)).catch((Y)=>this._onerror(Error(`Uncaught error in notification handler: ${Y}`)))}_onrequest(Q,X){let Y=this._requestHandlers.get(Q.method)??this.fallbackRequestHandler,W=this._transport,$=Q.params?._meta?.[N1]?.taskId;if(Y===void 0){let z={jsonrpc:"2.0",id:Q.id,error:{code:v.MethodNotFound,message:"Method not found"}};if($&&this._taskMessageQueue)this._enqueueTaskMessage($,{type:"error",message:z,timestamp:Date.now()},W?.sessionId).catch((A)=>this._onerror(Error(`Failed to enqueue error response: ${A}`)));else W?.send(z).catch((A)=>this._onerror(Error(`Failed to send an error response: ${A}`)));return}let J=new AbortController;this._requestHandlerAbortControllers.set(Q.id,J);let G=LJ(Q.params)?Q.params.task:void 0,H=this._taskStore?this.requestTaskStore(Q,W?.sessionId):void 0,B={signal:J.signal,sessionId:W?.sessionId,_meta:Q.params?._meta,sendNotification:async(z)=>{if(J.signal.aborted)return;let A={relatedRequestId:Q.id};if($)A.relatedTask={taskId:$};await this.notification(z,A)},sendRequest:async(z,A,D)=>{if(J.signal.aborted)throw new C(v.ConnectionClosed,"Request was cancelled");let L={...D,relatedRequestId:Q.id};if($&&!L.relatedTask)L.relatedTask={taskId:$};let K=L.relatedTask?.taskId??$;if(K&&H)await H.updateTaskStatus(K,"input_required");return await this.request(z,A,L)},authInfo:X?.authInfo,requestId:Q.id,requestInfo:X?.requestInfo,taskId:$,taskStore:H,taskRequestedTtl:G?.ttl,closeSSEStream:X?.closeSSEStream,closeStandaloneSSEStream:X?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(G)this.assertTaskHandlerCapability(Q.method)}).then(()=>Y(Q,B)).then(async(z)=>{if(J.signal.aborted)return;let A={result:z,jsonrpc:"2.0",id:Q.id};if($&&this._taskMessageQueue)await this._enqueueTaskMessage($,{type:"response",message:A,timestamp:Date.now()},W?.sessionId);else await W?.send(A)},async(z)=>{if(J.signal.aborted)return;let A={jsonrpc:"2.0",id:Q.id,error:{code:Number.isSafeInteger(z.code)?z.code:v.InternalError,message:z.message??"Internal error",...z.data!==void 0&&{data:z.data}}};if($&&this._taskMessageQueue)await this._enqueueTaskMessage($,{type:"error",message:A,timestamp:Date.now()},W?.sessionId);else await W?.send(A)}).catch((z)=>this._onerror(Error(`Failed to send response: ${z}`))).finally(()=>{if(this._requestHandlerAbortControllers.get(Q.id)===J)this._requestHandlerAbortControllers.delete(Q.id)})}_onprogress(Q){let{progressToken:X,...Y}=Q.params,W=Number(X),$=this._progressHandlers.get(W);if(!$){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(Q)}`));return}let J=this._responseHandlers.get(W),G=this._timeoutInfo.get(W);if(G&&J&&G.resetTimeoutOnProgress)try{this._resetTimeout(W)}catch(H){this._responseHandlers.delete(W),this._progressHandlers.delete(W),this._cleanupTimeout(W),J(H);return}$(Y)}_onresponse(Q){let X=Number(Q.id),Y=this._requestResolvers.get(X);if(Y){if(this._requestResolvers.delete(X),Y4(Q))Y(Q);else{let J=new C(Q.error.code,Q.error.message,Q.error.data);Y(J)}return}let W=this._responseHandlers.get(X);if(W===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(Q)}`));return}this._responseHandlers.delete(X),this._cleanupTimeout(X);let $=!1;if(Y4(Q)&&Q.result&&typeof Q.result==="object"){let J=Q.result;if(J.task&&typeof J.task==="object"){let G=J.task;if(typeof G.taskId==="string")$=!0,this._taskProgressTokens.set(G.taskId,X)}}if(!$)this._progressHandlers.delete(X);if(Y4(Q))W(Q);else{let J=C.fromError(Q.error.code,Q.error.message,Q.error.data);W(J)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(Q,X,Y){let{task:W}=Y??{};if(!W){try{yield{type:"result",result:await this.request(Q,X,Y)}}catch(J){yield{type:"error",error:J instanceof C?J:new C(v.InternalError,String(J))}}return}let $;try{let J=await this.request(Q,G6,Y);if(J.task)$=J.task.taskId,yield{type:"taskCreated",task:J.task};else throw new C(v.InternalError,"Task creation did not return a task");while(!0){let G=await this.getTask({taskId:$},Y);if(yield{type:"taskStatus",task:G},I1(G.status)){if(G.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:$},X,Y)};else if(G.status==="failed")yield{type:"error",error:new C(v.InternalError,`Task ${$} failed`)};else if(G.status==="cancelled")yield{type:"error",error:new C(v.InternalError,`Task ${$} was cancelled`)};return}if(G.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:$},X,Y)};return}let H=G.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((B)=>setTimeout(B,H)),Y?.signal?.throwIfAborted()}}catch(J){yield{type:"error",error:J instanceof C?J:new C(v.InternalError,String(J))}}}request(Q,X,Y){let{relatedRequestId:W,resumptionToken:$,onresumptiontoken:J,task:G,relatedTask:H}=Y??{};return new Promise((B,z)=>{let A=(O)=>{z(O)};if(!this._transport){A(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(Q.method),G)this.assertTaskCapability(Q.method)}catch(O){A(O);return}Y?.signal?.throwIfAborted();let D=this._requestMessageId++,L={...Q,jsonrpc:"2.0",id:D};if(Y?.onprogress)this._progressHandlers.set(D,Y.onprogress),L.params={...Q.params,_meta:{...Q.params?._meta||{},progressToken:D}};if(G)L.params={...L.params,task:G};if(H)L.params={...L.params,_meta:{...L.params?._meta||{},[N1]:H}};let K=(O)=>{this._responseHandlers.delete(D),this._progressHandlers.delete(D),this._cleanupTimeout(D),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:D,reason:String(O)}},{relatedRequestId:W,resumptionToken:$,onresumptiontoken:J}).catch((E)=>this._onerror(Error(`Failed to send cancellation: ${E}`)));let b=O instanceof C?O:new C(v.RequestTimeout,String(O));z(b)};this._responseHandlers.set(D,(O)=>{if(Y?.signal?.aborted)return;if(O instanceof Error)return z(O);try{let b=S1(X,O.result);if(!b.success)z(b.error);else B(b.data)}catch(b){z(b)}}),Y?.signal?.addEventListener("abort",()=>{K(Y?.signal?.reason)});let q=Y?.timeout??yL,F=()=>K(C.fromError(v.RequestTimeout,"Request timed out",{timeout:q}));this._setupTimeout(D,q,Y?.maxTotalTimeout,F,Y?.resetTimeoutOnProgress??!1);let N=H?.taskId;if(N){let O=(b)=>{let E=this._responseHandlers.get(D);if(E)E(b);else this._onerror(Error(`Response handler missing for side-channeled request ${D}`))};this._requestResolvers.set(D,O),this._enqueueTaskMessage(N,{type:"request",message:L,timestamp:Date.now()}).catch((b)=>{this._cleanupTimeout(D),z(b)})}else this._transport.send(L,{relatedRequestId:W,resumptionToken:$,onresumptiontoken:J}).catch((O)=>{this._cleanupTimeout(D),z(O)})})}async getTask(Q,X){return this.request({method:"tasks/get",params:Q},U9,X)}async getTaskResult(Q,X,Y){return this.request({method:"tasks/result",params:Q},X,Y)}async listTasks(Q,X){return this.request({method:"tasks/list",params:Q},w9,X)}async cancelTask(Q,X){return this.request({method:"tasks/cancel",params:Q},wJ,X)}async notification(Q,X){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(Q.method);let Y=X?.relatedTask?.taskId;if(Y){let G={...Q,jsonrpc:"2.0",params:{...Q.params,_meta:{...Q.params?._meta||{},[N1]:X.relatedTask}}};await this._enqueueTaskMessage(Y,{type:"notification",message:G,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(Q.method)&&!Q.params&&!X?.relatedRequestId&&!X?.relatedTask){if(this._pendingDebouncedNotifications.has(Q.method))return;this._pendingDebouncedNotifications.add(Q.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(Q.method),!this._transport)return;let G={...Q,jsonrpc:"2.0"};if(X?.relatedTask)G={...G,params:{...G.params,_meta:{...G.params?._meta||{},[N1]:X.relatedTask}}};this._transport?.send(G,X).catch((H)=>this._onerror(H))});return}let J={...Q,jsonrpc:"2.0"};if(X?.relatedTask)J={...J,params:{...J.params,_meta:{...J.params?._meta||{},[N1]:X.relatedTask}}};await this._transport.send(J,X)}setRequestHandler(Q,X){let Y=BY(Q);this.assertRequestHandlerCapability(Y),this._requestHandlers.set(Y,(W,$)=>{let J=zY(Q,W);return Promise.resolve(X(J,$))})}removeRequestHandler(Q){this._requestHandlers.delete(Q)}assertCanSetRequestHandler(Q){if(this._requestHandlers.has(Q))throw Error(`A request handler for ${Q} already exists, which would be overridden`)}setNotificationHandler(Q,X){let Y=BY(Q);this._notificationHandlers.set(Y,(W)=>{let $=zY(Q,W);return Promise.resolve(X($))})}removeNotificationHandler(Q){this._notificationHandlers.delete(Q)}_cleanupTaskProgressHandler(Q){let X=this._taskProgressTokens.get(Q);if(X!==void 0)this._progressHandlers.delete(X),this._taskProgressTokens.delete(Q)}async _enqueueTaskMessage(Q,X,Y){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let W=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(Q,X,Y,W)}async _clearTaskQueue(Q,X){if(this._taskMessageQueue){let Y=await this._taskMessageQueue.dequeueAll(Q,X);for(let W of Y)if(W.type==="request"&&xX(W.message)){let $=W.message.id,J=this._requestResolvers.get($);if(J)J(new C(v.InternalError,"Task cancelled or completed")),this._requestResolvers.delete($);else this._onerror(Error(`Resolver missing for request ${$} during task ${Q} cleanup`))}}}async _waitForTaskUpdate(Q,X){let Y=this._options?.defaultTaskPollInterval??1000;try{let W=await this._taskStore?.getTask(Q);if(W?.pollInterval)Y=W.pollInterval}catch{}return new Promise((W,$)=>{if(X.aborted){$(new C(v.InvalidRequest,"Request cancelled"));return}let J=setTimeout(W,Y);X.addEventListener("abort",()=>{clearTimeout(J),$(new C(v.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(Q,X){let Y=this._taskStore;if(!Y)throw Error("No task store configured");return{createTask:async(W)=>{if(!Q)throw Error("No request provided");return await Y.createTask(W,Q.id,{method:Q.method,params:Q.params},X)},getTask:async(W)=>{let $=await Y.getTask(W,X);if(!$)throw new C(v.InvalidParams,"Failed to retrieve task: Task not found");return $},storeTaskResult:async(W,$,J)=>{await Y.storeTaskResult(W,$,J,X);let G=await Y.getTask(W,X);if(G){let H=H4.parse({method:"notifications/tasks/status",params:G});if(await this.notification(H),I1(G.status))this._cleanupTaskProgressHandler(W)}},getTaskResult:(W)=>{return Y.getTaskResult(W,X)},updateTaskStatus:async(W,$,J)=>{let G=await Y.getTask(W,X);if(!G)throw new C(v.InvalidParams,`Task "${W}" not found - it may have been cleaned up`);if(I1(G.status))throw new C(v.InvalidParams,`Cannot update task "${W}" from terminal status "${G.status}" to "${$}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await Y.updateTaskStatus(W,$,J,X);let H=await Y.getTask(W,X);if(H){let B=H4.parse({method:"notifications/tasks/status",params:H});if(await this.notification(B),I1(H.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return Y.listTasks(W,X)}}}}function j7(Q){return Q!==null&&typeof Q==="object"&&!Array.isArray(Q)}function b7(Q,X){let Y={...Q};for(let W in X){let $=W,J=X[$];if(J===void 0)continue;let G=Y[$];if(j7(G)&&j7(J))Y[$]={...G,...J};else Y[$]=J}return Y}var JB=SW(JW(),1),GB=SW($B(),1);function Jj(){let Q=new JB.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return GB.default(Q),Q}class FW{constructor(Q){this._ajv=Q??Jj()}getValidator(Q){let X="$id"in Q&&typeof Q.$id==="string"?this._ajv.getSchema(Q.$id)??this._ajv.compile(Q):this._ajv.compile(Q);return(Y)=>{if(X(Y))return{valid:!0,data:Y,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(X.errors)}}}}class VW{constructor(Q){this._server=Q}requestStream(Q,X,Y){return this._server.requestStream(Q,X,Y)}createMessageStream(Q,X){let Y=this._server.getClientCapabilities();if((Q.tools||Q.toolChoice)&&!Y?.sampling?.tools)throw Error("Client does not support sampling tools capability.");if(Q.messages.length>0){let W=Q.messages[Q.messages.length-1],$=Array.isArray(W.content)?W.content:[W.content],J=$.some((z)=>z.type==="tool_result"),G=Q.messages.length>1?Q.messages[Q.messages.length-2]:void 0,H=G?Array.isArray(G.content)?G.content:[G.content]:[],B=H.some((z)=>z.type==="tool_use");if(J){if($.some((z)=>z.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!B)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(B){let z=new Set(H.filter((D)=>D.type==="tool_use").map((D)=>D.id)),A=new Set($.filter((D)=>D.type==="tool_result").map((D)=>D.toolUseId));if(z.size!==A.size||![...z].every((D)=>A.has(D)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:Q},A4,X)}elicitInputStream(Q,X){let Y=this._server.getClientCapabilities(),W=Q.mode??"form";switch(W){case"url":{if(!Y?.elicitation?.url)throw Error("Client does not support url elicitation.");break}case"form":{if(!Y?.elicitation?.form)throw Error("Client does not support form elicitation.");break}}let $=W==="form"&&Q.mode===void 0?{...Q,mode:"form"}:Q;return this.requestStream({method:"elicitation/create",params:$},z6,X)}async getTask(Q,X){return this._server.getTask({taskId:Q},X)}async getTaskResult(Q,X,Y){return this._server.getTaskResult({taskId:Q},X,Y)}async listTasks(Q,X){return this._server.listTasks(Q?{cursor:Q}:void 0,X)}async cancelTask(Q,X){return this._server.cancelTask({taskId:Q},X)}}function HB(Q,X,Y){if(!Q)throw Error(`${Y} does not support task creation (required for ${X})`);switch(X){case"tools/call":if(!Q.tools?.call)throw Error(`${Y} does not support task creation for tools/call (required for ${X})`);break;default:break}}function BB(Q,X,Y){if(!Q)throw Error(`${Y} does not support task creation (required for ${X})`);switch(X){case"sampling/createMessage":if(!Q.sampling?.createMessage)throw Error(`${Y} does not support task creation for sampling/createMessage (required for ${X})`);break;case"elicitation/create":if(!Q.elicitation?.create)throw Error(`${Y} does not support task creation for elicitation/create (required for ${X})`);break;default:break}}class UW extends AY{constructor(Q,X){super(X);if(this._serverInfo=Q,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(z4.options.map((Y,W)=>[Y,W])),this.isMessageIgnored=(Y,W)=>{let $=this._loggingLevels.get(W);return $?this.LOG_LEVEL_SEVERITY.get(Y)<this.LOG_LEVEL_SEVERITY.get($):!1},this._capabilities=X?.capabilities??{},this._instructions=X?.instructions,this._jsonSchemaValidator=X?.jsonSchemaValidator??new FW,this.setRequestHandler(hX,(Y)=>this._oninitialize(Y)),this.setNotificationHandler(fX,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(nX,async(Y,W)=>{let $=W.sessionId||W.requestInfo?.headers["mcp-session-id"]||void 0,{level:J}=Y.params,G=z4.safeParse(J);if(G.success)this._loggingLevels.set($,G.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new VW(this)};return this._experimental}registerCapabilities(Q){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=b7(this._capabilities,Q)}setRequestHandler(Q,X){let W=P1(Q)?.method;if(!W)throw Error("Schema is missing a method literal");let $;if(u0(W)){let G=W;$=G._zod?.def?.value??G.value}else{let G=W;$=G._def?.value??G.value}if(typeof $!=="string")throw Error("Schema method literal must be a string");if($==="tools/call"){let G=async(H,B)=>{let z=S1(B6,H);if(!z.success){let K=z.error instanceof Error?z.error.message:String(z.error);throw new C(v.InvalidParams,`Invalid tools/call request: ${K}`)}let{params:A}=z.data,D=await Promise.resolve(X(H,B));if(A.task){let K=S1(G6,D);if(!K.success){let q=K.error instanceof Error?K.error.message:String(K.error);throw new C(v.InvalidParams,`Invalid task creation result: ${q}`)}return K.data}let L=S1(R9,D);if(!L.success){let K=L.error instanceof Error?L.error.message:String(L.error);throw new C(v.InvalidParams,`Invalid tools/call result: ${K}`)}return L.data};return super.setRequestHandler(Q,G)}return super.setRequestHandler(Q,X)}assertCapabilityForMethod(Q){switch(Q){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${Q})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${Q})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${Q})`);break;case"ping":break}}assertNotificationCapability(Q){switch(Q){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);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 ${Q})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${Q})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${Q})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${Q})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(Q){if(!this._capabilities)return;switch(Q){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${Q})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${Q})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${Q})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${Q})`);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 ${Q})`);break;case"ping":case"initialize":break}}assertTaskCapability(Q){BB(this._clientCapabilities?.tasks?.requests,Q,"Client")}assertTaskHandlerCapability(Q){if(!this._capabilities)return;HB(this._capabilities.tasks?.requests,Q,"Server")}async _oninitialize(Q){let X=Q.params.protocolVersion;return this._clientCapabilities=Q.params.capabilities,this._clientVersion=Q.params.clientInfo,{protocolVersion:AJ.includes(X)?X:kX,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"},D9)}async createMessage(Q,X){if(Q.tools||Q.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(Q.messages.length>0){let Y=Q.messages[Q.messages.length-1],W=Array.isArray(Y.content)?Y.content:[Y.content],$=W.some((B)=>B.type==="tool_result"),J=Q.messages.length>1?Q.messages[Q.messages.length-2]:void 0,G=J?Array.isArray(J.content)?J.content:[J.content]:[],H=G.some((B)=>B.type==="tool_use");if($){if(W.some((B)=>B.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!H)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(H){let B=new Set(G.filter((A)=>A.type==="tool_use").map((A)=>A.id)),z=new Set(W.filter((A)=>A.type==="tool_result").map((A)=>A.toolUseId));if(B.size!==z.size||![...B].every((A)=>z.has(A)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(Q.tools)return this.request({method:"sampling/createMessage",params:Q},dX,X);return this.request({method:"sampling/createMessage",params:Q},A4,X)}async elicitInput(Q,X){switch(Q.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let W=Q;return this.request({method:"elicitation/create",params:W},z6,X)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let W=Q.mode==="form"?Q:{...Q,mode:"form"},$=await this.request({method:"elicitation/create",params:W},z6,X);if($.action==="accept"&&$.content&&W.requestedSchema)try{let G=this._jsonSchemaValidator.getValidator(W.requestedSchema)($.content);if(!G.valid)throw new C(v.InvalidParams,`Elicitation response content does not match requested schema: ${G.errorMessage}`)}catch(J){if(J instanceof C)throw J;throw new C(v.InternalError,`Error validating elicitation response: ${J instanceof Error?J.message:String(J)}`)}return $}}}createElicitationCompletionNotifier(Q,X){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:Q}},X)}async listRoots(Q,X){return this.request({method:"roots/list",params:Q},oX,X)}async sendLoggingMessage(Q,X){if(this._capabilities.logging){if(!this.isMessageIgnored(Q.level,X))return this.notification({method:"notifications/message",params:Q})}}async sendResourceUpdated(Q){return this.notification({method:"notifications/resources/updated",params:Q})}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"})}}var AB=Symbol.for("mcp.completable");function OW(Q){return!!Q&&typeof Q==="object"&&AB in Q}function KB(Q){return Q[AB]?.complete}var zB;(function(Q){Q.Completable="McpCompletable"})(zB||(zB={}));var Gj=/^[A-Za-z0-9._-]{1,128}$/;function Hj(Q){let X=[];if(Q.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(Q.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${Q.length})`]};if(Q.includes(" "))X.push("Tool name contains spaces, which may cause parsing issues");if(Q.includes(","))X.push("Tool name contains commas, which may cause parsing issues");if(Q.startsWith("-")||Q.endsWith("-"))X.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");if(Q.startsWith(".")||Q.endsWith("."))X.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");if(!Gj.test(Q)){let Y=Q.split("").filter((W)=>!/[A-Za-z0-9._-]/.test(W)).filter((W,$,J)=>J.indexOf(W)===$);return X.push(`Tool name contains invalid characters: ${Y.map((W)=>`"${W}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:X}}return{isValid:!0,warnings:X}}function Bj(Q,X){if(X.length>0){console.warn(`Tool name validation warning for "${Q}":`);for(let Y of X)console.warn(` - ${Y}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function NW(Q){let X=Hj(Q);return Bj(Q,X.warnings),X.isValid}class wW{constructor(Q){this._mcpServer=Q}registerToolTask(Q,X,Y){let W={taskSupport:"required",...X.execution};if(W.taskSupport==="forbidden")throw Error(`Cannot register task-based tool '${Q}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(Q,X.title,X.description,X.inputSchema,X.outputSchema,X.annotations,W,X._meta,Y)}}class jW{constructor(Q,X){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new UW(Q,X)}get experimental(){if(!this._experimental)this._experimental={tasks:new wW(this)};return this._experimental}async connect(Q){return await this.server.connect(Q)}async close(){await this.server.close()}setToolRequestHandlers(){if(this._toolHandlersInitialized)return;this.server.assertCanSetRequestHandler(x1(I9)),this.server.assertCanSetRequestHandler(x1(B6)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(I9,()=>({tools:Object.entries(this._registeredTools).filter(([,Q])=>Q.enabled).map(([Q,X])=>{let Y={name:Q,title:X.title,description:X.description,inputSchema:(()=>{let W=S6(X.inputSchema);return W?HY(W,{strictUnions:!0,pipeStrategy:"input"}):zj})(),annotations:X.annotations,execution:X.execution,_meta:X._meta};if(X.outputSchema){let W=S6(X.outputSchema);if(W)Y.outputSchema=HY(W,{strictUnions:!0,pipeStrategy:"output"})}return Y})})),this.server.setRequestHandler(B6,async(Q,X)=>{try{let Y=this._registeredTools[Q.params.name];if(!Y)throw new C(v.InvalidParams,`Tool ${Q.params.name} not found`);if(!Y.enabled)throw new C(v.InvalidParams,`Tool ${Q.params.name} disabled`);let W=!!Q.params.task,$=Y.execution?.taskSupport,J="createTask"in Y.handler;if(($==="required"||$==="optional")&&!J)throw new C(v.InternalError,`Tool ${Q.params.name} has taskSupport '${$}' but was not registered with registerToolTask`);if($==="required"&&!W)throw new C(v.MethodNotFound,`Tool ${Q.params.name} requires task augmentation (taskSupport: 'required')`);if($==="optional"&&!W&&J)return await this.handleAutomaticTaskPolling(Y,Q,X);let G=await this.validateToolInput(Y,Q.params.arguments,Q.params.name),H=await this.executeToolHandler(Y,G,X);if(W)return H;return await this.validateToolOutput(Y,H,Q.params.name),H}catch(Y){if(Y instanceof C){if(Y.code===v.UrlElicitationRequired)throw Y}return this.createToolError(Y instanceof Error?Y.message:String(Y))}}),this._toolHandlersInitialized=!0}createToolError(Q){return{content:[{type:"text",text:Q}],isError:!0}}async validateToolInput(Q,X,Y){if(!Q.inputSchema)return;let $=S6(Q.inputSchema)??Q.inputSchema,J=await _9($,X);if(!J.success){let G="error"in J?J.error:"Unknown error",H=x9(G);throw new C(v.InvalidParams,`Input validation error: Invalid arguments for tool ${Y}: ${H}`)}return J.data}async validateToolOutput(Q,X,Y){if(!Q.outputSchema)return;if(!("content"in X))return;if(X.isError)return;if(!X.structuredContent)throw new C(v.InvalidParams,`Output validation error: Tool ${Y} has an output schema but no structured content was provided`);let W=S6(Q.outputSchema),$=await _9(W,X.structuredContent);if(!$.success){let J="error"in $?$.error:"Unknown error",G=x9(J);throw new C(v.InvalidParams,`Output validation error: Invalid structured content for tool ${Y}: ${G}`)}}async executeToolHandler(Q,X,Y){let W=Q.handler;if("createTask"in W){if(!Y.taskStore)throw Error("No task store provided.");let J={...Y,taskStore:Y.taskStore};if(Q.inputSchema)return await Promise.resolve(W.createTask(X,J));else return await Promise.resolve(W.createTask(J))}if(Q.inputSchema)return await Promise.resolve(W(X,Y));else return await Promise.resolve(W(Y))}async handleAutomaticTaskPolling(Q,X,Y){if(!Y.taskStore)throw Error("No task store provided for task-capable tool.");let W=await this.validateToolInput(Q,X.params.arguments,X.params.name),$=Q.handler,J={...Y,taskStore:Y.taskStore},G=W?await Promise.resolve($.createTask(W,J)):await Promise.resolve($.createTask(J)),H=G.task.taskId,B=G.task,z=B.pollInterval??5000;while(B.status!=="completed"&&B.status!=="failed"&&B.status!=="cancelled"){await new Promise((D)=>setTimeout(D,z));let A=await Y.taskStore.getTask(H);if(!A)throw new C(v.InternalError,`Task ${H} not found during polling`);B=A}return await Y.taskStore.getTaskResult(H)}setCompletionRequestHandler(){if(this._completionHandlerInitialized)return;this.server.assertCanSetRequestHandler(x1(C9)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(C9,async(Q)=>{switch(Q.params.ref.type){case"ref/prompt":return PJ(Q),this.handlePromptCompletion(Q,Q.params.ref);case"ref/resource":return IJ(Q),this.handleResourceCompletion(Q,Q.params.ref);default:throw new C(v.InvalidParams,`Invalid completion reference: ${Q.params.ref}`)}}),this._completionHandlerInitialized=!0}async handlePromptCompletion(Q,X){let Y=this._registeredPrompts[X.name];if(!Y)throw new C(v.InvalidParams,`Prompt ${X.name} not found`);if(!Y.enabled)throw new C(v.InvalidParams,`Prompt ${X.name} disabled`);if(!Y.argsSchema)return m4;let $=P1(Y.argsSchema)?.[Q.params.argument.name];if(!OW($))return m4;let J=KB($);if(!J)return m4;let G=await J(Q.params.argument.value,Q.params.context);return LB(G)}async handleResourceCompletion(Q,X){let Y=Object.values(this._registeredResourceTemplates).find((J)=>J.resourceTemplate.uriTemplate.toString()===X.uri);if(!Y){if(this._registeredResources[X.uri])return m4;throw new C(v.InvalidParams,`Resource template ${Q.params.ref.uri} not found`)}let W=Y.resourceTemplate.completeCallback(Q.params.argument.name);if(!W)return m4;let $=await W(Q.params.argument.value,Q.params.context);return LB($)}setResourceRequestHandlers(){if(this._resourceHandlersInitialized)return;this.server.assertCanSetRequestHandler(x1(j9)),this.server.assertCanSetRequestHandler(x1(b9)),this.server.assertCanSetRequestHandler(x1(E9)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(j9,async(Q,X)=>{let Y=Object.entries(this._registeredResources).filter(([$,J])=>J.enabled).map(([$,J])=>({uri:$,name:J.name,...J.metadata})),W=[];for(let $ of Object.values(this._registeredResourceTemplates)){if(!$.resourceTemplate.listCallback)continue;let J=await $.resourceTemplate.listCallback(X);for(let G of J.resources)W.push({...$.metadata,...G})}return{resources:[...Y,...W]}}),this.server.setRequestHandler(b9,async()=>{return{resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([X,Y])=>({name:X,uriTemplate:Y.resourceTemplate.uriTemplate.toString(),...Y.metadata}))}}),this.server.setRequestHandler(E9,async(Q,X)=>{let Y=new URL(Q.params.uri),W=this._registeredResources[Y.toString()];if(W){if(!W.enabled)throw new C(v.InvalidParams,`Resource ${Y} disabled`);return W.readCallback(Y,X)}for(let $ of Object.values(this._registeredResourceTemplates)){let J=$.resourceTemplate.uriTemplate.match(Y.toString());if(J)return $.readCallback(Y,J,X)}throw new C(v.InvalidParams,`Resource ${Y} not found`)}),this._resourceHandlersInitialized=!0}setPromptRequestHandlers(){if(this._promptHandlersInitialized)return;this.server.assertCanSetRequestHandler(x1(S9)),this.server.assertCanSetRequestHandler(x1(P9)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(S9,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,Q])=>Q.enabled).map(([Q,X])=>{return{name:Q,title:X.title,description:X.description,arguments:X.argsSchema?Aj(X.argsSchema):void 0}})})),this.server.setRequestHandler(P9,async(Q,X)=>{let Y=this._registeredPrompts[Q.params.name];if(!Y)throw new C(v.InvalidParams,`Prompt ${Q.params.name} not found`);if(!Y.enabled)throw new C(v.InvalidParams,`Prompt ${Q.params.name} disabled`);if(Y.argsSchema){let W=S6(Y.argsSchema),$=await _9(W,Q.params.arguments);if(!$.success){let H="error"in $?$.error:"Unknown error",B=x9(H);throw new C(v.InvalidParams,`Invalid arguments for prompt ${Q.params.name}: ${B}`)}let J=$.data,G=Y.callback;return await Promise.resolve(G(J,X))}else{let W=Y.callback;return await Promise.resolve(W(X))}}),this._promptHandlersInitialized=!0}resource(Q,X,...Y){let W;if(typeof Y[0]==="object")W=Y.shift();let $=Y[0];if(typeof X==="string"){if(this._registeredResources[X])throw Error(`Resource ${X} is already registered`);let J=this._createRegisteredResource(Q,void 0,X,W,$);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),J}else{if(this._registeredResourceTemplates[Q])throw Error(`Resource template ${Q} is already registered`);let J=this._createRegisteredResourceTemplate(Q,void 0,X,W,$);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),J}}registerResource(Q,X,Y,W){if(typeof X==="string"){if(this._registeredResources[X])throw Error(`Resource ${X} is already registered`);let $=this._createRegisteredResource(Q,Y.title,X,Y,W);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),$}else{if(this._registeredResourceTemplates[Q])throw Error(`Resource template ${Q} is already registered`);let $=this._createRegisteredResourceTemplate(Q,Y.title,X,Y,W);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),$}}_createRegisteredResource(Q,X,Y,W,$){let J={name:Q,title:X,metadata:W,readCallback:$,enabled:!0,disable:()=>J.update({enabled:!1}),enable:()=>J.update({enabled:!0}),remove:()=>J.update({uri:null}),update:(G)=>{if(typeof G.uri<"u"&&G.uri!==Y){if(delete this._registeredResources[Y],G.uri)this._registeredResources[G.uri]=J}if(typeof G.name<"u")J.name=G.name;if(typeof G.title<"u")J.title=G.title;if(typeof G.metadata<"u")J.metadata=G.metadata;if(typeof G.callback<"u")J.readCallback=G.callback;if(typeof G.enabled<"u")J.enabled=G.enabled;this.sendResourceListChanged()}};return this._registeredResources[Y]=J,J}_createRegisteredResourceTemplate(Q,X,Y,W,$){let J={resourceTemplate:Y,title:X,metadata:W,readCallback:$,enabled:!0,disable:()=>J.update({enabled:!1}),enable:()=>J.update({enabled:!0}),remove:()=>J.update({name:null}),update:(B)=>{if(typeof B.name<"u"&&B.name!==Q){if(delete this._registeredResourceTemplates[Q],B.name)this._registeredResourceTemplates[B.name]=J}if(typeof B.title<"u")J.title=B.title;if(typeof B.template<"u")J.resourceTemplate=B.template;if(typeof B.metadata<"u")J.metadata=B.metadata;if(typeof B.callback<"u")J.readCallback=B.callback;if(typeof B.enabled<"u")J.enabled=B.enabled;this.sendResourceListChanged()}};this._registeredResourceTemplates[Q]=J;let G=Y.uriTemplate.variableNames;if(Array.isArray(G)&&G.some((B)=>!!Y.completeCallback(B)))this.setCompletionRequestHandler();return J}_createRegisteredPrompt(Q,X,Y,W,$){let J={title:X,description:Y,argsSchema:W===void 0?void 0:d1(W),callback:$,enabled:!0,disable:()=>J.update({enabled:!1}),enable:()=>J.update({enabled:!0}),remove:()=>J.update({name:null}),update:(G)=>{if(typeof G.name<"u"&&G.name!==Q){if(delete this._registeredPrompts[Q],G.name)this._registeredPrompts[G.name]=J}if(typeof G.title<"u")J.title=G.title;if(typeof G.description<"u")J.description=G.description;if(typeof G.argsSchema<"u")J.argsSchema=d1(G.argsSchema);if(typeof G.callback<"u")J.callback=G.callback;if(typeof G.enabled<"u")J.enabled=G.enabled;this.sendPromptListChanged()}};if(this._registeredPrompts[Q]=J,W){if(Object.values(W).some((H)=>{let B=H instanceof g0?H._def?.innerType:H;return OW(B)}))this.setCompletionRequestHandler()}return J}_createRegisteredTool(Q,X,Y,W,$,J,G,H,B){NW(Q);let z={title:X,description:Y,inputSchema:DB(W),outputSchema:DB($),annotations:J,execution:G,_meta:H,handler:B,enabled:!0,disable:()=>z.update({enabled:!1}),enable:()=>z.update({enabled:!0}),remove:()=>z.update({name:null}),update:(A)=>{if(typeof A.name<"u"&&A.name!==Q){if(typeof A.name==="string")NW(A.name);if(delete this._registeredTools[Q],A.name)this._registeredTools[A.name]=z}if(typeof A.title<"u")z.title=A.title;if(typeof A.description<"u")z.description=A.description;if(typeof A.paramsSchema<"u")z.inputSchema=d1(A.paramsSchema);if(typeof A.outputSchema<"u")z.outputSchema=d1(A.outputSchema);if(typeof A.callback<"u")z.handler=A.callback;if(typeof A.annotations<"u")z.annotations=A.annotations;if(typeof A._meta<"u")z._meta=A._meta;if(typeof A.enabled<"u")z.enabled=A.enabled;this.sendToolListChanged()}};return this._registeredTools[Q]=z,this.setToolRequestHandlers(),this.sendToolListChanged(),z}tool(Q,...X){if(this._registeredTools[Q])throw Error(`Tool ${Q} is already registered`);let Y,W,$,J;if(typeof X[0]==="string")Y=X.shift();if(X.length>1){let H=X[0];if(MW(H)){if(W=X.shift(),X.length>1&&typeof X[0]==="object"&&X[0]!==null&&!MW(X[0]))J=X.shift()}else if(typeof H==="object"&&H!==null){if(Object.values(H).some((B)=>typeof B==="object"&&B!==null))throw Error(`Tool ${Q} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);J=X.shift()}}let G=X[0];return this._createRegisteredTool(Q,void 0,Y,W,$,J,{taskSupport:"forbidden"},void 0,G)}registerTool(Q,X,Y){if(this._registeredTools[Q])throw Error(`Tool ${Q} is already registered`);let{title:W,description:$,inputSchema:J,outputSchema:G,annotations:H,_meta:B}=X;return this._createRegisteredTool(Q,W,$,J,G,H,{taskSupport:"forbidden"},B,Y)}prompt(Q,...X){if(this._registeredPrompts[Q])throw Error(`Prompt ${Q} is already registered`);let Y;if(typeof X[0]==="string")Y=X.shift();let W;if(X.length>1)W=X.shift();let $=X[0],J=this._createRegisteredPrompt(Q,void 0,Y,W,$);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),J}registerPrompt(Q,X,Y){if(this._registeredPrompts[Q])throw Error(`Prompt ${Q} is already registered`);let{title:W,description:$,argsSchema:J}=X,G=this._createRegisteredPrompt(Q,W,$,J,Y);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),G}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(Q,X){return this.server.sendLoggingMessage(Q,X)}sendResourceListChanged(){if(this.isConnected())this.server.sendResourceListChanged()}sendToolListChanged(){if(this.isConnected())this.server.sendToolListChanged()}sendPromptListChanged(){if(this.isConnected())this.server.sendPromptListChanged()}}var zj={type:"object",properties:{}};function qB(Q){return Q!==null&&typeof Q==="object"&&"parse"in Q&&typeof Q.parse==="function"&&"safeParse"in Q&&typeof Q.safeParse==="function"}function FB(Q){return"_def"in Q||"_zod"in Q||qB(Q)}function MW(Q){if(typeof Q!=="object"||Q===null)return!1;if(FB(Q))return!1;if(Object.keys(Q).length===0)return!0;return Object.values(Q).some(qB)}function DB(Q){if(!Q)return;if(MW(Q))return d1(Q);if(!FB(Q))throw Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return Q}function Aj(Q){let X=P1(Q);if(!X)return[];return Object.entries(X).map(([Y,W])=>{let $=mJ(W),J=cJ(W);return{name:Y,description:$,required:!J}})}function x1(Q){let Y=P1(Q)?.method;if(!Y)throw Error("Schema is missing a method literal");let W=g9(Y);if(typeof W==="string")return W;throw Error("Schema method literal must be a string")}function LB(Q){return{completion:{values:Q.slice(0,100),total:Q.length,hasMore:Q.length>100}}}var m4={completion:{values:[],hasMore:!1}};import{AsyncLocalStorage as Kj}from"node:async_hooks";var VB=new Kj;var Dj="https://api.stophy.dev/v1";class c4 extends Error{status;code;constructor(Q,X,Y){super(Y);this.status=Q;this.code=X;this.name="StophyError"}}async function c0(Q,X){let Y=VB.getStore()??process.env.STOPHY_API_KEY;if(!Y)throw new c4(0,"MISSING_API_KEY","No Stophy API key provided. Set STOPHY_API_KEY (stdio) or include your key in the URL path (hosted). Get a key at https://stophy.dev/dashboard.");let W=await fetch(`${Dj}${Q}`,{method:X!==void 0?"POST":"GET",headers:{Authorization:`Bearer ${Y}`,...X!==void 0?{"Content-Type":"application/json"}:{}},...X!==void 0?{body:JSON.stringify(X)}:{}}),$=await W.json();if(!$.success)throw new c4(W.status,$.code??"API_ERROR",$.error);return $.data}var UB={channelUrl:s.string().describe("YouTube channel URL. Accepts youtube.com/@handle or youtube.com/channel/UCxxx"),tab:s.enum(["video","short","playlist","about"]).optional().describe("Which tab to fetch. Defaults to video"),sortBy:s.enum(["latest","popular","oldest"]).optional().describe("Sort order for the video tab"),continuationToken:s.string().optional().describe("Pagination token from a previous channel response")};async function OB(Q){let X=await c0("/channel",Q);return{content:[{type:"text",text:JSON.stringify(X,null,2)}]}}async function NB(){let Q=await c0("/credits");return{content:[{type:"text",text:JSON.stringify(Q,null,2)}]}}var wB={playlistUrl:s.string().describe("YouTube playlist URL (youtube.com/playlist?list=PLxxx)"),continuationToken:s.string().optional().describe("Pagination token from a previous playlist response")};async function MB(Q){let X=await c0("/playlist",Q);return{content:[{type:"text",text:JSON.stringify(X,null,2)}]}}var jB={q:s.string().describe("Search query"),type:s.enum(["video","channel","playlist","short"]).optional().describe("Filter by content type"),uploadDate:s.enum(["hour","today","week","month","year"]).optional().describe("Filter by upload date"),duration:s.enum(["short","medium","long"]).optional().describe("short = under 4 min, medium = 4–20 min, long = over 20 min"),sortBy:s.enum(["relevance","popularity","date","rating"]).optional().describe("Sort order. Defaults to relevance"),continuationToken:s.string().optional().describe("Pagination token from a previous search response")};async function bB(Q){let X=await c0("/search",Q);return{content:[{type:"text",text:JSON.stringify(X,null,2)}]}}var EB={q:s.string().describe("Partial query to get autocomplete suggestions for"),hl:s.string().optional().describe("Language code (e.g. en, fr). Defaults to en"),gl:s.string().optional().describe("Country code (e.g. US, GB). Defaults to US")};async function SB(Q){let X=new URLSearchParams({q:Q.q});if(Q.hl)X.set("hl",Q.hl);if(Q.gl)X.set("gl",Q.gl);let Y=await c0(`/suggest?${X.toString()}`);return{content:[{type:"text",text:JSON.stringify(Y,null,2)}]}}var PB={videoUrl:s.string().describe("YouTube video URL or ID (e.g. https://youtube.com/watch?v=VIDEO_ID)"),type:s.enum(["details","transcript","comments","livechat"]).describe("What to fetch: details = title/description/stats, transcript = timestamped captions, comments = threaded comments, livechat = live stream chat messages + status"),sortBy:s.enum(["latest","top"]).optional().describe("Sort order for comments. Defaults to top"),chatType:s.enum(["top","live"]).optional().describe("For livechat only: 'top' = Top chat (moderated, default), 'live' = Live chat (all messages). Applied on the first call; later polls keep the chosen mode."),continuationToken:s.string().optional().describe("Pagination token. For comments, pass a previous comments response token. For livechat, pass the continuationToken from a previous livechat response to poll for new messages.")};async function IB(Q){let X=await c0("/video",Q);return{content:[{type:"text",text:JSON.stringify(X,null,2)}]}}function f6(Q){return async(X)=>{try{return await Q(X)}catch(Y){return{content:[{type:"text",text:Y instanceof c4?`Stophy error (${Y.code}): ${Y.message}`:`Unexpected error: ${String(Y)}`}]}}}}var u6={readOnlyHint:!0,destructiveHint:!1};function RB(){let Q=new jW({name:"stophy",version:"1.0.0"});return Q.tool("stophy_search_videos","Search YouTube by keyword with optional filters. Returns items[] where each item has: type, id, videoUrl, title, author, description, duration, durationSec, viewCount, publishedAt, publishedAtText, thumbnails, isLive. Also returns continuationToken for the next page. Best for: discovering videos on a topic, finding recent uploads. Not recommended for: fetching a specific video you already have the URL for. Use stophy_get_video instead.",jB,u6,f6(bB)),Q.tool("stophy_get_video",'Fetch details, transcript, comments, or live chat for a YouTube video. type="details": returns video{id, title, author, description, viewCount, likeCount, durationSec, publishedAt, tags, isLive} and related[]. type="transcript": returns {videoId, language{code, name, isAutoGenerated}, segments[{text, start, duration}], text}. type="comments": returns {videoId, items[{id, text, author, likeCount, replyCount, repliesToken}], continuationToken}. Pass repliesToken as continuationToken with type="comments" to fetch replies. type="livechat": returns {videoId, status (live|upcoming|replay|chat_disabled|not_live), isLive, concurrentViewers, messages[{id, text, author, authorId, timestampUsec, isOwner, isModerator, isVerified, superChatAmount}], continuationToken, pollIntervalMs}. Set chatType="top" for moderated Top chat (default) or "live" for all messages. To follow a live stream, poll again passing the previous continuationToken for only new messages, waiting pollIntervalMs between polls; a null continuationToken means the stream ended. Best for: extracting content from a known video URL. Not recommended for: discovering videos. Use stophy_search_videos instead.',PB,u6,f6(IB)),Q.tool("stophy_get_channel","Browse a YouTube channel's content. Returns channel{id, name, handle, subscriberCount, videoCount, isVerified, thumbnails} on every tab. Video/short/playlist tabs also return items[{id, videoUrl, title, author, publishedAt, thumbnails}] and continuationToken. About tab returns the full profile including country, joinedDate, viewCount, and links[]. Best for: auditing a creator's catalog, reading channel videos, reading channel description. Not recommended for: fetching a single known video. Use stophy_get_video instead.",UB,u6,f6(OB)),Q.tool("stophy_get_playlist","Get all videos in a YouTube playlist. Returns playlist{id, title, author} and items[{id, videoUrl, title, author, publishedAt, thumbnails}] with continuationToken. Best for: processing curated collections, course playlists, or a channel's uploads playlist.",wB,u6,f6(MB)),Q.tool("stophy_get_suggestions","Get YouTube autocomplete suggestions for a partial query. Returns {q, hl, gl, suggestions: string[]}. Best for: query expansion, topic discovery, and building search UIs.",EB,u6,f6(SB)),Q.tool("stophy_get_credits","Check your remaining Stophy API credit balance. Returns {credits: number}. Does not consume a credit. Use before running large batch jobs to confirm you have enough credits.",{},u6,f6(NB)),Q}var Lj=RB(),qj=new tX;await Lj.connect(qj);
42
+ ]`;continue}if($+=W[B],W[B]==="\\")J=!0;else if(G&&W[B]==="]")G=!1;else if(!G&&W[B]==="[")G=!0}try{new RegExp($)}catch{return console.warn(`Could not convert regex pattern at ${X.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),Q.source}return $}function u9(Q,X){if(X.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if(X.target==="openApi3"&&Q.keyType?._def.typeName===M.ZodEnum)return{type:"object",required:Q.keyType._def.values,properties:Q.keyType._def.values.reduce((W,$)=>({...W,[$]:g(Q.valueType._def,{...X,currentPath:[...X.currentPath,"properties",$]})??B0(X)}),{}),additionalProperties:X.rejectedAdditionalProperties};let Y={type:"object",additionalProperties:g(Q.valueType._def,{...X,currentPath:[...X.currentPath,"additionalProperties"]})??X.allowedAdditionalProperties};if(X.target==="openApi3")return Y;if(Q.keyType?._def.typeName===M.ZodString&&Q.keyType._def.checks?.length){let{type:W,...$}=f9(Q.keyType._def,X);return{...Y,propertyNames:$}}else if(Q.keyType?._def.typeName===M.ZodEnum)return{...Y,propertyNames:{enum:Q.keyType._def.values}};else if(Q.keyType?._def.typeName===M.ZodBranded&&Q.keyType._def.type._def.typeName===M.ZodString&&Q.keyType._def.type._def.checks?.length){let{type:W,...$}=h9(Q.keyType._def,X);return{...Y,propertyNames:$}}return Y}function $7(Q,X){if(X.mapStrategy==="record")return u9(Q,X);let Y=g(Q.keyType._def,{...X,currentPath:[...X.currentPath,"items","items","0"]})||B0(X),W=g(Q.valueType._def,{...X,currentPath:[...X.currentPath,"items","items","1"]})||B0(X);return{type:"array",maxItems:125,items:{type:"array",items:[Y,W],minItems:2,maxItems:2}}}function J7(Q){let X=Q.values,W=Object.keys(Q.values).filter((J)=>{return typeof X[X[J]]!=="number"}).map((J)=>X[J]),$=Array.from(new Set(W.map((J)=>typeof J)));return{type:$.length===1?$[0]==="string"?"string":"number":["string","number"],enum:W}}function G7(Q){return Q.target==="openAi"?void 0:{not:B0({...Q,currentPath:[...Q.currentPath,"not"]})}}function H7(Q){return Q.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var O4={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function z7(Q,X){if(X.target==="openApi3")return B7(Q,X);let Y=Q.options instanceof Map?Array.from(Q.options.values()):Q.options;if(Y.every((W)=>(W._def.typeName in O4)&&(!W._def.checks||!W._def.checks.length))){let W=Y.reduce(($,J)=>{let G=O4[J._def.typeName];return G&&!$.includes(G)?[...$,G]:$},[]);return{type:W.length>1?W:W[0]}}else if(Y.every((W)=>W._def.typeName==="ZodLiteral"&&!W.description)){let W=Y.reduce(($,J)=>{let G=typeof J._def.value;switch(G){case"string":case"number":case"boolean":return[...$,G];case"bigint":return[...$,"integer"];case"object":if(J._def.value===null)return[...$,"null"];case"symbol":case"undefined":case"function":default:return $}},[]);if(W.length===Y.length){let $=W.filter((J,G,H)=>H.indexOf(J)===G);return{type:$.length>1?$:$[0],enum:Y.reduce((J,G)=>{return J.includes(G._def.value)?J:[...J,G._def.value]},[])}}}else if(Y.every((W)=>W._def.typeName==="ZodEnum"))return{type:"string",enum:Y.reduce((W,$)=>[...W,...$._def.values.filter((J)=>!W.includes(J))],[])};return B7(Q,X)}var B7=(Q,X)=>{let Y=(Q.options instanceof Map?Array.from(Q.options.values()):Q.options).map((W,$)=>g(W._def,{...X,currentPath:[...X.currentPath,"anyOf",`${$}`]})).filter((W)=>!!W&&(!X.strictUnions||typeof W==="object"&&Object.keys(W).length>0));return Y.length?{anyOf:Y}:void 0};function A7(Q,X){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(Q.innerType._def.typeName)&&(!Q.innerType._def.checks||!Q.innerType._def.checks.length)){if(X.target==="openApi3")return{type:O4[Q.innerType._def.typeName],nullable:!0};return{type:[O4[Q.innerType._def.typeName],"null"]}}if(X.target==="openApi3"){let W=g(Q.innerType._def,{...X,currentPath:[...X.currentPath]});if(W&&"$ref"in W)return{allOf:[W],nullable:!0};return W&&{...W,nullable:!0}}let Y=g(Q.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","0"]});return Y&&{anyOf:[Y,{type:"null"}]}}function K7(Q,X){let Y={type:"number"};if(!Q.checks)return Y;for(let W of Q.checks)switch(W.kind){case"int":Y.type="integer",YY(Y,"type",W.message,X);break;case"min":if(X.target==="jsonSchema7")if(W.inclusive)n(Y,"minimum",W.value,W.message,X);else n(Y,"exclusiveMinimum",W.value,W.message,X);else{if(!W.inclusive)Y.exclusiveMinimum=!0;n(Y,"minimum",W.value,W.message,X)}break;case"max":if(X.target==="jsonSchema7")if(W.inclusive)n(Y,"maximum",W.value,W.message,X);else n(Y,"exclusiveMaximum",W.value,W.message,X);else{if(!W.inclusive)Y.exclusiveMaximum=!0;n(Y,"maximum",W.value,W.message,X)}break;case"multipleOf":n(Y,"multipleOf",W.value,W.message,X);break}return Y}function D7(Q,X){let Y=X.target==="openAi",W={type:"object",properties:{}},$=[],J=Q.shape();for(let H in J){let B=J[H];if(B===void 0||B._def===void 0)continue;let z=kL(B);if(z&&Y){if(B._def.typeName==="ZodOptional")B=B._def.innerType;if(!B.isNullable())B=B.nullable();z=!1}let A=g(B._def,{...X,currentPath:[...X.currentPath,"properties",H],propertyPath:[...X.currentPath,"properties",H]});if(A===void 0)continue;if(W.properties[H]=A,!z)$.push(H)}if($.length)W.required=$;let G=vL(Q,X);if(G!==void 0)W.additionalProperties=G;return W}function vL(Q,X){if(Q.catchall._def.typeName!=="ZodNever")return g(Q.catchall._def,{...X,currentPath:[...X.currentPath,"additionalProperties"]});switch(Q.unknownKeys){case"passthrough":return X.allowedAdditionalProperties;case"strict":return X.rejectedAdditionalProperties;case"strip":return X.removeAdditionalStrategy==="strict"?X.allowedAdditionalProperties:X.rejectedAdditionalProperties}}function kL(Q){try{return Q.isOptional()}catch{return!0}}var L7=(Q,X)=>{if(X.currentPath.toString()===X.propertyPath?.toString())return g(Q.innerType._def,X);let Y=g(Q.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","1"]});return Y?{anyOf:[{not:B0(X)},Y]}:B0(X)};var q7=(Q,X)=>{if(X.pipeStrategy==="input")return g(Q.in._def,X);else if(X.pipeStrategy==="output")return g(Q.out._def,X);let Y=g(Q.in._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),W=g(Q.out._def,{...X,currentPath:[...X.currentPath,"allOf",Y?"1":"0"]});return{allOf:[Y,W].filter(($)=>$!==void 0)}};function F7(Q,X){return g(Q.type._def,X)}function V7(Q,X){let W={type:"array",uniqueItems:!0,items:g(Q.valueType._def,{...X,currentPath:[...X.currentPath,"items"]})};if(Q.minSize)n(W,"minItems",Q.minSize.value,Q.minSize.message,X);if(Q.maxSize)n(W,"maxItems",Q.maxSize.value,Q.maxSize.message,X);return W}function U7(Q,X){if(Q.rest)return{type:"array",minItems:Q.items.length,items:Q.items.map((Y,W)=>g(Y._def,{...X,currentPath:[...X.currentPath,"items",`${W}`]})).reduce((Y,W)=>W===void 0?Y:[...Y,W],[]),additionalItems:g(Q.rest._def,{...X,currentPath:[...X.currentPath,"additionalItems"]})};else return{type:"array",minItems:Q.items.length,maxItems:Q.items.length,items:Q.items.map((Y,W)=>g(Y._def,{...X,currentPath:[...X.currentPath,"items",`${W}`]})).reduce((Y,W)=>W===void 0?Y:[...Y,W],[])}}function O7(Q){return{not:B0(Q)}}function N7(Q){return B0(Q)}var w7=(Q,X)=>{return g(Q.innerType._def,X)};var M7=(Q,X,Y)=>{switch(X){case M.ZodString:return f9(Q,Y);case M.ZodNumber:return K7(Q,Y);case M.ZodObject:return D7(Q,Y);case M.ZodBigInt:return rJ(Q,Y);case M.ZodBoolean:return tJ();case M.ZodDate:return WY(Q,Y);case M.ZodUndefined:return O7(Y);case M.ZodNull:return H7(Y);case M.ZodArray:return oJ(Q,Y);case M.ZodUnion:case M.ZodDiscriminatedUnion:return z7(Q,Y);case M.ZodIntersection:return X7(Q,Y);case M.ZodTuple:return U7(Q,Y);case M.ZodRecord:return u9(Q,Y);case M.ZodLiteral:return Y7(Q,Y);case M.ZodEnum:return Q7(Q);case M.ZodNativeEnum:return J7(Q);case M.ZodNullable:return A7(Q,Y);case M.ZodOptional:return L7(Q,Y);case M.ZodMap:return $7(Q,Y);case M.ZodSet:return V7(Q,Y);case M.ZodLazy:return()=>Q.getter()._def;case M.ZodPromise:return F7(Q,Y);case M.ZodNaN:case M.ZodNever:return G7(Y);case M.ZodEffects:return eJ(Q,Y);case M.ZodAny:return B0(Y);case M.ZodUnknown:return N7(Y);case M.ZodDefault:return sJ(Q,Y);case M.ZodBranded:return h9(Q,Y);case M.ZodReadonly:return w7(Q,Y);case M.ZodCatch:return aJ(Q,Y);case M.ZodPipeline:return q7(Q,Y);case M.ZodFunction:case M.ZodVoid:case M.ZodSymbol:return;default:return((W)=>{return})(X)}};function g(Q,X,Y=!1){let W=X.seen.get(Q);if(X.override){let H=X.override?.(Q,X,W,Y);if(H!==iJ)return H}if(W&&!Y){let H=_L(W,X);if(H!==void 0)return H}let $={def:Q,path:X.currentPath,jsonSchema:void 0};X.seen.set(Q,$);let J=M7(Q,Q.typeName,X),G=typeof J==="function"?g(J(),X):J;if(G)xL(Q,X,G);if(X.postProcess){let H=X.postProcess(G,Q,X);return $.jsonSchema=G,H}return $.jsonSchema=G,G}var _L=(Q,X)=>{switch(X.$refStrategy){case"root":return{$ref:Q.path.join("/")};case"relative":return{$ref:y9(X.currentPath,Q.path)};case"none":case"seen":{if(Q.path.length<X.currentPath.length&&Q.path.every((Y,W)=>X.currentPath[W]===Y))return console.warn(`Recursive reference detected at ${X.currentPath.join("/")}! Defaulting to any`),B0(X);return X.$refStrategy==="seen"?B0(X):void 0}}},xL=(Q,X,Y)=>{if(Q.description){if(Y.description=Q.description,X.markdownDescription)Y.markdownDescription=Q.description}return Y};var GY=(Q,X)=>{let Y=dJ(X),W=typeof X==="object"&&X.definitions?Object.entries(X.definitions).reduce((B,[z,A])=>({...B,[z]:g(A._def,{...Y,currentPath:[...Y.basePath,Y.definitionPath,z]},!0)??B0(Y)}),{}):void 0,$=typeof X==="string"?X:X?.nameStrategy==="title"?void 0:X?.name,J=g(Q._def,$===void 0?Y:{...Y,currentPath:[...Y.basePath,Y.definitionPath,$]},!1)??B0(Y),G=typeof X==="object"&&X.name!==void 0&&X.nameStrategy==="title"?X.name:void 0;if(G!==void 0)J.title=G;if(Y.flags.hasReferencedOpenAiAnyType){if(!W)W={};if(!W[Y.openAiAnyTypeName])W[Y.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:Y.$refStrategy==="relative"?"1":[...Y.basePath,Y.definitionPath,Y.openAiAnyTypeName].join("/")}}}let H=$===void 0?W?{...J,[Y.definitionPath]:W}:J:{$ref:[...Y.$refStrategy==="relative"?[]:Y.basePath,Y.definitionPath,$].join("/"),[Y.definitionPath]:{...W,[$]:J}};if(Y.target==="jsonSchema7")H.$schema="http://json-schema.org/draft-07/schema#";else if(Y.target==="jsonSchema2019-09"||Y.target==="openAi")H.$schema="https://json-schema.org/draft/2019-09/schema#";if(Y.target==="openAi"&&(("anyOf"in H)||("oneOf"in H)||("allOf"in H)||("type"in H)&&Array.isArray(H.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return H};function gL(Q){if(!Q)return"draft-7";if(Q==="jsonSchema7"||Q==="draft-7")return"draft-7";if(Q==="jsonSchema2019-09"||Q==="draft-2020-12")return"draft-2020-12";return"draft-7"}function HY(Q,X){if(u0(Q))return EX(Q,{target:gL(X?.target),io:X?.pipeStrategy??"input"});return GY(Q,{strictUnions:X?.strictUnions??!0,pipeStrategy:X?.pipeStrategy??"input"})}function BY(Q){let Y=P1(Q)?.method;if(!Y)throw Error("Schema is missing a method literal");let W=g9(Y);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function zY(Q,X){let Y=S1(Q,X);if(!Y.success)throw Y.error;return Y.data}var yL=60000;class AY{constructor(Q){if(this._options=Q,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(L9,(X)=>{this._oncancel(X)}),this.setNotificationHandler(F9,(X)=>{this._onprogress(X)}),this.setRequestHandler(q9,(X)=>({})),this._taskStore=Q?.taskStore,this._taskMessageQueue=Q?.taskMessageQueue,this._taskStore)this.setRequestHandler(V9,async(X,Y)=>{let W=await this._taskStore.getTask(X.params.taskId,Y.sessionId);if(!W)throw new C(v.InvalidParams,"Failed to retrieve task: Task not found");return{...W}}),this.setRequestHandler(O9,async(X,Y)=>{let W=async()=>{let $=X.params.taskId;if(this._taskMessageQueue){let G;while(G=await this._taskMessageQueue.dequeue($,Y.sessionId)){if(G.type==="response"||G.type==="error"){let H=G.message,B=H.id,z=this._requestResolvers.get(B);if(z)if(this._requestResolvers.delete(B),G.type==="response")z(H);else{let A=H,D=new C(A.error.code,A.error.message,A.error.data);z(D)}else{let A=G.type==="response"?"Response":"Error";this._onerror(Error(`${A} handler missing for request ${B}`))}continue}await this._transport?.send(G.message,{relatedRequestId:Y.requestId})}}let J=await this._taskStore.getTask($,Y.sessionId);if(!J)throw new C(v.InvalidParams,`Task not found: ${$}`);if(!I1(J.status))return await this._waitForTaskUpdate($,Y.signal),await W();if(I1(J.status)){let G=await this._taskStore.getTaskResult($,Y.sessionId);return this._clearTaskQueue($),{...G,_meta:{...G._meta,[N1]:{taskId:$}}}}return await W()};return await W()}),this.setRequestHandler(N9,async(X,Y)=>{try{let{tasks:W,nextCursor:$}=await this._taskStore.listTasks(X.params?.cursor,Y.sessionId);return{tasks:W,nextCursor:$,_meta:{}}}catch(W){throw new C(v.InvalidParams,`Failed to list tasks: ${W instanceof Error?W.message:String(W)}`)}}),this.setRequestHandler(M9,async(X,Y)=>{try{let W=await this._taskStore.getTask(X.params.taskId,Y.sessionId);if(!W)throw new C(v.InvalidParams,`Task not found: ${X.params.taskId}`);if(I1(W.status))throw new C(v.InvalidParams,`Cannot cancel task in terminal status: ${W.status}`);await this._taskStore.updateTaskStatus(X.params.taskId,"cancelled","Client cancelled task execution.",Y.sessionId),this._clearTaskQueue(X.params.taskId);let $=await this._taskStore.getTask(X.params.taskId,Y.sessionId);if(!$)throw new C(v.InvalidParams,`Task not found after cancellation: ${X.params.taskId}`);return{_meta:{},...$}}catch(W){if(W instanceof C)throw W;throw new C(v.InvalidRequest,`Failed to cancel task: ${W instanceof Error?W.message:String(W)}`)}})}async _oncancel(Q){if(!Q.params.requestId)return;this._requestHandlerAbortControllers.get(Q.params.requestId)?.abort(Q.params.reason)}_setupTimeout(Q,X,Y,W,$=!1){this._timeoutInfo.set(Q,{timeoutId:setTimeout(W,X),startTime:Date.now(),timeout:X,maxTotalTimeout:Y,resetTimeoutOnProgress:$,onTimeout:W})}_resetTimeout(Q){let X=this._timeoutInfo.get(Q);if(!X)return!1;let Y=Date.now()-X.startTime;if(X.maxTotalTimeout&&Y>=X.maxTotalTimeout)throw this._timeoutInfo.delete(Q),C.fromError(v.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:X.maxTotalTimeout,totalElapsed:Y});return clearTimeout(X.timeoutId),X.timeoutId=setTimeout(X.onTimeout,X.timeout),!0}_cleanupTimeout(Q){let X=this._timeoutInfo.get(Q);if(X)clearTimeout(X.timeoutId),this._timeoutInfo.delete(Q)}async connect(Q){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=Q;let X=this.transport?.onclose;this._transport.onclose=()=>{X?.(),this._onclose()};let Y=this.transport?.onerror;this._transport.onerror=($)=>{Y?.($),this._onerror($)};let W=this._transport?.onmessage;this._transport.onmessage=($,J)=>{if(W?.($,J),Y4($)||UJ($))this._onresponse($);else if(xX($))this._onrequest($,J);else if(VJ($))this._onnotification($);else this._onerror(Error(`Unknown message type: ${JSON.stringify($)}`))},await this._transport.start()}_onclose(){let Q=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let Y of this._timeoutInfo.values())clearTimeout(Y.timeoutId);this._timeoutInfo.clear();for(let Y of this._requestHandlerAbortControllers.values())Y.abort();this._requestHandlerAbortControllers.clear();let X=C.fromError(v.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let Y of Q.values())Y(X)}_onerror(Q){this.onerror?.(Q)}_onnotification(Q){let X=this._notificationHandlers.get(Q.method)??this.fallbackNotificationHandler;if(X===void 0)return;Promise.resolve().then(()=>X(Q)).catch((Y)=>this._onerror(Error(`Uncaught error in notification handler: ${Y}`)))}_onrequest(Q,X){let Y=this._requestHandlers.get(Q.method)??this.fallbackRequestHandler,W=this._transport,$=Q.params?._meta?.[N1]?.taskId;if(Y===void 0){let z={jsonrpc:"2.0",id:Q.id,error:{code:v.MethodNotFound,message:"Method not found"}};if($&&this._taskMessageQueue)this._enqueueTaskMessage($,{type:"error",message:z,timestamp:Date.now()},W?.sessionId).catch((A)=>this._onerror(Error(`Failed to enqueue error response: ${A}`)));else W?.send(z).catch((A)=>this._onerror(Error(`Failed to send an error response: ${A}`)));return}let J=new AbortController;this._requestHandlerAbortControllers.set(Q.id,J);let G=LJ(Q.params)?Q.params.task:void 0,H=this._taskStore?this.requestTaskStore(Q,W?.sessionId):void 0,B={signal:J.signal,sessionId:W?.sessionId,_meta:Q.params?._meta,sendNotification:async(z)=>{if(J.signal.aborted)return;let A={relatedRequestId:Q.id};if($)A.relatedTask={taskId:$};await this.notification(z,A)},sendRequest:async(z,A,D)=>{if(J.signal.aborted)throw new C(v.ConnectionClosed,"Request was cancelled");let L={...D,relatedRequestId:Q.id};if($&&!L.relatedTask)L.relatedTask={taskId:$};let K=L.relatedTask?.taskId??$;if(K&&H)await H.updateTaskStatus(K,"input_required");return await this.request(z,A,L)},authInfo:X?.authInfo,requestId:Q.id,requestInfo:X?.requestInfo,taskId:$,taskStore:H,taskRequestedTtl:G?.ttl,closeSSEStream:X?.closeSSEStream,closeStandaloneSSEStream:X?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(G)this.assertTaskHandlerCapability(Q.method)}).then(()=>Y(Q,B)).then(async(z)=>{if(J.signal.aborted)return;let A={result:z,jsonrpc:"2.0",id:Q.id};if($&&this._taskMessageQueue)await this._enqueueTaskMessage($,{type:"response",message:A,timestamp:Date.now()},W?.sessionId);else await W?.send(A)},async(z)=>{if(J.signal.aborted)return;let A={jsonrpc:"2.0",id:Q.id,error:{code:Number.isSafeInteger(z.code)?z.code:v.InternalError,message:z.message??"Internal error",...z.data!==void 0&&{data:z.data}}};if($&&this._taskMessageQueue)await this._enqueueTaskMessage($,{type:"error",message:A,timestamp:Date.now()},W?.sessionId);else await W?.send(A)}).catch((z)=>this._onerror(Error(`Failed to send response: ${z}`))).finally(()=>{if(this._requestHandlerAbortControllers.get(Q.id)===J)this._requestHandlerAbortControllers.delete(Q.id)})}_onprogress(Q){let{progressToken:X,...Y}=Q.params,W=Number(X),$=this._progressHandlers.get(W);if(!$){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(Q)}`));return}let J=this._responseHandlers.get(W),G=this._timeoutInfo.get(W);if(G&&J&&G.resetTimeoutOnProgress)try{this._resetTimeout(W)}catch(H){this._responseHandlers.delete(W),this._progressHandlers.delete(W),this._cleanupTimeout(W),J(H);return}$(Y)}_onresponse(Q){let X=Number(Q.id),Y=this._requestResolvers.get(X);if(Y){if(this._requestResolvers.delete(X),Y4(Q))Y(Q);else{let J=new C(Q.error.code,Q.error.message,Q.error.data);Y(J)}return}let W=this._responseHandlers.get(X);if(W===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(Q)}`));return}this._responseHandlers.delete(X),this._cleanupTimeout(X);let $=!1;if(Y4(Q)&&Q.result&&typeof Q.result==="object"){let J=Q.result;if(J.task&&typeof J.task==="object"){let G=J.task;if(typeof G.taskId==="string")$=!0,this._taskProgressTokens.set(G.taskId,X)}}if(!$)this._progressHandlers.delete(X);if(Y4(Q))W(Q);else{let J=C.fromError(Q.error.code,Q.error.message,Q.error.data);W(J)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(Q,X,Y){let{task:W}=Y??{};if(!W){try{yield{type:"result",result:await this.request(Q,X,Y)}}catch(J){yield{type:"error",error:J instanceof C?J:new C(v.InternalError,String(J))}}return}let $;try{let J=await this.request(Q,G6,Y);if(J.task)$=J.task.taskId,yield{type:"taskCreated",task:J.task};else throw new C(v.InternalError,"Task creation did not return a task");while(!0){let G=await this.getTask({taskId:$},Y);if(yield{type:"taskStatus",task:G},I1(G.status)){if(G.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:$},X,Y)};else if(G.status==="failed")yield{type:"error",error:new C(v.InternalError,`Task ${$} failed`)};else if(G.status==="cancelled")yield{type:"error",error:new C(v.InternalError,`Task ${$} was cancelled`)};return}if(G.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:$},X,Y)};return}let H=G.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((B)=>setTimeout(B,H)),Y?.signal?.throwIfAborted()}}catch(J){yield{type:"error",error:J instanceof C?J:new C(v.InternalError,String(J))}}}request(Q,X,Y){let{relatedRequestId:W,resumptionToken:$,onresumptiontoken:J,task:G,relatedTask:H}=Y??{};return new Promise((B,z)=>{let A=(O)=>{z(O)};if(!this._transport){A(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(Q.method),G)this.assertTaskCapability(Q.method)}catch(O){A(O);return}Y?.signal?.throwIfAborted();let D=this._requestMessageId++,L={...Q,jsonrpc:"2.0",id:D};if(Y?.onprogress)this._progressHandlers.set(D,Y.onprogress),L.params={...Q.params,_meta:{...Q.params?._meta||{},progressToken:D}};if(G)L.params={...L.params,task:G};if(H)L.params={...L.params,_meta:{...L.params?._meta||{},[N1]:H}};let K=(O)=>{this._responseHandlers.delete(D),this._progressHandlers.delete(D),this._cleanupTimeout(D),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:D,reason:String(O)}},{relatedRequestId:W,resumptionToken:$,onresumptiontoken:J}).catch((E)=>this._onerror(Error(`Failed to send cancellation: ${E}`)));let b=O instanceof C?O:new C(v.RequestTimeout,String(O));z(b)};this._responseHandlers.set(D,(O)=>{if(Y?.signal?.aborted)return;if(O instanceof Error)return z(O);try{let b=S1(X,O.result);if(!b.success)z(b.error);else B(b.data)}catch(b){z(b)}}),Y?.signal?.addEventListener("abort",()=>{K(Y?.signal?.reason)});let q=Y?.timeout??yL,F=()=>K(C.fromError(v.RequestTimeout,"Request timed out",{timeout:q}));this._setupTimeout(D,q,Y?.maxTotalTimeout,F,Y?.resetTimeoutOnProgress??!1);let N=H?.taskId;if(N){let O=(b)=>{let E=this._responseHandlers.get(D);if(E)E(b);else this._onerror(Error(`Response handler missing for side-channeled request ${D}`))};this._requestResolvers.set(D,O),this._enqueueTaskMessage(N,{type:"request",message:L,timestamp:Date.now()}).catch((b)=>{this._cleanupTimeout(D),z(b)})}else this._transport.send(L,{relatedRequestId:W,resumptionToken:$,onresumptiontoken:J}).catch((O)=>{this._cleanupTimeout(D),z(O)})})}async getTask(Q,X){return this.request({method:"tasks/get",params:Q},U9,X)}async getTaskResult(Q,X,Y){return this.request({method:"tasks/result",params:Q},X,Y)}async listTasks(Q,X){return this.request({method:"tasks/list",params:Q},w9,X)}async cancelTask(Q,X){return this.request({method:"tasks/cancel",params:Q},wJ,X)}async notification(Q,X){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(Q.method);let Y=X?.relatedTask?.taskId;if(Y){let G={...Q,jsonrpc:"2.0",params:{...Q.params,_meta:{...Q.params?._meta||{},[N1]:X.relatedTask}}};await this._enqueueTaskMessage(Y,{type:"notification",message:G,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(Q.method)&&!Q.params&&!X?.relatedRequestId&&!X?.relatedTask){if(this._pendingDebouncedNotifications.has(Q.method))return;this._pendingDebouncedNotifications.add(Q.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(Q.method),!this._transport)return;let G={...Q,jsonrpc:"2.0"};if(X?.relatedTask)G={...G,params:{...G.params,_meta:{...G.params?._meta||{},[N1]:X.relatedTask}}};this._transport?.send(G,X).catch((H)=>this._onerror(H))});return}let J={...Q,jsonrpc:"2.0"};if(X?.relatedTask)J={...J,params:{...J.params,_meta:{...J.params?._meta||{},[N1]:X.relatedTask}}};await this._transport.send(J,X)}setRequestHandler(Q,X){let Y=BY(Q);this.assertRequestHandlerCapability(Y),this._requestHandlers.set(Y,(W,$)=>{let J=zY(Q,W);return Promise.resolve(X(J,$))})}removeRequestHandler(Q){this._requestHandlers.delete(Q)}assertCanSetRequestHandler(Q){if(this._requestHandlers.has(Q))throw Error(`A request handler for ${Q} already exists, which would be overridden`)}setNotificationHandler(Q,X){let Y=BY(Q);this._notificationHandlers.set(Y,(W)=>{let $=zY(Q,W);return Promise.resolve(X($))})}removeNotificationHandler(Q){this._notificationHandlers.delete(Q)}_cleanupTaskProgressHandler(Q){let X=this._taskProgressTokens.get(Q);if(X!==void 0)this._progressHandlers.delete(X),this._taskProgressTokens.delete(Q)}async _enqueueTaskMessage(Q,X,Y){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let W=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(Q,X,Y,W)}async _clearTaskQueue(Q,X){if(this._taskMessageQueue){let Y=await this._taskMessageQueue.dequeueAll(Q,X);for(let W of Y)if(W.type==="request"&&xX(W.message)){let $=W.message.id,J=this._requestResolvers.get($);if(J)J(new C(v.InternalError,"Task cancelled or completed")),this._requestResolvers.delete($);else this._onerror(Error(`Resolver missing for request ${$} during task ${Q} cleanup`))}}}async _waitForTaskUpdate(Q,X){let Y=this._options?.defaultTaskPollInterval??1000;try{let W=await this._taskStore?.getTask(Q);if(W?.pollInterval)Y=W.pollInterval}catch{}return new Promise((W,$)=>{if(X.aborted){$(new C(v.InvalidRequest,"Request cancelled"));return}let J=setTimeout(W,Y);X.addEventListener("abort",()=>{clearTimeout(J),$(new C(v.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(Q,X){let Y=this._taskStore;if(!Y)throw Error("No task store configured");return{createTask:async(W)=>{if(!Q)throw Error("No request provided");return await Y.createTask(W,Q.id,{method:Q.method,params:Q.params},X)},getTask:async(W)=>{let $=await Y.getTask(W,X);if(!$)throw new C(v.InvalidParams,"Failed to retrieve task: Task not found");return $},storeTaskResult:async(W,$,J)=>{await Y.storeTaskResult(W,$,J,X);let G=await Y.getTask(W,X);if(G){let H=H4.parse({method:"notifications/tasks/status",params:G});if(await this.notification(H),I1(G.status))this._cleanupTaskProgressHandler(W)}},getTaskResult:(W)=>{return Y.getTaskResult(W,X)},updateTaskStatus:async(W,$,J)=>{let G=await Y.getTask(W,X);if(!G)throw new C(v.InvalidParams,`Task "${W}" not found - it may have been cleaned up`);if(I1(G.status))throw new C(v.InvalidParams,`Cannot update task "${W}" from terminal status "${G.status}" to "${$}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await Y.updateTaskStatus(W,$,J,X);let H=await Y.getTask(W,X);if(H){let B=H4.parse({method:"notifications/tasks/status",params:H});if(await this.notification(B),I1(H.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return Y.listTasks(W,X)}}}}function j7(Q){return Q!==null&&typeof Q==="object"&&!Array.isArray(Q)}function b7(Q,X){let Y={...Q};for(let W in X){let $=W,J=X[$];if(J===void 0)continue;let G=Y[$];if(j7(G)&&j7(J))Y[$]={...G,...J};else Y[$]=J}return Y}var JB=SW(JW(),1),GB=SW($B(),1);function Jj(){let Q=new JB.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return GB.default(Q),Q}class FW{constructor(Q){this._ajv=Q??Jj()}getValidator(Q){let X="$id"in Q&&typeof Q.$id==="string"?this._ajv.getSchema(Q.$id)??this._ajv.compile(Q):this._ajv.compile(Q);return(Y)=>{if(X(Y))return{valid:!0,data:Y,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(X.errors)}}}}class VW{constructor(Q){this._server=Q}requestStream(Q,X,Y){return this._server.requestStream(Q,X,Y)}createMessageStream(Q,X){let Y=this._server.getClientCapabilities();if((Q.tools||Q.toolChoice)&&!Y?.sampling?.tools)throw Error("Client does not support sampling tools capability.");if(Q.messages.length>0){let W=Q.messages[Q.messages.length-1],$=Array.isArray(W.content)?W.content:[W.content],J=$.some((z)=>z.type==="tool_result"),G=Q.messages.length>1?Q.messages[Q.messages.length-2]:void 0,H=G?Array.isArray(G.content)?G.content:[G.content]:[],B=H.some((z)=>z.type==="tool_use");if(J){if($.some((z)=>z.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!B)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(B){let z=new Set(H.filter((D)=>D.type==="tool_use").map((D)=>D.id)),A=new Set($.filter((D)=>D.type==="tool_result").map((D)=>D.toolUseId));if(z.size!==A.size||![...z].every((D)=>A.has(D)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:Q},A4,X)}elicitInputStream(Q,X){let Y=this._server.getClientCapabilities(),W=Q.mode??"form";switch(W){case"url":{if(!Y?.elicitation?.url)throw Error("Client does not support url elicitation.");break}case"form":{if(!Y?.elicitation?.form)throw Error("Client does not support form elicitation.");break}}let $=W==="form"&&Q.mode===void 0?{...Q,mode:"form"}:Q;return this.requestStream({method:"elicitation/create",params:$},z6,X)}async getTask(Q,X){return this._server.getTask({taskId:Q},X)}async getTaskResult(Q,X,Y){return this._server.getTaskResult({taskId:Q},X,Y)}async listTasks(Q,X){return this._server.listTasks(Q?{cursor:Q}:void 0,X)}async cancelTask(Q,X){return this._server.cancelTask({taskId:Q},X)}}function HB(Q,X,Y){if(!Q)throw Error(`${Y} does not support task creation (required for ${X})`);switch(X){case"tools/call":if(!Q.tools?.call)throw Error(`${Y} does not support task creation for tools/call (required for ${X})`);break;default:break}}function BB(Q,X,Y){if(!Q)throw Error(`${Y} does not support task creation (required for ${X})`);switch(X){case"sampling/createMessage":if(!Q.sampling?.createMessage)throw Error(`${Y} does not support task creation for sampling/createMessage (required for ${X})`);break;case"elicitation/create":if(!Q.elicitation?.create)throw Error(`${Y} does not support task creation for elicitation/create (required for ${X})`);break;default:break}}class UW extends AY{constructor(Q,X){super(X);if(this._serverInfo=Q,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(z4.options.map((Y,W)=>[Y,W])),this.isMessageIgnored=(Y,W)=>{let $=this._loggingLevels.get(W);return $?this.LOG_LEVEL_SEVERITY.get(Y)<this.LOG_LEVEL_SEVERITY.get($):!1},this._capabilities=X?.capabilities??{},this._instructions=X?.instructions,this._jsonSchemaValidator=X?.jsonSchemaValidator??new FW,this.setRequestHandler(hX,(Y)=>this._oninitialize(Y)),this.setNotificationHandler(fX,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(nX,async(Y,W)=>{let $=W.sessionId||W.requestInfo?.headers["mcp-session-id"]||void 0,{level:J}=Y.params,G=z4.safeParse(J);if(G.success)this._loggingLevels.set($,G.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new VW(this)};return this._experimental}registerCapabilities(Q){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=b7(this._capabilities,Q)}setRequestHandler(Q,X){let W=P1(Q)?.method;if(!W)throw Error("Schema is missing a method literal");let $;if(u0(W)){let G=W;$=G._zod?.def?.value??G.value}else{let G=W;$=G._def?.value??G.value}if(typeof $!=="string")throw Error("Schema method literal must be a string");if($==="tools/call"){let G=async(H,B)=>{let z=S1(B6,H);if(!z.success){let K=z.error instanceof Error?z.error.message:String(z.error);throw new C(v.InvalidParams,`Invalid tools/call request: ${K}`)}let{params:A}=z.data,D=await Promise.resolve(X(H,B));if(A.task){let K=S1(G6,D);if(!K.success){let q=K.error instanceof Error?K.error.message:String(K.error);throw new C(v.InvalidParams,`Invalid task creation result: ${q}`)}return K.data}let L=S1(R9,D);if(!L.success){let K=L.error instanceof Error?L.error.message:String(L.error);throw new C(v.InvalidParams,`Invalid tools/call result: ${K}`)}return L.data};return super.setRequestHandler(Q,G)}return super.setRequestHandler(Q,X)}assertCapabilityForMethod(Q){switch(Q){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${Q})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${Q})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${Q})`);break;case"ping":break}}assertNotificationCapability(Q){switch(Q){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);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 ${Q})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${Q})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${Q})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${Q})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(Q){if(!this._capabilities)return;switch(Q){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${Q})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${Q})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${Q})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${Q})`);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 ${Q})`);break;case"ping":case"initialize":break}}assertTaskCapability(Q){BB(this._clientCapabilities?.tasks?.requests,Q,"Client")}assertTaskHandlerCapability(Q){if(!this._capabilities)return;HB(this._capabilities.tasks?.requests,Q,"Server")}async _oninitialize(Q){let X=Q.params.protocolVersion;return this._clientCapabilities=Q.params.capabilities,this._clientVersion=Q.params.clientInfo,{protocolVersion:AJ.includes(X)?X:kX,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"},D9)}async createMessage(Q,X){if(Q.tools||Q.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(Q.messages.length>0){let Y=Q.messages[Q.messages.length-1],W=Array.isArray(Y.content)?Y.content:[Y.content],$=W.some((B)=>B.type==="tool_result"),J=Q.messages.length>1?Q.messages[Q.messages.length-2]:void 0,G=J?Array.isArray(J.content)?J.content:[J.content]:[],H=G.some((B)=>B.type==="tool_use");if($){if(W.some((B)=>B.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!H)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(H){let B=new Set(G.filter((A)=>A.type==="tool_use").map((A)=>A.id)),z=new Set(W.filter((A)=>A.type==="tool_result").map((A)=>A.toolUseId));if(B.size!==z.size||![...B].every((A)=>z.has(A)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(Q.tools)return this.request({method:"sampling/createMessage",params:Q},dX,X);return this.request({method:"sampling/createMessage",params:Q},A4,X)}async elicitInput(Q,X){switch(Q.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let W=Q;return this.request({method:"elicitation/create",params:W},z6,X)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let W=Q.mode==="form"?Q:{...Q,mode:"form"},$=await this.request({method:"elicitation/create",params:W},z6,X);if($.action==="accept"&&$.content&&W.requestedSchema)try{let G=this._jsonSchemaValidator.getValidator(W.requestedSchema)($.content);if(!G.valid)throw new C(v.InvalidParams,`Elicitation response content does not match requested schema: ${G.errorMessage}`)}catch(J){if(J instanceof C)throw J;throw new C(v.InternalError,`Error validating elicitation response: ${J instanceof Error?J.message:String(J)}`)}return $}}}createElicitationCompletionNotifier(Q,X){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:Q}},X)}async listRoots(Q,X){return this.request({method:"roots/list",params:Q},oX,X)}async sendLoggingMessage(Q,X){if(this._capabilities.logging){if(!this.isMessageIgnored(Q.level,X))return this.notification({method:"notifications/message",params:Q})}}async sendResourceUpdated(Q){return this.notification({method:"notifications/resources/updated",params:Q})}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"})}}var AB=Symbol.for("mcp.completable");function OW(Q){return!!Q&&typeof Q==="object"&&AB in Q}function KB(Q){return Q[AB]?.complete}var zB;(function(Q){Q.Completable="McpCompletable"})(zB||(zB={}));var Gj=/^[A-Za-z0-9._-]{1,128}$/;function Hj(Q){let X=[];if(Q.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(Q.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${Q.length})`]};if(Q.includes(" "))X.push("Tool name contains spaces, which may cause parsing issues");if(Q.includes(","))X.push("Tool name contains commas, which may cause parsing issues");if(Q.startsWith("-")||Q.endsWith("-"))X.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");if(Q.startsWith(".")||Q.endsWith("."))X.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");if(!Gj.test(Q)){let Y=Q.split("").filter((W)=>!/[A-Za-z0-9._-]/.test(W)).filter((W,$,J)=>J.indexOf(W)===$);return X.push(`Tool name contains invalid characters: ${Y.map((W)=>`"${W}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:X}}return{isValid:!0,warnings:X}}function Bj(Q,X){if(X.length>0){console.warn(`Tool name validation warning for "${Q}":`);for(let Y of X)console.warn(` - ${Y}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function NW(Q){let X=Hj(Q);return Bj(Q,X.warnings),X.isValid}class wW{constructor(Q){this._mcpServer=Q}registerToolTask(Q,X,Y){let W={taskSupport:"required",...X.execution};if(W.taskSupport==="forbidden")throw Error(`Cannot register task-based tool '${Q}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(Q,X.title,X.description,X.inputSchema,X.outputSchema,X.annotations,W,X._meta,Y)}}class jW{constructor(Q,X){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new UW(Q,X)}get experimental(){if(!this._experimental)this._experimental={tasks:new wW(this)};return this._experimental}async connect(Q){return await this.server.connect(Q)}async close(){await this.server.close()}setToolRequestHandlers(){if(this._toolHandlersInitialized)return;this.server.assertCanSetRequestHandler(x1(I9)),this.server.assertCanSetRequestHandler(x1(B6)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(I9,()=>({tools:Object.entries(this._registeredTools).filter(([,Q])=>Q.enabled).map(([Q,X])=>{let Y={name:Q,title:X.title,description:X.description,inputSchema:(()=>{let W=S6(X.inputSchema);return W?HY(W,{strictUnions:!0,pipeStrategy:"input"}):zj})(),annotations:X.annotations,execution:X.execution,_meta:X._meta};if(X.outputSchema){let W=S6(X.outputSchema);if(W)Y.outputSchema=HY(W,{strictUnions:!0,pipeStrategy:"output"})}return Y})})),this.server.setRequestHandler(B6,async(Q,X)=>{try{let Y=this._registeredTools[Q.params.name];if(!Y)throw new C(v.InvalidParams,`Tool ${Q.params.name} not found`);if(!Y.enabled)throw new C(v.InvalidParams,`Tool ${Q.params.name} disabled`);let W=!!Q.params.task,$=Y.execution?.taskSupport,J="createTask"in Y.handler;if(($==="required"||$==="optional")&&!J)throw new C(v.InternalError,`Tool ${Q.params.name} has taskSupport '${$}' but was not registered with registerToolTask`);if($==="required"&&!W)throw new C(v.MethodNotFound,`Tool ${Q.params.name} requires task augmentation (taskSupport: 'required')`);if($==="optional"&&!W&&J)return await this.handleAutomaticTaskPolling(Y,Q,X);let G=await this.validateToolInput(Y,Q.params.arguments,Q.params.name),H=await this.executeToolHandler(Y,G,X);if(W)return H;return await this.validateToolOutput(Y,H,Q.params.name),H}catch(Y){if(Y instanceof C){if(Y.code===v.UrlElicitationRequired)throw Y}return this.createToolError(Y instanceof Error?Y.message:String(Y))}}),this._toolHandlersInitialized=!0}createToolError(Q){return{content:[{type:"text",text:Q}],isError:!0}}async validateToolInput(Q,X,Y){if(!Q.inputSchema)return;let $=S6(Q.inputSchema)??Q.inputSchema,J=await _9($,X);if(!J.success){let G="error"in J?J.error:"Unknown error",H=x9(G);throw new C(v.InvalidParams,`Input validation error: Invalid arguments for tool ${Y}: ${H}`)}return J.data}async validateToolOutput(Q,X,Y){if(!Q.outputSchema)return;if(!("content"in X))return;if(X.isError)return;if(!X.structuredContent)throw new C(v.InvalidParams,`Output validation error: Tool ${Y} has an output schema but no structured content was provided`);let W=S6(Q.outputSchema),$=await _9(W,X.structuredContent);if(!$.success){let J="error"in $?$.error:"Unknown error",G=x9(J);throw new C(v.InvalidParams,`Output validation error: Invalid structured content for tool ${Y}: ${G}`)}}async executeToolHandler(Q,X,Y){let W=Q.handler;if("createTask"in W){if(!Y.taskStore)throw Error("No task store provided.");let J={...Y,taskStore:Y.taskStore};if(Q.inputSchema)return await Promise.resolve(W.createTask(X,J));else return await Promise.resolve(W.createTask(J))}if(Q.inputSchema)return await Promise.resolve(W(X,Y));else return await Promise.resolve(W(Y))}async handleAutomaticTaskPolling(Q,X,Y){if(!Y.taskStore)throw Error("No task store provided for task-capable tool.");let W=await this.validateToolInput(Q,X.params.arguments,X.params.name),$=Q.handler,J={...Y,taskStore:Y.taskStore},G=W?await Promise.resolve($.createTask(W,J)):await Promise.resolve($.createTask(J)),H=G.task.taskId,B=G.task,z=B.pollInterval??5000;while(B.status!=="completed"&&B.status!=="failed"&&B.status!=="cancelled"){await new Promise((D)=>setTimeout(D,z));let A=await Y.taskStore.getTask(H);if(!A)throw new C(v.InternalError,`Task ${H} not found during polling`);B=A}return await Y.taskStore.getTaskResult(H)}setCompletionRequestHandler(){if(this._completionHandlerInitialized)return;this.server.assertCanSetRequestHandler(x1(C9)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(C9,async(Q)=>{switch(Q.params.ref.type){case"ref/prompt":return PJ(Q),this.handlePromptCompletion(Q,Q.params.ref);case"ref/resource":return IJ(Q),this.handleResourceCompletion(Q,Q.params.ref);default:throw new C(v.InvalidParams,`Invalid completion reference: ${Q.params.ref}`)}}),this._completionHandlerInitialized=!0}async handlePromptCompletion(Q,X){let Y=this._registeredPrompts[X.name];if(!Y)throw new C(v.InvalidParams,`Prompt ${X.name} not found`);if(!Y.enabled)throw new C(v.InvalidParams,`Prompt ${X.name} disabled`);if(!Y.argsSchema)return m4;let $=P1(Y.argsSchema)?.[Q.params.argument.name];if(!OW($))return m4;let J=KB($);if(!J)return m4;let G=await J(Q.params.argument.value,Q.params.context);return LB(G)}async handleResourceCompletion(Q,X){let Y=Object.values(this._registeredResourceTemplates).find((J)=>J.resourceTemplate.uriTemplate.toString()===X.uri);if(!Y){if(this._registeredResources[X.uri])return m4;throw new C(v.InvalidParams,`Resource template ${Q.params.ref.uri} not found`)}let W=Y.resourceTemplate.completeCallback(Q.params.argument.name);if(!W)return m4;let $=await W(Q.params.argument.value,Q.params.context);return LB($)}setResourceRequestHandlers(){if(this._resourceHandlersInitialized)return;this.server.assertCanSetRequestHandler(x1(j9)),this.server.assertCanSetRequestHandler(x1(b9)),this.server.assertCanSetRequestHandler(x1(E9)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(j9,async(Q,X)=>{let Y=Object.entries(this._registeredResources).filter(([$,J])=>J.enabled).map(([$,J])=>({uri:$,name:J.name,...J.metadata})),W=[];for(let $ of Object.values(this._registeredResourceTemplates)){if(!$.resourceTemplate.listCallback)continue;let J=await $.resourceTemplate.listCallback(X);for(let G of J.resources)W.push({...$.metadata,...G})}return{resources:[...Y,...W]}}),this.server.setRequestHandler(b9,async()=>{return{resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([X,Y])=>({name:X,uriTemplate:Y.resourceTemplate.uriTemplate.toString(),...Y.metadata}))}}),this.server.setRequestHandler(E9,async(Q,X)=>{let Y=new URL(Q.params.uri),W=this._registeredResources[Y.toString()];if(W){if(!W.enabled)throw new C(v.InvalidParams,`Resource ${Y} disabled`);return W.readCallback(Y,X)}for(let $ of Object.values(this._registeredResourceTemplates)){let J=$.resourceTemplate.uriTemplate.match(Y.toString());if(J)return $.readCallback(Y,J,X)}throw new C(v.InvalidParams,`Resource ${Y} not found`)}),this._resourceHandlersInitialized=!0}setPromptRequestHandlers(){if(this._promptHandlersInitialized)return;this.server.assertCanSetRequestHandler(x1(S9)),this.server.assertCanSetRequestHandler(x1(P9)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(S9,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,Q])=>Q.enabled).map(([Q,X])=>{return{name:Q,title:X.title,description:X.description,arguments:X.argsSchema?Aj(X.argsSchema):void 0}})})),this.server.setRequestHandler(P9,async(Q,X)=>{let Y=this._registeredPrompts[Q.params.name];if(!Y)throw new C(v.InvalidParams,`Prompt ${Q.params.name} not found`);if(!Y.enabled)throw new C(v.InvalidParams,`Prompt ${Q.params.name} disabled`);if(Y.argsSchema){let W=S6(Y.argsSchema),$=await _9(W,Q.params.arguments);if(!$.success){let H="error"in $?$.error:"Unknown error",B=x9(H);throw new C(v.InvalidParams,`Invalid arguments for prompt ${Q.params.name}: ${B}`)}let J=$.data,G=Y.callback;return await Promise.resolve(G(J,X))}else{let W=Y.callback;return await Promise.resolve(W(X))}}),this._promptHandlersInitialized=!0}resource(Q,X,...Y){let W;if(typeof Y[0]==="object")W=Y.shift();let $=Y[0];if(typeof X==="string"){if(this._registeredResources[X])throw Error(`Resource ${X} is already registered`);let J=this._createRegisteredResource(Q,void 0,X,W,$);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),J}else{if(this._registeredResourceTemplates[Q])throw Error(`Resource template ${Q} is already registered`);let J=this._createRegisteredResourceTemplate(Q,void 0,X,W,$);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),J}}registerResource(Q,X,Y,W){if(typeof X==="string"){if(this._registeredResources[X])throw Error(`Resource ${X} is already registered`);let $=this._createRegisteredResource(Q,Y.title,X,Y,W);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),$}else{if(this._registeredResourceTemplates[Q])throw Error(`Resource template ${Q} is already registered`);let $=this._createRegisteredResourceTemplate(Q,Y.title,X,Y,W);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),$}}_createRegisteredResource(Q,X,Y,W,$){let J={name:Q,title:X,metadata:W,readCallback:$,enabled:!0,disable:()=>J.update({enabled:!1}),enable:()=>J.update({enabled:!0}),remove:()=>J.update({uri:null}),update:(G)=>{if(typeof G.uri<"u"&&G.uri!==Y){if(delete this._registeredResources[Y],G.uri)this._registeredResources[G.uri]=J}if(typeof G.name<"u")J.name=G.name;if(typeof G.title<"u")J.title=G.title;if(typeof G.metadata<"u")J.metadata=G.metadata;if(typeof G.callback<"u")J.readCallback=G.callback;if(typeof G.enabled<"u")J.enabled=G.enabled;this.sendResourceListChanged()}};return this._registeredResources[Y]=J,J}_createRegisteredResourceTemplate(Q,X,Y,W,$){let J={resourceTemplate:Y,title:X,metadata:W,readCallback:$,enabled:!0,disable:()=>J.update({enabled:!1}),enable:()=>J.update({enabled:!0}),remove:()=>J.update({name:null}),update:(B)=>{if(typeof B.name<"u"&&B.name!==Q){if(delete this._registeredResourceTemplates[Q],B.name)this._registeredResourceTemplates[B.name]=J}if(typeof B.title<"u")J.title=B.title;if(typeof B.template<"u")J.resourceTemplate=B.template;if(typeof B.metadata<"u")J.metadata=B.metadata;if(typeof B.callback<"u")J.readCallback=B.callback;if(typeof B.enabled<"u")J.enabled=B.enabled;this.sendResourceListChanged()}};this._registeredResourceTemplates[Q]=J;let G=Y.uriTemplate.variableNames;if(Array.isArray(G)&&G.some((B)=>!!Y.completeCallback(B)))this.setCompletionRequestHandler();return J}_createRegisteredPrompt(Q,X,Y,W,$){let J={title:X,description:Y,argsSchema:W===void 0?void 0:d1(W),callback:$,enabled:!0,disable:()=>J.update({enabled:!1}),enable:()=>J.update({enabled:!0}),remove:()=>J.update({name:null}),update:(G)=>{if(typeof G.name<"u"&&G.name!==Q){if(delete this._registeredPrompts[Q],G.name)this._registeredPrompts[G.name]=J}if(typeof G.title<"u")J.title=G.title;if(typeof G.description<"u")J.description=G.description;if(typeof G.argsSchema<"u")J.argsSchema=d1(G.argsSchema);if(typeof G.callback<"u")J.callback=G.callback;if(typeof G.enabled<"u")J.enabled=G.enabled;this.sendPromptListChanged()}};if(this._registeredPrompts[Q]=J,W){if(Object.values(W).some((H)=>{let B=H instanceof g0?H._def?.innerType:H;return OW(B)}))this.setCompletionRequestHandler()}return J}_createRegisteredTool(Q,X,Y,W,$,J,G,H,B){NW(Q);let z={title:X,description:Y,inputSchema:DB(W),outputSchema:DB($),annotations:J,execution:G,_meta:H,handler:B,enabled:!0,disable:()=>z.update({enabled:!1}),enable:()=>z.update({enabled:!0}),remove:()=>z.update({name:null}),update:(A)=>{if(typeof A.name<"u"&&A.name!==Q){if(typeof A.name==="string")NW(A.name);if(delete this._registeredTools[Q],A.name)this._registeredTools[A.name]=z}if(typeof A.title<"u")z.title=A.title;if(typeof A.description<"u")z.description=A.description;if(typeof A.paramsSchema<"u")z.inputSchema=d1(A.paramsSchema);if(typeof A.outputSchema<"u")z.outputSchema=d1(A.outputSchema);if(typeof A.callback<"u")z.handler=A.callback;if(typeof A.annotations<"u")z.annotations=A.annotations;if(typeof A._meta<"u")z._meta=A._meta;if(typeof A.enabled<"u")z.enabled=A.enabled;this.sendToolListChanged()}};return this._registeredTools[Q]=z,this.setToolRequestHandlers(),this.sendToolListChanged(),z}tool(Q,...X){if(this._registeredTools[Q])throw Error(`Tool ${Q} is already registered`);let Y,W,$,J;if(typeof X[0]==="string")Y=X.shift();if(X.length>1){let H=X[0];if(MW(H)){if(W=X.shift(),X.length>1&&typeof X[0]==="object"&&X[0]!==null&&!MW(X[0]))J=X.shift()}else if(typeof H==="object"&&H!==null){if(Object.values(H).some((B)=>typeof B==="object"&&B!==null))throw Error(`Tool ${Q} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);J=X.shift()}}let G=X[0];return this._createRegisteredTool(Q,void 0,Y,W,$,J,{taskSupport:"forbidden"},void 0,G)}registerTool(Q,X,Y){if(this._registeredTools[Q])throw Error(`Tool ${Q} is already registered`);let{title:W,description:$,inputSchema:J,outputSchema:G,annotations:H,_meta:B}=X;return this._createRegisteredTool(Q,W,$,J,G,H,{taskSupport:"forbidden"},B,Y)}prompt(Q,...X){if(this._registeredPrompts[Q])throw Error(`Prompt ${Q} is already registered`);let Y;if(typeof X[0]==="string")Y=X.shift();let W;if(X.length>1)W=X.shift();let $=X[0],J=this._createRegisteredPrompt(Q,void 0,Y,W,$);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),J}registerPrompt(Q,X,Y){if(this._registeredPrompts[Q])throw Error(`Prompt ${Q} is already registered`);let{title:W,description:$,argsSchema:J}=X,G=this._createRegisteredPrompt(Q,W,$,J,Y);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),G}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(Q,X){return this.server.sendLoggingMessage(Q,X)}sendResourceListChanged(){if(this.isConnected())this.server.sendResourceListChanged()}sendToolListChanged(){if(this.isConnected())this.server.sendToolListChanged()}sendPromptListChanged(){if(this.isConnected())this.server.sendPromptListChanged()}}var zj={type:"object",properties:{}};function qB(Q){return Q!==null&&typeof Q==="object"&&"parse"in Q&&typeof Q.parse==="function"&&"safeParse"in Q&&typeof Q.safeParse==="function"}function FB(Q){return"_def"in Q||"_zod"in Q||qB(Q)}function MW(Q){if(typeof Q!=="object"||Q===null)return!1;if(FB(Q))return!1;if(Object.keys(Q).length===0)return!0;return Object.values(Q).some(qB)}function DB(Q){if(!Q)return;if(MW(Q))return d1(Q);if(!FB(Q))throw Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return Q}function Aj(Q){let X=P1(Q);if(!X)return[];return Object.entries(X).map(([Y,W])=>{let $=mJ(W),J=cJ(W);return{name:Y,description:$,required:!J}})}function x1(Q){let Y=P1(Q)?.method;if(!Y)throw Error("Schema is missing a method literal");let W=g9(Y);if(typeof W==="string")return W;throw Error("Schema method literal must be a string")}function LB(Q){return{completion:{values:Q.slice(0,100),total:Q.length,hasMore:Q.length>100}}}var m4={completion:{values:[],hasMore:!1}};import{AsyncLocalStorage as Kj}from"node:async_hooks";var VB=new Kj;var Dj="https://api.stophy.dev/v1";class c4 extends Error{status;code;constructor(Q,X,Y){super(Y);this.status=Q;this.code=X;this.name="StophyError"}}async function c0(Q,X){let Y=VB.getStore()??process.env.STOPHY_API_KEY;if(!Y)throw new c4(0,"MISSING_API_KEY","No Stophy API key provided. Set STOPHY_API_KEY (stdio) or include your key in the URL path (hosted). Get a key at https://stophy.dev/dashboard.");let W=await fetch(`${Dj}${Q}`,{method:X!==void 0?"POST":"GET",headers:{Authorization:`Bearer ${Y}`,...X!==void 0?{"Content-Type":"application/json"}:{}},...X!==void 0?{body:JSON.stringify(X)}:{}}),$=await W.json();if(!$.success)throw new c4(W.status,$.code??"API_ERROR",$.error);return $.data}var UB={channelUrl:s.string().describe("YouTube channel URL. Accepts youtube.com/@handle or youtube.com/channel/UCxxx"),tab:s.enum(["video","short","playlist","about"]).optional().describe("Which tab to fetch. Defaults to video"),sortBy:s.enum(["latest","popular","oldest"]).optional().describe("Sort order for the video tab"),continuationToken:s.string().optional().describe("Pagination token from a previous channel response")};async function OB(Q){let X=await c0("/channel",Q);return{content:[{type:"text",text:JSON.stringify(X,null,2)}]}}async function NB(){let Q=await c0("/credits");return{content:[{type:"text",text:JSON.stringify(Q,null,2)}]}}var wB={playlistUrl:s.string().describe("YouTube playlist URL (youtube.com/playlist?list=PLxxx)"),continuationToken:s.string().optional().describe("Pagination token from a previous playlist response")};async function MB(Q){let X=await c0("/playlist",Q);return{content:[{type:"text",text:JSON.stringify(X,null,2)}]}}var jB={q:s.string().describe("Search query"),type:s.enum(["video","channel","playlist","short"]).optional().describe("Filter by content type"),uploadDate:s.enum(["hour","today","week","month","year"]).optional().describe("Filter by upload date"),duration:s.enum(["short","medium","long"]).optional().describe("short = under 4 min, medium = 4–20 min, long = over 20 min"),sortBy:s.enum(["relevance","popularity","date","rating"]).optional().describe("Sort order. Defaults to relevance"),continuationToken:s.string().optional().describe("Pagination token from a previous search response")};async function bB(Q){let X=await c0("/search",Q);return{content:[{type:"text",text:JSON.stringify(X,null,2)}]}}var EB={q:s.string().describe("Partial query to get autocomplete suggestions for"),hl:s.string().optional().describe("Language code (e.g. en, fr). Defaults to en"),gl:s.string().optional().describe("Country code (e.g. US, GB). Defaults to US")};async function SB(Q){let X=new URLSearchParams({q:Q.q});if(Q.hl)X.set("hl",Q.hl);if(Q.gl)X.set("gl",Q.gl);let Y=await c0(`/suggest?${X.toString()}`);return{content:[{type:"text",text:JSON.stringify(Y,null,2)}]}}var PB={videoUrl:s.string().describe("YouTube video URL or ID (e.g. https://youtube.com/watch?v=VIDEO_ID)"),type:s.enum(["details","transcript","comments","livechat"]).describe("What to fetch: details = title/description/stats, transcript = timestamped captions, comments = threaded comments, livechat = live stream chat messages + status"),sortBy:s.enum(["latest","top"]).optional().describe("Sort order for comments. Defaults to top"),chatType:s.enum(["top","live"]).optional().describe("For livechat only: 'top' = Top chat (moderated, default), 'live' = Live chat (all messages). Applied on the first call; later polls keep the chosen mode."),continuationToken:s.string().optional().describe("Pagination token. For comments, pass a previous comments response token. For livechat, pass the continuationToken from a previous livechat response to poll for new messages.")};async function IB(Q){let X=await c0("/video",Q);return{content:[{type:"text",text:JSON.stringify(X,null,2)}]}}function f6(Q){return async(X)=>{try{return await Q(X)}catch(Y){return{content:[{type:"text",text:Y instanceof c4?`Stophy error (${Y.code}): ${Y.message}`:`Unexpected error: ${String(Y)}`}]}}}}var u6={readOnlyHint:!0,destructiveHint:!1};function RB(){let Q=new jW({name:"stophy",version:"1.0.0"});return Q.tool("stophy_search_videos","Search YouTube for videos, channels, playlists, or Shorts. Filter by upload date, duration, and sort order. Returns items with title, author, view count, duration, and publish date. Paginate with continuationToken. When you already have a video URL, use stophy_get_video instead.",jB,u6,f6(bB)),Q.tool("stophy_get_video",`Get YouTube data for a specific video. type="details": title, description, stats, tags, and related videos. type="transcript": timestamped captions with language info and speaker segments. type="comments": threaded comments with author, likes, and reply count — pass a comment's repliesToken as continuationToken to fetch its replies. type="livechat": real-time chat from a live stream. Poll with continuationToken every pollIntervalMs until it returns null (stream ended). Set chatType="top" for moderated chat or "live" for all messages. When discovering videos, use stophy_search_videos instead.`,PB,u6,f6(IB)),Q.tool("stophy_get_channel",'Browse a YouTube channel. Every tab returns channel info (name, handle, subscriber count, video count). tab="video", "short", or "playlist" lists content with pagination. tab="about" returns the full profile: country, join date, total views, and links. When you have a specific video URL, use stophy_get_video instead.',UB,u6,f6(OB)),Q.tool("stophy_get_playlist","Get all videos in a YouTube playlist. Returns the playlist title, author, and every video. Paginate with continuationToken.",wB,u6,f6(MB)),Q.tool("stophy_get_suggestions","YouTube autocomplete suggestions for a partial query. Returns an array of completions. Useful for topic discovery and query expansion.",EB,u6,f6(SB)),Q.tool("stophy_get_credits","Check your Stophy credit balance. Free — does not cost a credit. Returns remaining credits.",{},u6,f6(NB)),Q}var Lj=RB(),qj=new tX;await Lj.connect(qj);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stophy/mcp",
3
- "version": "1.0.4",
3
+ "version": "1.0.5",
4
4
  "description": "YouTube data for AI agents. MCP server that gives AI agents YouTube transcripts, comments, search, and channels as structured JSON.",
5
5
  "type": "module",
6
6
  "bin": {