@farthershore/cli 0.7.3 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +76 -50
- package/dist/index.js +143 -143
- package/dist/mcp.js +1 -1
- package/package.json +1 -1
package/dist/mcp.js
CHANGED
|
@@ -215,4 +215,4 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
215
215
|
`:`[${i[c]}\r
|
|
216
216
|
]`;continue}n+=i[c],i[c]==="\\"?o=!0:a&&i[c]==="]"?a=!1:!a&&i[c]==="["&&(a=!0)}try{new RegExp(n)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return n}function td(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===E.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((i,n)=>({...i,[n]:V(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",n]})??we(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:V(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===E.ZodString&&t.keyType._def.checks?.length){let{type:i,...n}=ed(t.keyType._def,e);return{...r,propertyNames:n}}else{if(t.keyType?._def.typeName===E.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===E.ZodBranded&&t.keyType._def.type._def.typeName===E.ZodString&&t.keyType._def.type._def.checks?.length){let{type:i,...n}=Ql(t.keyType._def,e);return{...r,propertyNames:n}}}return r}function pw(t,e){if(e.mapStrategy==="record")return td(t,e);let r=V(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||we(e),i=V(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||we(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,i],minItems:2,maxItems:2}}}function mw(t){let e=t.values,i=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),n=Array.from(new Set(i.map(o=>typeof o)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:i}}function hw(t){return t.target==="openAi"?void 0:{not:we({...t,currentPath:[...t.currentPath,"not"]})}}function gw(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Na={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function yw(t,e){if(e.target==="openApi3")return vw(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(i=>i._def.typeName in Na&&(!i._def.checks||!i._def.checks.length))){let i=r.reduce((n,o)=>{let a=Na[o._def.typeName];return a&&!n.includes(a)?[...n,a]:n},[]);return{type:i.length>1?i:i[0]}}else if(r.every(i=>i._def.typeName==="ZodLiteral"&&!i.description)){let i=r.reduce((n,o)=>{let a=typeof o._def.value;switch(a){case"string":case"number":case"boolean":return[...n,a];case"bigint":return[...n,"integer"];case"object":if(o._def.value===null)return[...n,"null"];default:return n}},[]);if(i.length===r.length){let n=i.filter((o,a,s)=>s.indexOf(o)===a);return{type:n.length>1?n:n[0],enum:r.reduce((o,a)=>o.includes(a._def.value)?o:[...o,a._def.value],[])}}}else if(r.every(i=>i._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((i,n)=>[...i,...n._def.values.filter(o=>!i.includes(o))],[])};return vw(t,e)}var vw=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((i,n)=>V(i._def,{...e,currentPath:[...e.currentPath,"anyOf",`${n}`]})).filter(i=>!!i&&(!e.strictUnions||typeof i=="object"&&Object.keys(i).length>0));return r.length?{anyOf:r}:void 0};function _w(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:Na[t.innerType._def.typeName],nullable:!0}:{type:[Na[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let i=V(t.innerType._def,{...e,currentPath:[...e.currentPath]});return i&&"$ref"in i?{allOf:[i],nullable:!0}:i&&{...i,nullable:!0}}let r=V(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function bw(t,e){let r={type:"number"};if(!t.checks)return r;for(let i of t.checks)switch(i.kind){case"int":r.type="integer",Ag(r,"type",i.message,e);break;case"min":e.target==="jsonSchema7"?i.inclusive?ie(r,"minimum",i.value,i.message,e):ie(r,"exclusiveMinimum",i.value,i.message,e):(i.inclusive||(r.exclusiveMinimum=!0),ie(r,"minimum",i.value,i.message,e));break;case"max":e.target==="jsonSchema7"?i.inclusive?ie(r,"maximum",i.value,i.message,e):ie(r,"exclusiveMaximum",i.value,i.message,e):(i.inclusive||(r.exclusiveMaximum=!0),ie(r,"maximum",i.value,i.message,e));break;case"multipleOf":ie(r,"multipleOf",i.value,i.message,e);break}return r}function $w(t,e){let r=e.target==="openAi",i={type:"object",properties:{}},n=[],o=t.shape();for(let s in o){let c=o[s];if(c===void 0||c._def===void 0)continue;let u=T1(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=V(c._def,{...e,currentPath:[...e.currentPath,"properties",s],propertyPath:[...e.currentPath,"properties",s]});l!==void 0&&(i.properties[s]=l,u||n.push(s))}n.length&&(i.required=n);let a=P1(t,e);return a!==void 0&&(i.additionalProperties=a),i}function P1(t,e){if(t.catchall._def.typeName!=="ZodNever")return V(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function T1(t){try{return t.isOptional()}catch{return!0}}var kw=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return V(t.innerType._def,e);let r=V(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:we(e)},r]}:we(e)};var xw=(t,e)=>{if(e.pipeStrategy==="input")return V(t.in._def,e);if(e.pipeStrategy==="output")return V(t.out._def,e);let r=V(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),i=V(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,i].filter(n=>n!==void 0)}};function ww(t,e){return V(t.type._def,e)}function Sw(t,e){let i={type:"array",uniqueItems:!0,items:V(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ie(i,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ie(i,"maxItems",t.maxSize.value,t.maxSize.message,e),i}function zw(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,i)=>V(r._def,{...e,currentPath:[...e.currentPath,"items",`${i}`]})).reduce((r,i)=>i===void 0?r:[...r,i],[]),additionalItems:V(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,i)=>V(r._def,{...e,currentPath:[...e.currentPath,"items",`${i}`]})).reduce((r,i)=>i===void 0?r:[...r,i],[])}}function Iw(t){return{not:we(t)}}function Pw(t){return we(t)}var Tw=(t,e)=>V(t.innerType._def,e);var Ew=(t,e,r)=>{switch(e){case E.ZodString:return ed(t,r);case E.ZodNumber:return bw(t,r);case E.ZodObject:return $w(t,r);case E.ZodBigInt:return iw(t,r);case E.ZodBoolean:return ow();case E.ZodDate:return Rg(t,r);case E.ZodUndefined:return Iw(r);case E.ZodNull:return gw(r);case E.ZodArray:return nw(t,r);case E.ZodUnion:case E.ZodDiscriminatedUnion:return yw(t,r);case E.ZodIntersection:return lw(t,r);case E.ZodTuple:return zw(t,r);case E.ZodRecord:return td(t,r);case E.ZodLiteral:return dw(t,r);case E.ZodEnum:return uw(t);case E.ZodNativeEnum:return mw(t);case E.ZodNullable:return _w(t,r);case E.ZodOptional:return kw(t,r);case E.ZodMap:return pw(t,r);case E.ZodSet:return Sw(t,r);case E.ZodLazy:return()=>t.getter()._def;case E.ZodPromise:return ww(t,r);case E.ZodNaN:case E.ZodNever:return hw(r);case E.ZodEffects:return cw(t,r);case E.ZodAny:return we(r);case E.ZodUnknown:return Pw(r);case E.ZodDefault:return sw(t,r);case E.ZodBranded:return Ql(t,r);case E.ZodReadonly:return Tw(t,r);case E.ZodCatch:return aw(t,r);case E.ZodPipeline:return xw(t,r);case E.ZodFunction:case E.ZodVoid:case E.ZodSymbol:return;default:return(i=>{})(e)}};function V(t,e,r=!1){let i=e.seen.get(t);if(e.override){let s=e.override?.(t,e,i,r);if(s!==ew)return s}if(i&&!r){let s=E1(i,e);if(s!==void 0)return s}let n={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,n);let o=Ew(t,t.typeName,e),a=typeof o=="function"?V(o(),e):o;if(a&&O1(t,e,a),e.postProcess){let s=e.postProcess(a,t,e);return n.jsonSchema=a,s}return n.jsonSchema=a,a}var E1=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Xl(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,i)=>e.currentPath[i]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),we(e)):e.$refStrategy==="seen"?we(e):void 0}},O1=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var Ug=(t,e)=>{let r=rw(e),i=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:V(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??we(r)}),{}):void 0,n=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=V(t._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??we(r),a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(o.title=a),r.flags.hasReferencedOpenAiAnyType&&(i||(i={}),i[r.openAiAnyTypeName]||(i[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let s=n===void 0?i?{...o,[r.definitionPath]:i}:o:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...i,[n]:o}};return r.target==="jsonSchema7"?s.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(s.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in s||"oneOf"in s||"allOf"in s||"type"in s&&Array.isArray(s.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),s};function N1(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Zg(t,e){return vt(t)?ln(t,{target:N1(e?.target),io:e?.pipeStrategy??"input"}):Ug(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Mg(t){let r=Tr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let i=tl(r);if(typeof i!="string")throw new Error("Schema method literal must be a string");return i}function qg(t,e){let r=Pr(t,e);if(!r.success)throw r.error;return r.data}var j1=6e4,rd=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Rl,r=>{this._oncancel(r)}),this.setNotificationHandler(Dl,r=>{this._onprogress(r)}),this.setRequestHandler(Cl,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ul,async(r,i)=>{let n=await this._taskStore.getTask(r.params.taskId,i.sessionId);if(!n)throw new Z(L.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(Ml,async(r,i)=>{let n=async()=>{let o=r.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(o,i.sessionId);){if(s.type==="response"||s.type==="error"){let c=s.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),s.type==="response")l(c);else{let d=c,f=new Z(d.error.code,d.error.message,d.error.data);l(f)}else{let d=s.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(s.message,{relatedRequestId:i.requestId})}}let a=await this._taskStore.getTask(o,i.sessionId);if(!a)throw new Z(L.InvalidParams,`Task not found: ${o}`);if(!Nr(a.status))return await this._waitForTaskUpdate(o,i.signal),await n();if(Nr(a.status)){let s=await this._taskStore.getTaskResult(o,i.sessionId);return this._clearTaskQueue(o),{...s,_meta:{...s._meta,[Or]:{taskId:o}}}}return await n()};return await n()}),this.setRequestHandler(ql,async(r,i)=>{try{let{tasks:n,nextCursor:o}=await this._taskStore.listTasks(r.params?.cursor,i.sessionId);return{tasks:n,nextCursor:o,_meta:{}}}catch(n){throw new Z(L.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(Fl,async(r,i)=>{try{let n=await this._taskStore.getTask(r.params.taskId,i.sessionId);if(!n)throw new Z(L.InvalidParams,`Task not found: ${r.params.taskId}`);if(Nr(n.status))throw new Z(L.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",i.sessionId),this._clearTaskQueue(r.params.taskId);let o=await this._taskStore.getTask(r.params.taskId,i.sessionId);if(!o)throw new Z(L.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(n){throw n instanceof Z?n:new Z(L.InvalidRequest,`Failed to cancel task: ${n instanceof Error?n.message:String(n)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,i,n,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,r),startTime:Date.now(),timeout:r,maxTotalTimeout:i,resetTimeoutOnProgress:o,onTimeout:n})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let i=Date.now()-r.startTime;if(r.maxTotalTimeout&&i>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),Z.fromError(L.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:i});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let i=this.transport?.onerror;this._transport.onerror=o=>{i?.(o),this._onerror(o)};let n=this._transport?.onmessage;this._transport.onmessage=(o,a)=>{n?.(o,a),xa(o)||Lx(o)?this._onresponse(o):bg(o)?this._onrequest(o,a):qx(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let i of this._timeoutInfo.values())clearTimeout(i.timeoutId);this._timeoutInfo.clear();for(let i of this._requestHandlerAbortControllers.values())i.abort();this._requestHandlerAbortControllers.clear();let r=Z.fromError(L.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let i of e.values())i(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(i=>this._onerror(new Error(`Uncaught error in notification handler: ${i}`)))}_onrequest(e,r){let i=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,n=this._transport,o=e.params?._meta?.[Or]?.taskId;if(i===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:L.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:l,timestamp:Date.now()},n?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):n?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let s=Ux(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,n?.sessionId):void 0,u={signal:a.signal,sessionId:n?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{if(a.signal.aborted)return;let d={relatedRequestId:e.id};o&&(d.relatedTask={taskId:o}),await this.notification(l,d)},sendRequest:async(l,d,f)=>{if(a.signal.aborted)throw new Z(L.ConnectionClosed,"Request was cancelled");let p={...f,relatedRequestId:e.id};o&&!p.relatedTask&&(p.relatedTask={taskId:o});let h=p.relatedTask?.taskId??o;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(l,d,p)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:o,taskStore:c,taskRequestedTtl:s?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(e.method)}).then(()=>i(e,u)).then(async l=>{if(a.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:d,timestamp:Date.now()},n?.sessionId):await n?.send(d)},async l=>{if(a.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:L.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:d,timestamp:Date.now()},n?.sessionId):await n?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===a&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...i}=e.params,n=Number(r),o=this._progressHandlers.get(n);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(n),s=this._timeoutInfo.get(n);if(s&&a&&s.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(c){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),a(c);return}o(i)}_onresponse(e){let r=Number(e.id),i=this._requestResolvers.get(r);if(i){if(this._requestResolvers.delete(r),xa(e))i(e);else{let a=new Z(e.error.code,e.error.message,e.error.data);i(a)}return}let n=this._responseHandlers.get(r);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let o=!1;if(xa(e)&&e.result&&typeof e.result=="object"){let a=e.result;if(a.task&&typeof a.task=="object"){let s=a.task;typeof s.taskId=="string"&&(o=!0,this._taskProgressTokens.set(s.taskId,r))}}if(o||this._progressHandlers.delete(r),xa(e))n(e);else{let a=Z.fromError(e.error.code,e.error.message,e.error.data);n(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,i){let{task:n}=i??{};if(!n){try{yield{type:"result",result:await this.request(e,r,i)}}catch(a){yield{type:"error",error:a instanceof Z?a:new Z(L.InternalError,String(a))}}return}let o;try{let a=await this.request(e,Ei,i);if(a.task)o=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new Z(L.InternalError,"Task creation did not return a task");for(;;){let s=await this.getTask({taskId:o},i);if(yield{type:"taskStatus",task:s},Nr(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,i)}:s.status==="failed"?yield{type:"error",error:new Z(L.InternalError,`Task ${o} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new Z(L.InternalError,`Task ${o} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},r,i)};return}let c=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),i?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof Z?a:new Z(L.InternalError,String(a))}}}request(e,r,i){let{relatedRequestId:n,resumptionToken:o,onresumptiontoken:a,task:s,relatedTask:c}=i??{};return new Promise((u,l)=>{let d=k=>{l(k)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),s&&this.assertTaskCapability(e.method)}catch(k){d(k);return}i?.signal?.throwIfAborted();let f=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:f};i?.onprogress&&(this._progressHandlers.set(f,i.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:f}}),s&&(p.params={...p.params,task:s}),c&&(p.params={...p.params,_meta:{...p.params?._meta||{},[Or]:c}});let h=k=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(k)}},{relatedRequestId:n,resumptionToken:o,onresumptiontoken:a}).catch(I=>this._onerror(new Error(`Failed to send cancellation: ${I}`)));let x=k instanceof Z?k:new Z(L.RequestTimeout,String(k));l(x)};this._responseHandlers.set(f,k=>{if(!i?.signal?.aborted){if(k instanceof Error)return l(k);try{let x=Pr(r,k.result);x.success?u(x.data):l(x.error)}catch(x){l(x)}}}),i?.signal?.addEventListener("abort",()=>{h(i?.signal?.reason)});let m=i?.timeout??j1,g=()=>h(Z.fromError(L.RequestTimeout,"Request timed out",{timeout:m}));this._setupTimeout(f,m,i?.maxTotalTimeout,g,i?.resetTimeoutOnProgress??!1);let $=c?.taskId;if($){let k=x=>{let I=this._responseHandlers.get(f);I?I(x):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,k),this._enqueueTaskMessage($,{type:"request",message:p,timestamp:Date.now()}).catch(x=>{this._cleanupTimeout(f),l(x)})}else this._transport.send(p,{relatedRequestId:n,resumptionToken:o,onresumptiontoken:a}).catch(k=>{this._cleanupTimeout(f),l(k)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Zl,r)}async getTaskResult(e,r,i){return this.request({method:"tasks/result",params:e},r,i)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},Ll,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Jx,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let i=r?.relatedTask?.taskId;if(i){let s={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Or]:r.relatedTask}}};await this._enqueueTaskMessage(i,{type:"notification",message:s,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let s={...e,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Or]:r.relatedTask}}}),this._transport?.send(s,r).catch(c=>this._onerror(c))});return}let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Or]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(e,r){let i=Mg(e);this.assertRequestHandlerCapability(i),this._requestHandlers.set(i,(n,o)=>{let a=qg(e,n);return Promise.resolve(r(a,o))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let i=Mg(e);this._notificationHandlers.set(i,n=>{let o=qg(e,n);return Promise.resolve(r(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,i){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,i,n)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let i=await this._taskMessageQueue.dequeueAll(e,r);for(let n of i)if(n.type==="request"&&bg(n.message)){let o=n.message.id,a=this._requestResolvers.get(o);a?(a(new Z(L.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let i=this._options?.defaultTaskPollInterval??1e3;try{let n=await this._taskStore?.getTask(e);n?.pollInterval&&(i=n.pollInterval)}catch{}return new Promise((n,o)=>{if(r.aborted){o(new Z(L.InvalidRequest,"Request cancelled"));return}let a=setTimeout(n,i);r.addEventListener("abort",()=>{clearTimeout(a),o(new Z(L.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let i=this._taskStore;if(!i)throw new Error("No task store configured");return{createTask:async n=>{if(!e)throw new Error("No request provided");return await i.createTask(n,e.id,{method:e.method,params:e.params},r)},getTask:async n=>{let o=await i.getTask(n,r);if(!o)throw new Z(L.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(n,o,a)=>{await i.storeTaskResult(n,o,a,r);let s=await i.getTask(n,r);if(s){let c=Pa.parse({method:"notifications/tasks/status",params:s});await this.notification(c),Nr(s.status)&&this._cleanupTaskProgressHandler(n)}},getTaskResult:n=>i.getTaskResult(n,r),updateTaskStatus:async(n,o,a)=>{let s=await i.getTask(n,r);if(!s)throw new Z(L.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(Nr(s.status))throw new Z(L.InvalidParams,`Cannot update task "${n}" from terminal status "${s.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await i.updateTaskStatus(n,o,a,r);let c=await i.getTask(n,r);if(c){let u=Pa.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Nr(c.status)&&this._cleanupTaskProgressHandler(n)}},listTasks:n=>i.listTasks(n,r)}}};function Ow(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Nw(t,e){let r={...t};for(let i in e){let n=i,o=e[n];if(o===void 0)continue;let a=r[n];Ow(a)&&Ow(o)?r[n]={...a,...o}:r[n]=o}return r}var xz=Vf(Iy(),1),wz=Vf(kz(),1);function CU(){let t=new xz.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,wz.default)(t),t}var Dd=class{constructor(e){this._ajv=e??CU()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return i=>r(i)?{valid:!0,data:i,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var Ud=class{constructor(e){this._server=e}requestStream(e,r,i){return this._server.requestStream(e,r,i)}createMessageStream(e,r){let i=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!i?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],a=o.some(l=>l.type==="tool_result"),s=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=s?Array.isArray(s.content)?s.content:[s.content]:[],u=c.some(l=>l.type==="tool_use");if(a){if(o.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(f=>f.type==="tool_use").map(f=>f.id)),d=new Set(o.filter(f=>f.type==="tool_result").map(f=>f.toolUseId));if(l.size!==d.size||![...l].every(f=>d.has(f)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},Oa,r)}elicitInputStream(e,r){let i=this._server.getClientCapabilities(),n=e.mode??"form";switch(n){case"url":{if(!i?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!i?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let o=n==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:o},ji,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,i){return this._server.getTaskResult({taskId:e},r,i)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function Sz(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function zz(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var Zd=class extends rd{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Ea.options.map((i,n)=>[i,n])),this.isMessageIgnored=(i,n)=>{let o=this._loggingLevels.get(n);return o?this.LOG_LEVEL_SEVERITY.get(i)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Dd,this.setRequestHandler(xg,i=>this._oninitialize(i)),this.setNotificationHandler(wg,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Og,async(i,n)=>{let o=n.sessionId||n.requestInfo?.headers["mcp-session-id"]||void 0,{level:a}=i.params,s=Ea.safeParse(a);return s.success&&this._loggingLevels.set(o,s.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Ud(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Nw(this._capabilities,e)}setRequestHandler(e,r){let n=Tr(e)?.method;if(!n)throw new Error("Schema is missing a method literal");let o;if(vt(n)){let s=n;o=s._zod?.def?.value??s.value}else{let s=n;o=s._def?.value??s.value}if(typeof o!="string")throw new Error("Schema method literal must be a string");if(o==="tools/call"){let s=async(c,u)=>{let l=Pr(Ni,c);if(!l.success){let h=l.error instanceof Error?l.error.message:String(l.error);throw new Z(L.InvalidParams,`Invalid tools/call request: ${h}`)}let{params:d}=l.data,f=await Promise.resolve(r(c,u));if(d.task){let h=Pr(Ei,f);if(!h.success){let m=h.error instanceof Error?h.error.message:String(h.error);throw new Z(L.InvalidParams,`Invalid task creation result: ${m}`)}return h.data}let p=Pr(Wl,f);if(!p.success){let h=p.error instanceof Error?p.error.message:String(p.error);throw new Z(L.InvalidParams,`Invalid tools/call result: ${h}`)}return p.data};return super.setRequestHandler(e,s)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){zz(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Sz(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Rx.includes(r)?r:yg,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"},Al)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let i=e.messages[e.messages.length-1],n=Array.isArray(i.content)?i.content:[i.content],o=n.some(u=>u.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,s=a?Array.isArray(a.content)?a.content:[a.content]:[],c=s.some(u=>u.type==="tool_use");if(o){if(n.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(s.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(n.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},Ng,r):this.request({method:"sampling/createMessage",params:e},Oa,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let n=e;return this.request({method:"elicitation/create",params:n},ji,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let n=e.mode==="form"?e:{...e,mode:"form"},o=await this.request({method:"elicitation/create",params:n},ji,r);if(o.action==="accept"&&o.content&&n.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(n.requestedSchema)(o.content);if(!s.valid)throw new Z(L.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(a){throw a instanceof Z?a:new Z(L.InternalError,`Error validating elicitation response: ${a instanceof Error?a.message:String(a)}`)}return o}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},jg,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var Pz=Symbol.for("mcp.completable");function Ry(t){return!!t&&typeof t=="object"&&Pz in t}function Tz(t){return t[Pz]?.complete}var Iz;(function(t){t.Completable="McpCompletable"})(Iz||(Iz={}));var DU=/^[A-Za-z0-9._-]{1,128}$/;function UU(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!DU.test(t)){let r=t.split("").filter(i=>!/[A-Za-z0-9._-]/.test(i)).filter((i,n,o)=>o.indexOf(i)===n);return e.push(`Tool name contains invalid characters: ${r.map(i=>`"${i}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function ZU(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);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 Cy(t){let e=UU(t);return ZU(t,e.warnings),e.isValid}var Md=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,i){let n={taskSupport:"required",...r.execution};if(n.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,n,r._meta,i)}};var qd=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Zd(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Md(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(qr(Gl)),this.server.assertCanSetRequestHandler(qr(Ni)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Gl,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let i={name:e,title:r.title,description:r.description,inputSchema:(()=>{let n=_i(r.inputSchema);return n?Zg(n,{strictUnions:!0,pipeStrategy:"input"}):MU})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let n=_i(r.outputSchema);n&&(i.outputSchema=Zg(n,{strictUnions:!0,pipeStrategy:"output"}))}return i})})),this.server.setRequestHandler(Ni,async(e,r)=>{try{let i=this._registeredTools[e.params.name];if(!i)throw new Z(L.InvalidParams,`Tool ${e.params.name} not found`);if(!i.enabled)throw new Z(L.InvalidParams,`Tool ${e.params.name} disabled`);let n=!!e.params.task,o=i.execution?.taskSupport,a="createTask"in i.handler;if((o==="required"||o==="optional")&&!a)throw new Z(L.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!n)throw new Z(L.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!n&&a)return await this.handleAutomaticTaskPolling(i,e,r);let s=await this.validateToolInput(i,e.params.arguments,e.params.name),c=await this.executeToolHandler(i,s,r);return n||await this.validateToolOutput(i,c,e.params.name),c}catch(i){if(i instanceof Z&&i.code===L.UrlElicitationRequired)throw i;return this.createToolError(i instanceof Error?i.message:String(i))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,i){if(!e.inputSchema)return;let o=_i(e.inputSchema)??e.inputSchema,a=await Qu(o,r);if(!a.success){let s="error"in a?a.error:"Unknown error",c=el(s);throw new Z(L.InvalidParams,`Input validation error: Invalid arguments for tool ${i}: ${c}`)}return a.data}async validateToolOutput(e,r,i){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new Z(L.InvalidParams,`Output validation error: Tool ${i} has an output schema but no structured content was provided`);let n=_i(e.outputSchema),o=await Qu(n,r.structuredContent);if(!o.success){let a="error"in o?o.error:"Unknown error",s=el(a);throw new Z(L.InvalidParams,`Output validation error: Invalid structured content for tool ${i}: ${s}`)}}async executeToolHandler(e,r,i){let n=e.handler;if("createTask"in n){if(!i.taskStore)throw new Error("No task store provided.");let a={...i,taskStore:i.taskStore};if(e.inputSchema){let s=n;return await Promise.resolve(s.createTask(r,a))}else{let s=n;return await Promise.resolve(s.createTask(a))}}if(e.inputSchema){let a=n;return await Promise.resolve(a(r,i))}else{let a=n;return await Promise.resolve(a(i))}}async handleAutomaticTaskPolling(e,r,i){if(!i.taskStore)throw new Error("No task store provided for task-capable tool.");let n=await this.validateToolInput(e,r.params.arguments,r.params.name),o=e.handler,a={...i,taskStore:i.taskStore},s=n?await Promise.resolve(o.createTask(n,a)):await Promise.resolve(o.createTask(a)),c=s.task.taskId,u=s.task,l=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(f=>setTimeout(f,l));let d=await i.taskStore.getTask(c);if(!d)throw new Z(L.InternalError,`Task ${c} not found during polling`);u=d}return await i.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(qr(Yl)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Yl,async e=>{switch(e.params.ref.type){case"ref/prompt":return Yx(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Xx(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Z(L.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let i=this._registeredPrompts[r.name];if(!i)throw new Z(L.InvalidParams,`Prompt ${r.name} not found`);if(!i.enabled)throw new Z(L.InvalidParams,`Prompt ${r.name} disabled`);if(!i.argsSchema)return cs;let o=Tr(i.argsSchema)?.[e.params.argument.name];if(!Ry(o))return cs;let a=Tz(o);if(!a)return cs;let s=await a(e.params.argument.value,e.params.context);return Oz(s)}async handleResourceCompletion(e,r){let i=Object.values(this._registeredResourceTemplates).find(a=>a.resourceTemplate.uriTemplate.toString()===r.uri);if(!i){if(this._registeredResources[r.uri])return cs;throw new Z(L.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let n=i.resourceTemplate.completeCallback(e.params.argument.name);if(!n)return cs;let o=await n(e.params.argument.value,e.params.context);return Oz(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(qr(Vl)),this.server.assertCanSetRequestHandler(qr(Jl)),this.server.assertCanSetRequestHandler(qr(Bl)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Vl,async(e,r)=>{let i=Object.entries(this._registeredResources).filter(([o,a])=>a.enabled).map(([o,a])=>({uri:o,name:a.name,...a.metadata})),n=[];for(let o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;let a=await o.resourceTemplate.listCallback(r);for(let s of a.resources)n.push({...o.metadata,...s})}return{resources:[...i,...n]}}),this.server.setRequestHandler(Jl,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,i])=>({name:r,uriTemplate:i.resourceTemplate.uriTemplate.toString(),...i.metadata}))})),this.server.setRequestHandler(Bl,async(e,r)=>{let i=new URL(e.params.uri),n=this._registeredResources[i.toString()];if(n){if(!n.enabled)throw new Z(L.InvalidParams,`Resource ${i} disabled`);return n.readCallback(i,r)}for(let o of Object.values(this._registeredResourceTemplates)){let a=o.resourceTemplate.uriTemplate.match(i.toString());if(a)return o.readCallback(i,a,r)}throw new Z(L.InvalidParams,`Resource ${i} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(qr(Kl)),this.server.assertCanSetRequestHandler(qr(Hl)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Kl,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?qU(r.argsSchema):void 0}))})),this.server.setRequestHandler(Hl,async(e,r)=>{let i=this._registeredPrompts[e.params.name];if(!i)throw new Z(L.InvalidParams,`Prompt ${e.params.name} not found`);if(!i.enabled)throw new Z(L.InvalidParams,`Prompt ${e.params.name} disabled`);if(i.argsSchema){let n=_i(i.argsSchema),o=await Qu(n,e.params.arguments);if(!o.success){let c="error"in o?o.error:"Unknown error",u=el(c);throw new Z(L.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let a=o.data,s=i.callback;return await Promise.resolve(s(a,r))}else{let n=i.callback;return await Promise.resolve(n(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...i){let n;typeof i[0]=="object"&&(n=i.shift());let o=i[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let a=this._createRegisteredResource(e,void 0,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let a=this._createRegisteredResourceTemplate(e,void 0,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}registerResource(e,r,i,n){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let o=this._createRegisteredResource(e,i.title,r,i,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,i.title,r,i,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,r,i,n,o){let a={name:e,title:r,metadata:n,readCallback:o,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:s=>{typeof s.uri<"u"&&s.uri!==i&&(delete this._registeredResources[i],s.uri&&(this._registeredResources[s.uri]=a)),typeof s.name<"u"&&(a.name=s.name),typeof s.title<"u"&&(a.title=s.title),typeof s.metadata<"u"&&(a.metadata=s.metadata),typeof s.callback<"u"&&(a.readCallback=s.callback),typeof s.enabled<"u"&&(a.enabled=s.enabled),this.sendResourceListChanged()}};return this._registeredResources[i]=a,a}_createRegisteredResourceTemplate(e,r,i,n,o){let a={resourceTemplate:i,title:r,metadata:n,readCallback:o,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=a)),typeof u.title<"u"&&(a.title=u.title),typeof u.template<"u"&&(a.resourceTemplate=u.template),typeof u.metadata<"u"&&(a.metadata=u.metadata),typeof u.callback<"u"&&(a.readCallback=u.callback),typeof u.enabled<"u"&&(a.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let s=i.uriTemplate.variableNames;return Array.isArray(s)&&s.some(u=>!!i.completeCallback(u))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,r,i,n,o){let a={title:r,description:i,argsSchema:n===void 0?void 0:dn(n),callback:o,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:s=>{typeof s.name<"u"&&s.name!==e&&(delete this._registeredPrompts[e],s.name&&(this._registeredPrompts[s.name]=a)),typeof s.title<"u"&&(a.title=s.title),typeof s.description<"u"&&(a.description=s.description),typeof s.argsSchema<"u"&&(a.argsSchema=dn(s.argsSchema)),typeof s.callback<"u"&&(a.callback=s.callback),typeof s.enabled<"u"&&(a.enabled=s.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,n&&Object.values(n).some(c=>{let u=c instanceof Pi?c._def?.innerType:c;return Ry(u)})&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,r,i,n,o,a,s,c,u){Cy(e);let l={title:r,description:i,inputSchema:Ez(n),outputSchema:Ez(o),annotations:a,execution:s,_meta:c,handler:u,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(typeof d.name=="string"&&Cy(d.name),delete this._registeredTools[e],d.name&&(this._registeredTools[d.name]=l)),typeof d.title<"u"&&(l.title=d.title),typeof d.description<"u"&&(l.description=d.description),typeof d.paramsSchema<"u"&&(l.inputSchema=dn(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=dn(d.outputSchema)),typeof d.callback<"u"&&(l.handler=d.callback),typeof d.annotations<"u"&&(l.annotations=d.annotations),typeof d._meta<"u"&&(l._meta=d._meta),typeof d.enabled<"u"&&(l.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let i,n,o,a;if(typeof r[0]=="string"&&(i=r.shift()),r.length>1){let c=r[0];if(Dy(c))n=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Dy(r[0])&&(a=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);a=r.shift()}}let s=r[0];return this._createRegisteredTool(e,void 0,i,n,o,a,{taskSupport:"forbidden"},void 0,s)}registerTool(e,r,i){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:n,description:o,inputSchema:a,outputSchema:s,annotations:c,_meta:u}=r;return this._createRegisteredTool(e,n,o,a,s,c,{taskSupport:"forbidden"},u,i)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let i;typeof r[0]=="string"&&(i=r.shift());let n;r.length>1&&(n=r.shift());let o=r[0],a=this._createRegisteredPrompt(e,void 0,i,n,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,r,i){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:n,description:o,argsSchema:a}=r,s=this._createRegisteredPrompt(e,n,o,a,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var MU={type:"object",properties:{}};function Nz(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function jz(t){return"_def"in t||"_zod"in t||Nz(t)}function Dy(t){return typeof t!="object"||t===null||jz(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(Nz)}function Ez(t){if(t){if(Dy(t))return dn(t);if(!jz(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function qU(t){let e=Tr(t);return e?Object.entries(e).map(([r,i])=>{let n=bk(i),o=$k(i);return{name:r,description:n,required:!o}}):[]}function qr(t){let r=Tr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let i=tl(r);if(typeof i=="string")return i;throw new Error("Schema method literal must be a string")}function Oz(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var cs={completion:{values:[],hasMore:!1}};import Rz from"node:process";var Ld=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
217
217
|
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),LU(r)}clear(){this._buffer=void 0}};function LU(t){return Fx.parse(JSON.parse(t))}function Az(t){return JSON.stringify(t)+`
|
|
218
|
-
`}var Fd=class{constructor(e=Rz.stdin,r=Rz.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Ld,this._started=!1,this._ondata=i=>{this._readBuffer.append(i),this.processReadBuffer()},this._onerror=i=>{this.onerror?.(i)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let i=Az(e);this._stdout.write(i)?r():this._stdout.once("drain",r)})}};var qT=Vf(wT(),1);import{existsSync as kL,readFileSync as xL}from"node:fs";var Xt=class extends Error{constructor(r,i,n){super(r);this.status=i;this.name="CliError",this.code=n?.code,this.details=n?.details}status;code;details};function uo(t,e){let r=new URLSearchParams;for(let[n,o]of Object.entries(e))o&&r.set(n,o);let i=r.toString();return i?`${t}?${i}`:t}function ST(t){let e=null;async function r(){let o=await fetch(`${t.apiUrl}/auth/cli/exchange`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"}});if(!o.ok){let s=(await o.json().catch(()=>null))?.error;throw new Xt(
|
|
218
|
+
`}var Fd=class{constructor(e=Rz.stdin,r=Rz.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Ld,this._started=!1,this._ondata=i=>{this._readBuffer.append(i),this.processReadBuffer()},this._onerror=i=>{this.onerror?.(i)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let i=Az(e);this._stdout.write(i)?r():this._stdout.once("drain",r)})}};var qT=Vf(wT(),1);import{existsSync as kL,readFileSync as xL}from"node:fs";var Xt=class extends Error{constructor(r,i,n){super(r);this.status=i;this.name="CliError",this.code=n?.code,this.details=n?.details}status;code;details};function uo(t,e){let r=new URLSearchParams;for(let[n,o]of Object.entries(e))o&&r.set(n,o);let i=r.toString();return i?`${t}?${i}`:t}function ST(t){let e=null;async function r(){let o=await fetch(`${t.apiUrl}/auth/cli/exchange`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"}});if(!o.ok){let s=(await o.json().catch(()=>null))?.error,c=typeof s=="string"?{message:s}:s;throw new Xt(c?.message??o.statusText,o.status,{code:c?.code,details:c?.details})}return e=await o.json(),e}async function i(){if(!t.token.startsWith("mk_"))return t.token;let o=e?Date.parse(e.expiresAt):0;return(!e||o-Date.now()<6e4)&&await r(),e.accessToken}async function n(o,a,s){let c=await i(),u=await fetch(`${t.apiUrl}${a}`,{method:o,headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json"},body:s?JSON.stringify(s):void 0});if(!u.ok){let d=(await u.json().catch(()=>null))?.error,f=typeof d=="string"?{message:d}:d;throw new Xt(f?.message??u.statusText,u.status,{code:f?.code,details:f?.details})}if(u.status!==204)return u.json()}return{exchangeCliToken:r,bootstrap:()=>n("POST","/builder/context/bootstrap"),listProducts:()=>n("GET","/products"),initProduct:o=>n("POST","/products/init",o),updateProduct:(o,a,s)=>n("PATCH",uo(`/products/${o}`,{env:s?.env}),a),publishProduct:o=>n("POST",`/products/${o}/publish`),createPlan:(o,a,s)=>n("POST",uo(`/products/${o}/plans`,{env:s?.env}),a),updatePlan:(o,a,s,c)=>n("PATCH",uo(`/products/${o}/plans/${a}`,{env:c?.env}),s),deletePlan:(o,a,s)=>n("DELETE",uo(`/products/${o}/plans/${a}`,{env:s?.env})),getProduct:(o,a)=>n("GET",uo(`/products/${o}`,{env:a?.env})),listEnvironments:o=>n("GET",`/products/${o}/environments`),createEnvironment:(o,a)=>n("POST",`/products/${o}/environments`,a),deleteEnvironment:(o,a)=>n("DELETE",`/products/${o}/environments/${encodeURIComponent(a)}`),deleteProduct:o=>n("DELETE",`/products/${o}`),managementListPlans:o=>n("GET",`/management/products/${o}/plans`),managementGetUsage:o=>n("GET",`/management/products/${o}/usage`),managementListMakerTokens:()=>n("GET","/maker-tokens"),managementCreateMakerToken:o=>n("POST","/maker-tokens",o),managementRevokeMakerToken:o=>n("DELETE",`/maker-tokens/${o}`),builderGitHubStatus:()=>n("GET","/builder/git/github/status"),productStripeStatus:o=>n("GET",`/products/${o}/stripe/status`),issuePersonaBootstrapKey:async(o,a,s)=>{let c=await fetch(`${t.apiUrl}/portal/products/${o}/environments/${a}/test/bootstrap-key`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify(s??{})});if(!c.ok){let l=(await c.json().catch(()=>null))?.error,d=typeof l=="string"?{message:l}:l;throw new Xt(d?.message??c.statusText,c.status,{code:d?.code,details:d?.details})}return c.json()},listPersonas:async(o,a)=>{let s=await fetch(`${t.apiUrl}/portal/products/${o}/environments/${a}/test/personas`,{method:"GET",headers:{Authorization:`Bearer ${t.token}`}});if(!s.ok){let u=(await s.json().catch(()=>null))?.error,l=typeof u=="string"?{message:u}:u;throw new Xt(l?.message??s.statusText,s.status,{code:l?.code,details:l?.details})}return s.json()},revokePersona:async(o,a,s)=>{let c=await fetch(`${t.apiUrl}/portal/products/${o}/environments/${a}/test/personas/${s}`,{method:"DELETE",headers:{Authorization:`Bearer ${t.token}`}});if(!c.ok){let l=(await c.json().catch(()=>null))?.error,d=typeof l=="string"?{message:l}:l;throw new Xt(d?.message??c.statusText,c.status,{code:d?.code,details:d?.details})}return c.json()},getProductConfig:(o,a)=>n("GET",uo(`/products/${o}/config`,{format:"json",env:a?.env,state:a?.state})),updateProductConfigDraft:(o,a,s)=>n("PATCH",`/products/${o}/config/draft`,{spec:a,dryRun:s?.dryRun===!0,env:s?.env,branch:s?.branch,source:s?.source,baseDraftHash:s?.baseDraftHash}),validateProductConfigDraft:(o,a)=>n("POST",`/products/${o}/config/draft/validate`,{env:a?.env}),applyProductConfig:(o,a)=>n("POST",`/products/${o}/config/apply`,{spec:a?.spec,dryRun:a?.dryRun===!0,env:a?.env,branch:a?.branch,source:a?.source,draftHash:a?.draftHash}),compileProduct:(o,a)=>n("POST",`/products/${o}/compile`,gL(a))}}function gL(t){let e={};return t?.branch&&(e.branch=t.branch),t?.dryRun&&(e.dryRun=!0),t?.env&&(e.env=t.env),Object.keys(e).length>0?e:void 0}import{existsSync as _b,mkdirSync as vL,readFileSync as TT,writeFileSync as o5}from"node:fs";import{homedir as yL}from"node:os";import{join as bb}from"node:path";var zT="https://core.farthershore.com";var $b=bb(yL(),".farthershore"),IT=bb($b,"config.json"),PT=bb($b,"credentials.json");function _L(t){_b(t)||vL(t,{recursive:!0,mode:448})}var yb={apiUrl:zT};function ET(){if(_L($b),!_b(IT))return yb;try{let t=JSON.parse(TT(IT,"utf-8"));return{...yb,...t}}catch{return yb}}function OT(){if(!_b(PT))return null;try{return JSON.parse(TT(PT,"utf-8"))}catch{return null}}function NT(t){if(t)return t;let e=process.env.FARTHERSHORE_TOKEN;if(e)return e;let r=OT();if(r?.token)return r.token;throw new Xt("Not authenticated. Run `farthershore auth login` or set FARTHERSHORE_TOKEN environment variable.")}var $L=new Set(["production","prod","main"]);async function AT(t,e){if(e){if(e.length===36)return e;let i=(await t.listProducts()).find(n=>n.id===e||n.name.toLowerCase()===e.toLowerCase());if(i)return i.id}throw new Error("No product selected. Pass --product <id-or-name> or run `farthershore product create` first.")}function jT(t){let e=t?.trim();if(e)return $L.has(e.toLowerCase())?null:e}function RT(t){let e=jT(t);if(e!==void 0)return{name:e,production:e===null};let r=jT(process.env.FARTHERSHORE_ENV);return r!==void 0?{name:r,production:r===null}:{name:null,production:!0}}function CT(t){return t.production?void 0:t.name??void 0}function DT(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function UT(){let t=ET(),e=NT(void 0),r=process.env.FARTHERSHORE_API_URL??t.apiUrl;return ST({apiUrl:r,token:e})}async function ZT(t,e,r){let i=await AT(t,e),n=RT(r);return{productId:i,environment:n,env:CT(n)}}var MT={product:pn.string().optional(),env:pn.string().optional()};function wL(){let t=new qd({name:"farthershore-agent-product-builder",version:"0.1.0"});return t.tool("farthershore_draft_validate",MT,async({product:e,env:r})=>{let i=UT(),n=await ZT(i,e,r);return DT({ok:!0,...n,result:await i.validateProductConfigDraft(n.productId,{env:n.env})})}),t.tool("farthershore_apply",{...MT,toFile:pn.string().optional(),dryRun:pn.boolean().default(!0)},async({product:e,env:r,toFile:i,dryRun:n})=>{let o=UT(),a=await ZT(o,e,r),s=i&&kL(i)?qT.default.parse(xL(i,"utf-8")):void 0;return DT({ok:!0,...a,result:await o.applyProductConfig(a.productId,{spec:s,env:a.env,dryRun:n,source:"MCP"})})}),t}async function SL(){let t=wL(),e=new Fd;await t.connect(e)}import.meta.url===`file://${process.argv[1]}`&&SL();export{wL as createMcpServer};
|