@farthershore/cli 0.6.0 → 0.7.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 +5 -5
- package/dist/index.js +136 -137
- package/dist/mcp.js +1 -1
- package/package.json +2 -2
package/dist/mcp.js
CHANGED
|
@@ -197,4 +197,4 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
197
197
|
`:`[${i[c]}\r
|
|
198
198
|
]`;continue}n+=i[c],i[c]==="\\"?o=!0:s&&i[c]==="]"?s=!1:!s&&i[c]==="["&&(s=!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 yp(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===T.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((i,n)=>({...i,[n]:K(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",n]})??Ue(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:K(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===T.ZodString&&t.keyType._def.checks?.length){let{type:i,...n}=gp(t.keyType._def,e);return{...r,propertyNames:n}}else{if(t.keyType?._def.typeName===T.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===T.ZodBranded&&t.keyType._def.type._def.typeName===T.ZodString&&t.keyType._def.type._def.checks?.length){let{type:i,...n}=hp(t.keyType._def,e);return{...r,propertyNames:n}}}return r}function oI(t,e){if(e.mapStrategy==="record")return yp(t,e);let r=K(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Ue(e),i=K(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Ue(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,i],minItems:2,maxItems:2}}}function sI(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 aI(t){return t.target==="openAi"?void 0:{not:Ue({...t,currentPath:[...t.currentPath,"not"]})}}function cI(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var tc={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function lI(t,e){if(e.target==="openApi3")return uI(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(i=>i._def.typeName in tc&&(!i._def.checks||!i._def.checks.length))){let i=r.reduce((n,o)=>{let s=tc[o._def.typeName];return s&&!n.includes(s)?[...n,s]: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 s=typeof o._def.value;switch(s){case"string":case"number":case"boolean":return[...n,s];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,s,a)=>a.indexOf(o)===s);return{type:n.length>1?n:n[0],enum:r.reduce((o,s)=>o.includes(s._def.value)?o:[...o,s._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 uI(t,e)}var uI=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((i,n)=>K(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 dI(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:tc[t.innerType._def.typeName],nullable:!0}:{type:[tc[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let i=K(t.innerType._def,{...e,currentPath:[...e.currentPath]});return i&&"$ref"in i?{allOf:[i],nullable:!0}:i&&{...i,nullable:!0}}let r=K(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function fI(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",t_(r,"type",i.message,e);break;case"min":e.target==="jsonSchema7"?i.inclusive?le(r,"minimum",i.value,i.message,e):le(r,"exclusiveMinimum",i.value,i.message,e):(i.inclusive||(r.exclusiveMinimum=!0),le(r,"minimum",i.value,i.message,e));break;case"max":e.target==="jsonSchema7"?i.inclusive?le(r,"maximum",i.value,i.message,e):le(r,"exclusiveMaximum",i.value,i.message,e):(i.inclusive||(r.exclusiveMaximum=!0),le(r,"maximum",i.value,i.message,e));break;case"multipleOf":le(r,"multipleOf",i.value,i.message,e);break}return r}function pI(t,e){let r=e.target==="openAi",i={type:"object",properties:{}},n=[],o=t.shape();for(let a in o){let c=o[a];if(c===void 0||c._def===void 0)continue;let u=EM(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=K(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});l!==void 0&&(i.properties[a]=l,u||n.push(a))}n.length&&(i.required=n);let s=IM(t,e);return s!==void 0&&(i.additionalProperties=s),i}function IM(t,e){if(t.catchall._def.typeName!=="ZodNever")return K(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 EM(t){try{return t.isOptional()}catch{return!0}}var mI=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return K(t.innerType._def,e);let r=K(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ue(e)},r]}:Ue(e)};var hI=(t,e)=>{if(e.pipeStrategy==="input")return K(t.in._def,e);if(e.pipeStrategy==="output")return K(t.out._def,e);let r=K(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),i=K(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,i].filter(n=>n!==void 0)}};function gI(t,e){return K(t.type._def,e)}function yI(t,e){let i={type:"array",uniqueItems:!0,items:K(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&le(i,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&le(i,"maxItems",t.maxSize.value,t.maxSize.message,e),i}function vI(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,i)=>K(r._def,{...e,currentPath:[...e.currentPath,"items",`${i}`]})).reduce((r,i)=>i===void 0?r:[...r,i],[]),additionalItems:K(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,i)=>K(r._def,{...e,currentPath:[...e.currentPath,"items",`${i}`]})).reduce((r,i)=>i===void 0?r:[...r,i],[])}}function _I(t){return{not:Ue(t)}}function $I(t){return Ue(t)}var bI=(t,e)=>K(t.innerType._def,e);var wI=(t,e,r)=>{switch(e){case T.ZodString:return gp(t,r);case T.ZodNumber:return fI(t,r);case T.ZodObject:return pI(t,r);case T.ZodBigInt:return WP(t,r);case T.ZodBoolean:return YP();case T.ZodDate:return r_(t,r);case T.ZodUndefined:return _I(r);case T.ZodNull:return cI(r);case T.ZodArray:return GP(t,r);case T.ZodUnion:case T.ZodDiscriminatedUnion:return lI(t,r);case T.ZodIntersection:return rI(t,r);case T.ZodTuple:return vI(t,r);case T.ZodRecord:return yp(t,r);case T.ZodLiteral:return nI(t,r);case T.ZodEnum:return tI(t);case T.ZodNativeEnum:return sI(t);case T.ZodNullable:return dI(t,r);case T.ZodOptional:return mI(t,r);case T.ZodMap:return oI(t,r);case T.ZodSet:return yI(t,r);case T.ZodLazy:return()=>t.getter()._def;case T.ZodPromise:return gI(t,r);case T.ZodNaN:case T.ZodNever:return aI(r);case T.ZodEffects:return eI(t,r);case T.ZodAny:return Ue(r);case T.ZodUnknown:return $I(r);case T.ZodDefault:return QP(t,r);case T.ZodBranded:return hp(t,r);case T.ZodReadonly:return bI(t,r);case T.ZodCatch:return XP(t,r);case T.ZodPipeline:return hI(t,r);case T.ZodFunction:case T.ZodVoid:case T.ZodSymbol:return;default:return(i=>{})(e)}};function K(t,e,r=!1){let i=e.seen.get(t);if(e.override){let a=e.override?.(t,e,i,r);if(a!==JP)return a}if(i&&!r){let a=zM(i,e);if(a!==void 0)return a}let n={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,n);let o=wI(t,t.typeName,e),s=typeof o=="function"?K(o(),e):o;if(s&&TM(t,e,s),e.postProcess){let a=e.postProcess(s,t,e);return n.jsonSchema=s,a}return n.jsonSchema=s,s}var zM=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:mp(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`),Ue(e)):e.$refStrategy==="seen"?Ue(e):void 0}},TM=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var o_=(t,e)=>{let r=HP(e),i=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:K(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??Ue(r)}),{}):void 0,n=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=K(t._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??Ue(r),s=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;s!==void 0&&(o.title=s),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 a=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"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function OM(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function s_(t,e){return Bt(t)?_i(t,{target:OM(e?.target),io:e?.pipeStrategy??"input"}):o_(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function a_(t){let r=kn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let i=gf(r);if(typeof i!="string")throw new Error("Schema method literal must be a string");return i}function c_(t,e){let r=wn(t,e);if(!r.success)throw r.error;return r.data}var NM=6e4,vp=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(Yf,r=>{this._oncancel(r)}),this.setNotificationHandler(Qf,r=>{this._onprogress(r)}),this.setRequestHandler(Xf,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(ep,async(r,i)=>{let n=await this._taskStore.getTask(r.params.taskId,i.sessionId);if(!n)throw new U(V.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(rp,async(r,i)=>{let n=async()=>{let o=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(o,i.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,f=new U(d.error.code,d.error.message,d.error.data);l(f)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:i.requestId})}}let s=await this._taskStore.getTask(o,i.sessionId);if(!s)throw new U(V.InvalidParams,`Task not found: ${o}`);if(!In(s.status))return await this._waitForTaskUpdate(o,i.signal),await n();if(In(s.status)){let a=await this._taskStore.getTaskResult(o,i.sessionId);return this._clearTaskQueue(o),{...a,_meta:{...a._meta,[Pn]:{taskId:o}}}}return await n()};return await n()}),this.setRequestHandler(np,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 U(V.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(op,async(r,i)=>{try{let n=await this._taskStore.getTask(r.params.taskId,i.sessionId);if(!n)throw new U(V.InvalidParams,`Task not found: ${r.params.taskId}`);if(In(n.status))throw new U(V.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 U(V.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(n){throw n instanceof U?n:new U(V.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),U.fromError(V.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,s)=>{n?.(o,s),Ja(o)||RP(o)?this._onresponse(o):Zv(o)?this._onrequest(o,s):jP(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=U.fromError(V.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?.[Pn]?.taskId;if(i===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:V.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 s=new AbortController;this._requestHandlerAbortControllers.set(e.id,s);let a=TP(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,n?.sessionId):void 0,u={signal:s.signal,sessionId:n?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{if(s.signal.aborted)return;let d={relatedRequestId:e.id};o&&(d.relatedTask={taskId:o}),await this.notification(l,d)},sendRequest:async(l,d,f)=>{if(s.signal.aborted)throw new U(V.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:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>i(e,u)).then(async l=>{if(s.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(s.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:V.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)===s&&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 s=this._responseHandlers.get(n),a=this._timeoutInfo.get(n);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(c){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),s(c);return}o(i)}_onresponse(e){let r=Number(e.id),i=this._requestResolvers.get(r);if(i){if(this._requestResolvers.delete(r),Ja(e))i(e);else{let s=new U(e.error.code,e.error.message,e.error.data);i(s)}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(Ja(e)&&e.result&&typeof e.result=="object"){let s=e.result;if(s.task&&typeof s.task=="object"){let a=s.task;typeof a.taskId=="string"&&(o=!0,this._taskProgressTokens.set(a.taskId,r))}}if(o||this._progressHandlers.delete(r),Ja(e))n(e);else{let s=U.fromError(e.error.code,e.error.message,e.error.data);n(s)}}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(s){yield{type:"error",error:s instanceof U?s:new U(V.InternalError,String(s))}}return}let o;try{let s=await this.request(e,qo,i);if(s.task)o=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new U(V.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:o},i);if(yield{type:"taskStatus",task:a},In(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,i)}:a.status==="failed"?yield{type:"error",error:new U(V.InternalError,`Task ${o} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new U(V.InternalError,`Task ${o} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},r,i)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),i?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof U?s:new U(V.InternalError,String(s))}}}request(e,r,i){let{relatedRequestId:n,resumptionToken:o,onresumptiontoken:s,task:a,relatedTask:c}=i??{};return new Promise((u,l)=>{let d=$=>{l($)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch($){d($);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}}),a&&(p.params={...p.params,task:a}),c&&(p.params={...p.params,_meta:{...p.params?._meta||{},[Pn]:c}});let h=$=>{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($)}},{relatedRequestId:n,resumptionToken:o,onresumptiontoken:s}).catch(x=>this._onerror(new Error(`Failed to send cancellation: ${x}`)));let b=$ instanceof U?$:new U(V.RequestTimeout,String($));l(b)};this._responseHandlers.set(f,$=>{if(!i?.signal?.aborted){if($ instanceof Error)return l($);try{let b=wn(r,$.result);b.success?u(b.data):l(b.error)}catch(b){l(b)}}}),i?.signal?.addEventListener("abort",()=>{h(i?.signal?.reason)});let m=i?.timeout??NM,g=()=>h(U.fromError(V.RequestTimeout,"Request timed out",{timeout:m}));this._setupTimeout(f,m,i?.maxTotalTimeout,g,i?.resetTimeoutOnProgress??!1);let v=c?.taskId;if(v){let $=b=>{let x=this._responseHandlers.get(f);x?x(b):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,$),this._enqueueTaskMessage(v,{type:"request",message:p,timestamp:Date.now()}).catch(b=>{this._cleanupTimeout(f),l(b)})}else this._transport.send(p,{relatedRequestId:n,resumptionToken:o,onresumptiontoken:s}).catch($=>{this._cleanupTimeout(f),l($)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},tp,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},ip,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},DP,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 a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Pn]:r.relatedTask}}};await this._enqueueTaskMessage(i,{type:"notification",message:a,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 a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Pn]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let s={...e,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Pn]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(e,r){let i=a_(e);this.assertRequestHandlerCapability(i),this._requestHandlers.set(i,(n,o)=>{let s=c_(e,n);return Promise.resolve(r(s,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=a_(e);this._notificationHandlers.set(i,n=>{let o=c_(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"&&Zv(n.message)){let o=n.message.id,s=this._requestResolvers.get(o);s?(s(new U(V.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 U(V.InvalidRequest,"Request cancelled"));return}let s=setTimeout(n,i);r.addEventListener("abort",()=>{clearTimeout(s),o(new U(V.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 U(V.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(n,o,s)=>{await i.storeTaskResult(n,o,s,r);let a=await i.getTask(n,r);if(a){let c=Ya.parse({method:"notifications/tasks/status",params:a});await this.notification(c),In(a.status)&&this._cleanupTaskProgressHandler(n)}},getTaskResult:n=>i.getTaskResult(n,r),updateTaskStatus:async(n,o,s)=>{let a=await i.getTask(n,r);if(!a)throw new U(V.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(In(a.status))throw new U(V.InvalidParams,`Cannot update task "${n}" from terminal status "${a.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await i.updateTaskStatus(n,o,s,r);let c=await i.getTask(n,r);if(c){let u=Ya.parse({method:"notifications/tasks/status",params:c});await this.notification(u),In(c.status)&&this._cleanupTaskProgressHandler(n)}},listTasks:n=>i.listTasks(n,r)}}};function kI(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function SI(t,e){let r={...t};for(let i in e){let n=i,o=e[n];if(o===void 0)continue;let s=r[n];kI(s)&&kI(o)?r[n]={...s,...o}:r[n]=o}return r}var SN=Ch(Wz(),1),xN=Ch(kN(),1);function vJ(){let t=new SN.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,xN.default)(t),t}var Tm=class{constructor(e){this._ajv=e??vJ()}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 Om=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],s=o.some(l=>l.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(l=>l.type==="tool_use");if(s){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},ec,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},Zo,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 PN(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 IN(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 Nm=class extends vp{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Qa.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 Tm,this.setRequestHandler(Fv,i=>this._oninitialize(i)),this.setNotificationHandler(Kv,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Xv,async(i,n)=>{let o=n.sessionId||n.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=i.params,a=Qa.safeParse(s);return a.success&&this._loggingLevels.set(o,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Om(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=SI(this._capabilities,e)}setRequestHandler(e,r){let n=kn(e)?.method;if(!n)throw new Error("Schema is missing a method literal");let o;if(Bt(n)){let a=n;o=a._zod?.def?.value??a.value}else{let a=n;o=a._def?.value??a.value}if(typeof o!="string")throw new Error("Schema method literal must be a string");if(o==="tools/call"){let a=async(c,u)=>{let l=wn(Uo,c);if(!l.success){let h=l.error instanceof Error?l.error.message:String(l.error);throw new U(V.InvalidParams,`Invalid tools/call request: ${h}`)}let{params:d}=l.data,f=await Promise.resolve(r(c,u));if(d.task){let h=wn(qo,f);if(!h.success){let m=h.error instanceof Error?h.error.message:String(h.error);throw new U(V.InvalidParams,`Invalid task creation result: ${m}`)}return h.data}let p=wn(fp,f);if(!p.success){let h=p.error instanceof Error?p.error.message:String(p.error);throw new U(V.InvalidParams,`Invalid tools/call result: ${h}`)}return p.data};return super.setRequestHandler(e,a)}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){IN(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&PN(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:IP.includes(r)?r:Mv,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"},Wf)}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"),s=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=s?Array.isArray(s.content)?s.content:[s.content]:[],c=a.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(a.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},Qv,r):this.request({method:"sampling/createMessage",params:e},ec,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},Zo,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},Zo,r);if(o.action==="accept"&&o.content&&n.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(n.requestedSchema)(o.content);if(!a.valid)throw new U(V.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(s){throw s instanceof U?s:new U(V.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}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},e_,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 zN=Symbol.for("mcp.completable");function Nw(t){return!!t&&typeof t=="object"&&zN in t}function TN(t){return t[zN]?.complete}var EN;(function(t){t.Completable="McpCompletable"})(EN||(EN={}));var _J=/^[A-Za-z0-9._-]{1,128}$/;function $J(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"),!_J.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 bJ(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 jw(t){let e=$J(t);return bJ(t,e.warnings),e.isValid}var jm=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 Rm=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 Nm(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new jm(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Vn(dp)),this.server.assertCanSetRequestHandler(Vn(Uo)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(dp,()=>({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=Eo(r.inputSchema);return n?s_(n,{strictUnions:!0,pipeStrategy:"input"}):wJ})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let n=Eo(r.outputSchema);n&&(i.outputSchema=s_(n,{strictUnions:!0,pipeStrategy:"output"}))}return i})})),this.server.setRequestHandler(Uo,async(e,r)=>{try{let i=this._registeredTools[e.params.name];if(!i)throw new U(V.InvalidParams,`Tool ${e.params.name} not found`);if(!i.enabled)throw new U(V.InvalidParams,`Tool ${e.params.name} disabled`);let n=!!e.params.task,o=i.execution?.taskSupport,s="createTask"in i.handler;if((o==="required"||o==="optional")&&!s)throw new U(V.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!n)throw new U(V.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!n&&s)return await this.handleAutomaticTaskPolling(i,e,r);let a=await this.validateToolInput(i,e.params.arguments,e.params.name),c=await this.executeToolHandler(i,a,r);return n||await this.validateToolOutput(i,c,e.params.name),c}catch(i){if(i instanceof U&&i.code===V.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=Eo(e.inputSchema)??e.inputSchema,s=await mf(o,r);if(!s.success){let a="error"in s?s.error:"Unknown error",c=hf(a);throw new U(V.InvalidParams,`Input validation error: Invalid arguments for tool ${i}: ${c}`)}return s.data}async validateToolOutput(e,r,i){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new U(V.InvalidParams,`Output validation error: Tool ${i} has an output schema but no structured content was provided`);let n=Eo(e.outputSchema),o=await mf(n,r.structuredContent);if(!o.success){let s="error"in o?o.error:"Unknown error",a=hf(s);throw new U(V.InvalidParams,`Output validation error: Invalid structured content for tool ${i}: ${a}`)}}async executeToolHandler(e,r,i){let n=e.handler;if("createTask"in n){if(!i.taskStore)throw new Error("No task store provided.");let s={...i,taskStore:i.taskStore};if(e.inputSchema){let a=n;return await Promise.resolve(a.createTask(r,s))}else{let a=n;return await Promise.resolve(a.createTask(s))}}if(e.inputSchema){let s=n;return await Promise.resolve(s(r,i))}else{let s=n;return await Promise.resolve(s(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,s={...i,taskStore:i.taskStore},a=n?await Promise.resolve(o.createTask(n,s)):await Promise.resolve(o.createTask(s)),c=a.task.taskId,u=a.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 U(V.InternalError,`Task ${c} not found during polling`);u=d}return await i.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Vn(pp)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(pp,async e=>{switch(e.params.ref.type){case"ref/prompt":return VP(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return FP(e),this.handleResourceCompletion(e,e.params.ref);default:throw new U(V.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let i=this._registeredPrompts[r.name];if(!i)throw new U(V.InvalidParams,`Prompt ${r.name} not found`);if(!i.enabled)throw new U(V.InvalidParams,`Prompt ${r.name} disabled`);if(!i.argsSchema)return ou;let o=kn(i.argsSchema)?.[e.params.argument.name];if(!Nw(o))return ou;let s=TN(o);if(!s)return ou;let a=await s(e.params.argument.value,e.params.context);return NN(a)}async handleResourceCompletion(e,r){let i=Object.values(this._registeredResourceTemplates).find(s=>s.resourceTemplate.uriTemplate.toString()===r.uri);if(!i){if(this._registeredResources[r.uri])return ou;throw new U(V.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let n=i.resourceTemplate.completeCallback(e.params.argument.name);if(!n)return ou;let o=await n(e.params.argument.value,e.params.context);return NN(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Vn(sp)),this.server.assertCanSetRequestHandler(Vn(ap)),this.server.assertCanSetRequestHandler(Vn(cp)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(sp,async(e,r)=>{let i=Object.entries(this._registeredResources).filter(([o,s])=>s.enabled).map(([o,s])=>({uri:o,name:s.name,...s.metadata})),n=[];for(let o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;let s=await o.resourceTemplate.listCallback(r);for(let a of s.resources)n.push({...o.metadata,...a})}return{resources:[...i,...n]}}),this.server.setRequestHandler(ap,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,i])=>({name:r,uriTemplate:i.resourceTemplate.uriTemplate.toString(),...i.metadata}))})),this.server.setRequestHandler(cp,async(e,r)=>{let i=new URL(e.params.uri),n=this._registeredResources[i.toString()];if(n){if(!n.enabled)throw new U(V.InvalidParams,`Resource ${i} disabled`);return n.readCallback(i,r)}for(let o of Object.values(this._registeredResourceTemplates)){let s=o.resourceTemplate.uriTemplate.match(i.toString());if(s)return o.readCallback(i,s,r)}throw new U(V.InvalidParams,`Resource ${i} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Vn(up)),this.server.assertCanSetRequestHandler(Vn(lp)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(up,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?kJ(r.argsSchema):void 0}))})),this.server.setRequestHandler(lp,async(e,r)=>{let i=this._registeredPrompts[e.params.name];if(!i)throw new U(V.InvalidParams,`Prompt ${e.params.name} not found`);if(!i.enabled)throw new U(V.InvalidParams,`Prompt ${e.params.name} disabled`);if(i.argsSchema){let n=Eo(i.argsSchema),o=await mf(n,e.params.arguments);if(!o.success){let c="error"in o?o.error:"Unknown error",u=hf(c);throw new U(V.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let s=o.data,a=i.callback;return await Promise.resolve(a(s,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 s=this._createRegisteredResource(e,void 0,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,void 0,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}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 s={name:e,title:r,metadata:n,readCallback:o,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==i&&(delete this._registeredResources[i],a.uri&&(this._registeredResources[a.uri]=s)),typeof a.name<"u"&&(s.name=a.name),typeof a.title<"u"&&(s.title=a.title),typeof a.metadata<"u"&&(s.metadata=a.metadata),typeof a.callback<"u"&&(s.readCallback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[i]=s,s}_createRegisteredResourceTemplate(e,r,i,n,o){let s={resourceTemplate:i,title:r,metadata:n,readCallback:o,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=s)),typeof u.title<"u"&&(s.title=u.title),typeof u.template<"u"&&(s.resourceTemplate=u.template),typeof u.metadata<"u"&&(s.metadata=u.metadata),typeof u.callback<"u"&&(s.readCallback=u.callback),typeof u.enabled<"u"&&(s.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=s;let a=i.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!i.completeCallback(u))&&this.setCompletionRequestHandler(),s}_createRegisteredPrompt(e,r,i,n,o){let s={title:r,description:i,argsSchema:n===void 0?void 0:$i(n),callback:o,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=s)),typeof a.title<"u"&&(s.title=a.title),typeof a.description<"u"&&(s.description=a.description),typeof a.argsSchema<"u"&&(s.argsSchema=$i(a.argsSchema)),typeof a.callback<"u"&&(s.callback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=s,n&&Object.values(n).some(c=>{let u=c instanceof Ao?c._def?.innerType:c;return Nw(u)})&&this.setCompletionRequestHandler(),s}_createRegisteredTool(e,r,i,n,o,s,a,c,u){jw(e);let l={title:r,description:i,inputSchema:ON(n),outputSchema:ON(o),annotations:s,execution:a,_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"&&jw(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=$i(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=$i(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,s;if(typeof r[0]=="string"&&(i=r.shift()),r.length>1){let c=r[0];if(Rw(c))n=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Rw(r[0])&&(s=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`);s=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,i,n,o,s,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,i){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:n,description:o,inputSchema:s,outputSchema:a,annotations:c,_meta:u}=r;return this._createRegisteredTool(e,n,o,s,a,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],s=this._createRegisteredPrompt(e,void 0,i,n,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}registerPrompt(e,r,i){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:n,description:o,argsSchema:s}=r,a=this._createRegisteredPrompt(e,n,o,s,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}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 wJ={type:"object",properties:{}};function jN(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function RN(t){return"_def"in t||"_zod"in t||jN(t)}function Rw(t){return typeof t!="object"||t===null||RN(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(jN)}function ON(t){if(t){if(Rw(t))return $i(t);if(!RN(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function kJ(t){let e=kn(t);return e?Object.entries(e).map(([r,i])=>{let n=mx(i),o=hx(i);return{name:r,description:n,required:!o}}):[]}function Vn(t){let r=kn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let i=gf(r);if(typeof i=="string")return i;throw new Error("Schema method literal must be a string")}function NN(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var ou={completion:{values:[],hasMore:!1}};import AN from"node:process";var Cm=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
199
199
|
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),SJ(r)}clear(){this._buffer=void 0}};function SJ(t){return CP.parse(JSON.parse(t))}function CN(t){return JSON.stringify(t)+`
|
|
200
|
-
`}var Am=class{constructor(e=AN.stdin,r=AN.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Cm,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=CN(e);this._stdout.write(i)?r():this._stdout.once("drain",r)})}};var MR=Ch(SR(),1);import{existsSync as n5,readFileSync as i5}from"node:fs";var Vt=class extends Error{constructor(r,i,n){super(r);this.status=i;this.name="CliError",this.code=n?.code,this.details=n?.details}code;details};function ei(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 xR(t){let e=null;async function r(){let s=await fetch(`${t.apiUrl}/auth/cli/exchange`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"}});if(!s.ok){let c=(await s.json().catch(()=>null))?.error;throw new Vt(c?.message??s.statusText,s.status,{code:c?.code,details:c?.details})}return e=await s.json(),e}async function i(){if(!t.token.startsWith("mk_"))return t.token;let s=e?Date.parse(e.expiresAt):0;return(!e||s-Date.now()<6e4)&&await r(),e.accessToken}async function n(s,a,c){let u=await i(),l=await fetch(`${t.apiUrl}${a}`,{method:s,headers:{Authorization:`Bearer ${u}`,"Content-Type":"application/json"},body:c?JSON.stringify(c):void 0});if(!l.ok){let d=await l.json().catch(()=>null),f=d&&typeof d=="object"&&d.error,p=l.statusText,h,m;if(typeof f=="string")p=f;else if(f&&typeof f=="object")p=f.message??p,h=f.code,m=f.details;else if(d&&typeof d=="object"&&Array.isArray(d.errors)){let v=d.errors?.[0];v&&typeof v=="object"&&"message"in v&&(p=String(v.message)),m=d}throw new Vt(p,l.status,{code:h,details:m})}if(l.status!==204)return l.json()}async function o(s,a){let c=await i(),u=await fetch(`${t.apiUrl}${a}`,{method:s,headers:{Authorization:`Bearer ${c}`}});if(!u.ok)throw new Vt(u.statusText,u.status);return u.text()}return{exchangeCliToken:r,bootstrap:()=>n("POST","/builder/context/bootstrap"),listProducts:()=>n("GET","/products"),createProduct:s=>n("POST","/products",s),initProduct:s=>n("POST","/products/init",s),updateProduct:(s,a,c)=>n("PATCH",ei(`/products/${s}`,{env:c?.env}),a),createPlan:(s,a,c)=>n("POST",ei(`/products/${s}/plans`,{env:c?.env}),a),updatePlan:(s,a,c,u)=>n("PATCH",ei(`/products/${s}/plans/${a}`,{env:u?.env}),c),deletePlan:(s,a,c)=>n("DELETE",ei(`/products/${s}/plans/${a}`,{env:c?.env})),getProduct:(s,a)=>n("GET",ei(`/products/${s}`,{env:a?.env})),listEnvironments:s=>n("GET",`/products/${s}/environments`),createEnvironment:(s,a)=>n("POST",`/products/${s}/environments`,a),deleteEnvironment:(s,a)=>n("DELETE",`/products/${s}/environments/${encodeURIComponent(a)}`),deleteProduct:s=>n("DELETE",`/products/${s}`),managementListPlans:s=>n("GET",`/management/products/${s}/plans`),managementGetUsage:s=>n("GET",`/management/products/${s}/usage`),managementListMakerTokens:()=>n("GET","/maker-tokens"),managementCreateMakerToken:s=>n("POST","/maker-tokens",s),managementRevokeMakerToken:s=>n("DELETE",`/maker-tokens/${s}`),builderGitHubStatus:()=>n("GET","/builder/github/status"),productStripeStatus:s=>n("GET",`/products/${s}/stripe/status`),issuePersonaBootstrapKey:async(s,a,c)=>{let u=await fetch(`${t.apiUrl}/portal/products/${s}/environments/${a}/test/bootstrap-key`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify(c??{})});if(!u.ok){let d=(await u.json().catch(()=>null))?.error;throw new Vt(d?.message??u.statusText,u.status,{code:d?.code,details:d?.details})}return u.json()},listPersonas:async(s,a)=>{let c=await fetch(`${t.apiUrl}/portal/products/${s}/environments/${a}/test/personas`,{method:"GET",headers:{Authorization:`Bearer ${t.token}`}});if(!c.ok){let l=(await c.json().catch(()=>null))?.error;throw new Vt(l?.message??c.statusText,c.status,{code:l?.code,details:l?.details})}return c.json()},rotatePersona:async(s,a,c)=>{let u=await fetch(`${t.apiUrl}/portal/products/${s}/environments/${a}/test/personas/${c}/rotate`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"}});if(!u.ok){let d=(await u.json().catch(()=>null))?.error;throw new Vt(d?.message??u.statusText,u.status,{code:d?.code,details:d?.details})}return u.json()},revokePersona:async(s,a,c)=>{let u=await fetch(`${t.apiUrl}/portal/products/${s}/environments/${a}/test/personas/${c}`,{method:"DELETE",headers:{Authorization:`Bearer ${t.token}`}});if(!u.ok){let d=(await u.json().catch(()=>null))?.error;throw new Vt(d?.message??u.statusText,u.status,{code:d?.code,details:d?.details})}return u.json()},exchangePersonaSession:async s=>{let a=await fetch(`${t.apiUrl}/portal/auth/persona-session`,{method:"POST",headers:{"Content-Type":"application/json","X-Portal-Host":s.portalHost},body:JSON.stringify({apiKey:s.apiKey})});if(!a.ok){let u=(await a.json().catch(()=>null))?.error;throw new Vt(u?.message??a.statusText,a.status,{code:u?.code,details:u?.details})}return a.json()},getProductConfig:(s,a)=>n("GET",ei(`/products/${s}/config`,{format:"json",env:a?.env,state:a?.state})),getProductConfigYaml:(s,a)=>o("GET",ei(`/products/${s}/config`,{format:"yaml",env:a?.env,state:a?.state})),getProductAttempts:(s,a)=>n("GET",ei(`/products/${s}/config-attempts`,{env:a?.env})),updateProductConfigDraft:(s,a,c)=>n("PATCH",`/products/${s}/config/draft`,{spec:a,dryRun:c?.dryRun===!0,env:c?.env,branch:c?.branch,source:c?.source,baseDraftHash:c?.baseDraftHash}),updateProductConfig:(s,a,c)=>n("PATCH",`/products/${s}/config/draft`,{spec:a,dryRun:c?.dryRun===!0,env:c?.env,branch:c?.branch,source:c?.source,baseDraftHash:c?.baseDraftHash}),validateProductConfigDraft:(s,a)=>n("POST",`/products/${s}/config/draft/validate`,{env:a?.env}),previewProductConfigDraft:(s,a)=>n("POST",`/products/${s}/config/draft/preview`,{env:a?.env}),resetProductConfigDraft:(s,a)=>n("DELETE",`/products/${s}/config/draft`,{env:a?.env}),applyProductConfig:(s,a)=>n("POST",`/products/${s}/config/apply`,{spec:a?.spec,dryRun:a?.dryRun===!0,env:a?.env,branch:a?.branch,source:a?.source,draftHash:a?.draftHash}),compileProduct:(s,a)=>n("POST",`/products/${s}/compile`,hS(a)),managementCompileSelf:s=>n("POST","/management/compile",hS(s)),managementCompile:(s,a)=>n("POST",`/management/products/${s}/compile`,hS(a)),managementListProducts:async()=>{let s=await n("GET","/management/products");return Array.isArray(s)?s:s.data},isMakerToken:()=>t.token.startsWith("mk_")}}function hS(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 yS,mkdirSync as X3,readFileSync as zR,writeFileSync as loe}from"node:fs";import{homedir as Q3}from"node:os";import{join as vS}from"node:path";var PR="https://core.farthershore.com";var _S=vS(Q3(),".farthershore"),IR=vS(_S,"config.json"),ER=vS(_S,"credentials.json");function e5(t){yS(t)||X3(t,{recursive:!0,mode:448})}var gS={apiUrl:PR,defaultFormat:"table"};function Du(){if(e5(_S),!yS(IR))return gS;try{let t=JSON.parse(zR(IR,"utf-8"));return{...gS,...t}}catch{return gS}}function TR(){if(!yS(ER))return null;try{return JSON.parse(zR(ER,"utf-8"))}catch{return null}}function OR(t){if(t)return t;let e=process.env.FARTHERSHORE_TOKEN;if(e)return e;let r=TR();if(r?.token)return r.token;throw new Vt("Not authenticated. Run `farthershore set-key` or set FARTHERSHORE_TOKEN environment variable.")}var r5=new Set(["production","prod","main"]);async function NR(t,e){let r=Du();if(e){if(e.length===36)return e;let n=(await t.listProducts()).find(o=>o.id===e||o.name.toLowerCase()===e.toLowerCase());if(n)return n.id}if(r.activeProductId)return r.activeProductId;throw new Error("No product selected. Pass --product <id-or-name> or run `farthershore product create` first.")}function $S(t){let e=t?.trim();if(e)return r5.has(e.toLowerCase())?null:e}function jR(t,e){let r=$S(e);if(r!==void 0)return{name:r,production:r===null};let i=$S(process.env.FARTHERSHORE_ENV);if(i!==void 0)return{name:i,production:i===null};let o=Du().activeEnvironmentsByProductId?.[t],s=$S(o);return s!==void 0?{name:s,production:s===null}:{name:null,production:!0}}function RR(t){return t.production?void 0:t.name??void 0}function CR(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function AR(){let t=Du(),e=OR(void 0),r=process.env.FARTHERSHORE_API_URL??t.apiUrl;return xR({apiUrl:r,token:e})}async function DR(t,e,r){let i=await NR(t,e),n=jR(i,r);return{productId:i,environment:n,env:RR(n)}}var qR={product:xn.string().optional(),env:xn.string().optional()};function o5(){let t=new Rm({name:"farthershore-agent-product-builder",version:"0.1.0"});return t.tool("farthershore_draft_validate",qR,async({product:e,env:r})=>{let i=AR(),n=await DR(i,e,r);return CR({ok:!0,...n,result:await i.validateProductConfigDraft(n.productId,{env:n.env})})}),t.tool("farthershore_apply",{...qR,toFile:xn.string().optional(),dryRun:xn.boolean().default(!0)},async({product:e,env:r,toFile:i,dryRun:n})=>{let o=AR(),s=await DR(o,e,r),a=i&&n5(i)?MR.default.parse(i5(i,"utf-8")):void 0;return CR({ok:!0,...s,result:await o.applyProductConfig(s.productId,{spec:a,env:s.env,dryRun:n,source:"MCP"})})}),t}async function s5(){let t=o5(),e=new Am;await t.connect(e)}import.meta.url===`file://${process.argv[1]}`&&s5();export{o5 as createMcpServer};
|
|
200
|
+
`}var Am=class{constructor(e=AN.stdin,r=AN.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Cm,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=CN(e);this._stdout.write(i)?r():this._stdout.once("drain",r)})}};var MR=Ch(SR(),1);import{existsSync as n5,readFileSync as i5}from"node:fs";var Vt=class extends Error{constructor(r,i,n){super(r);this.status=i;this.name="CliError",this.code=n?.code,this.details=n?.details}code;details};function ei(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 xR(t){let e=null;async function r(){let s=await fetch(`${t.apiUrl}/auth/cli/exchange`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"}});if(!s.ok){let c=(await s.json().catch(()=>null))?.error;throw new Vt(c?.message??s.statusText,s.status,{code:c?.code,details:c?.details})}return e=await s.json(),e}async function i(){if(!t.token.startsWith("mk_"))return t.token;let s=e?Date.parse(e.expiresAt):0;return(!e||s-Date.now()<6e4)&&await r(),e.accessToken}async function n(s,a,c){let u=await i(),l=await fetch(`${t.apiUrl}${a}`,{method:s,headers:{Authorization:`Bearer ${u}`,"Content-Type":"application/json"},body:c?JSON.stringify(c):void 0});if(!l.ok){let d=await l.json().catch(()=>null),f=d&&typeof d=="object"&&d.error,p=l.statusText,h,m;if(typeof f=="string")p=f;else if(f&&typeof f=="object")p=f.message??p,h=f.code,m=f.details;else if(d&&typeof d=="object"&&Array.isArray(d.errors)){let v=d.errors?.[0];v&&typeof v=="object"&&"message"in v&&(p=String(v.message)),m=d}throw new Vt(p,l.status,{code:h,details:m})}if(l.status!==204)return l.json()}async function o(s,a){let c=await i(),u=await fetch(`${t.apiUrl}${a}`,{method:s,headers:{Authorization:`Bearer ${c}`}});if(!u.ok)throw new Vt(u.statusText,u.status);return u.text()}return{exchangeCliToken:r,bootstrap:()=>n("POST","/builder/context/bootstrap"),listProducts:()=>n("GET","/products"),createProduct:s=>n("POST","/products",s),initProduct:s=>n("POST","/products/init",s),updateProduct:(s,a,c)=>n("PATCH",ei(`/products/${s}`,{env:c?.env}),a),createPlan:(s,a,c)=>n("POST",ei(`/products/${s}/plans`,{env:c?.env}),a),updatePlan:(s,a,c,u)=>n("PATCH",ei(`/products/${s}/plans/${a}`,{env:u?.env}),c),deletePlan:(s,a,c)=>n("DELETE",ei(`/products/${s}/plans/${a}`,{env:c?.env})),getProduct:(s,a)=>n("GET",ei(`/products/${s}`,{env:a?.env})),listEnvironments:s=>n("GET",`/products/${s}/environments`),createEnvironment:(s,a)=>n("POST",`/products/${s}/environments`,a),deleteEnvironment:(s,a)=>n("DELETE",`/products/${s}/environments/${encodeURIComponent(a)}`),deleteProduct:s=>n("DELETE",`/products/${s}`),managementListPlans:s=>n("GET",`/management/products/${s}/plans`),managementGetUsage:s=>n("GET",`/management/products/${s}/usage`),managementListMakerTokens:()=>n("GET","/maker-tokens"),managementCreateMakerToken:s=>n("POST","/maker-tokens",s),managementRevokeMakerToken:s=>n("DELETE",`/maker-tokens/${s}`),builderGitHubStatus:()=>n("GET","/builder/github/status"),productStripeStatus:s=>n("GET",`/products/${s}/stripe/status`),issuePersonaBootstrapKey:async(s,a,c)=>{let u=await fetch(`${t.apiUrl}/portal/products/${s}/environments/${a}/test/bootstrap-key`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify(c??{})});if(!u.ok){let d=(await u.json().catch(()=>null))?.error;throw new Vt(d?.message??u.statusText,u.status,{code:d?.code,details:d?.details})}return u.json()},listPersonas:async(s,a)=>{let c=await fetch(`${t.apiUrl}/portal/products/${s}/environments/${a}/test/personas`,{method:"GET",headers:{Authorization:`Bearer ${t.token}`}});if(!c.ok){let l=(await c.json().catch(()=>null))?.error;throw new Vt(l?.message??c.statusText,c.status,{code:l?.code,details:l?.details})}return c.json()},rotatePersona:async(s,a,c)=>{let u=await fetch(`${t.apiUrl}/portal/products/${s}/environments/${a}/test/personas/${c}/rotate`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"}});if(!u.ok){let d=(await u.json().catch(()=>null))?.error;throw new Vt(d?.message??u.statusText,u.status,{code:d?.code,details:d?.details})}return u.json()},revokePersona:async(s,a,c)=>{let u=await fetch(`${t.apiUrl}/portal/products/${s}/environments/${a}/test/personas/${c}`,{method:"DELETE",headers:{Authorization:`Bearer ${t.token}`}});if(!u.ok){let d=(await u.json().catch(()=>null))?.error;throw new Vt(d?.message??u.statusText,u.status,{code:d?.code,details:d?.details})}return u.json()},exchangePersonaSession:async s=>{let a=await fetch(`${t.apiUrl}/portal/auth/persona-session`,{method:"POST",headers:{"Content-Type":"application/json","X-Portal-Host":s.portalHost},body:JSON.stringify({apiKey:s.apiKey})});if(!a.ok){let u=(await a.json().catch(()=>null))?.error;throw new Vt(u?.message??a.statusText,a.status,{code:u?.code,details:u?.details})}return a.json()},getProductConfig:(s,a)=>n("GET",ei(`/products/${s}/config`,{format:"json",env:a?.env,state:a?.state})),getProductConfigYaml:(s,a)=>o("GET",ei(`/products/${s}/config`,{format:"yaml",env:a?.env,state:a?.state})),getProductAttempts:(s,a)=>n("GET",ei(`/products/${s}/config-attempts`,{env:a?.env})),updateProductConfigDraft:(s,a,c)=>n("PATCH",`/products/${s}/config/draft`,{spec:a,dryRun:c?.dryRun===!0,env:c?.env,branch:c?.branch,source:c?.source,baseDraftHash:c?.baseDraftHash}),updateProductConfig:(s,a,c)=>n("PATCH",`/products/${s}/config/draft`,{spec:a,dryRun:c?.dryRun===!0,env:c?.env,branch:c?.branch,source:c?.source,baseDraftHash:c?.baseDraftHash}),validateProductConfigDraft:(s,a)=>n("POST",`/products/${s}/config/draft/validate`,{env:a?.env}),previewProductConfigDraft:(s,a)=>n("POST",`/products/${s}/config/draft/preview`,{env:a?.env}),resetProductConfigDraft:(s,a)=>n("DELETE",`/products/${s}/config/draft`,{env:a?.env}),applyProductConfig:(s,a)=>n("POST",`/products/${s}/config/apply`,{spec:a?.spec,dryRun:a?.dryRun===!0,env:a?.env,branch:a?.branch,source:a?.source,draftHash:a?.draftHash}),compileProduct:(s,a)=>n("POST",`/products/${s}/compile`,hS(a)),managementCompileSelf:s=>n("POST","/management/compile",hS(s)),managementCompile:(s,a)=>n("POST",`/management/products/${s}/compile`,hS(a)),validateManagedRepo:(s,a)=>n("POST",`/management/products/${s}/repo/validate`,{files:a.files,branch:a.branch}),managementListProducts:async()=>{let s=await n("GET","/management/products");return Array.isArray(s)?s:s.data},isMakerToken:()=>t.token.startsWith("mk_")}}function hS(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 yS,mkdirSync as X3,readFileSync as zR,writeFileSync as loe}from"node:fs";import{homedir as Q3}from"node:os";import{join as vS}from"node:path";var PR="https://core.farthershore.com";var _S=vS(Q3(),".farthershore"),IR=vS(_S,"config.json"),ER=vS(_S,"credentials.json");function e5(t){yS(t)||X3(t,{recursive:!0,mode:448})}var gS={apiUrl:PR,defaultFormat:"table"};function Du(){if(e5(_S),!yS(IR))return gS;try{let t=JSON.parse(zR(IR,"utf-8"));return{...gS,...t}}catch{return gS}}function TR(){if(!yS(ER))return null;try{return JSON.parse(zR(ER,"utf-8"))}catch{return null}}function OR(t){if(t)return t;let e=process.env.FARTHERSHORE_TOKEN;if(e)return e;let r=TR();if(r?.token)return r.token;throw new Vt("Not authenticated. Run `farthershore set-key` or set FARTHERSHORE_TOKEN environment variable.")}var r5=new Set(["production","prod","main"]);async function NR(t,e){let r=Du();if(e){if(e.length===36)return e;let n=(await t.listProducts()).find(o=>o.id===e||o.name.toLowerCase()===e.toLowerCase());if(n)return n.id}if(r.activeProductId)return r.activeProductId;throw new Error("No product selected. Pass --product <id-or-name> or run `farthershore product create` first.")}function $S(t){let e=t?.trim();if(e)return r5.has(e.toLowerCase())?null:e}function jR(t,e){let r=$S(e);if(r!==void 0)return{name:r,production:r===null};let i=$S(process.env.FARTHERSHORE_ENV);if(i!==void 0)return{name:i,production:i===null};let o=Du().activeEnvironmentsByProductId?.[t],s=$S(o);return s!==void 0?{name:s,production:s===null}:{name:null,production:!0}}function RR(t){return t.production?void 0:t.name??void 0}function CR(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function AR(){let t=Du(),e=OR(void 0),r=process.env.FARTHERSHORE_API_URL??t.apiUrl;return xR({apiUrl:r,token:e})}async function DR(t,e,r){let i=await NR(t,e),n=jR(i,r);return{productId:i,environment:n,env:RR(n)}}var qR={product:xn.string().optional(),env:xn.string().optional()};function o5(){let t=new Rm({name:"farthershore-agent-product-builder",version:"0.1.0"});return t.tool("farthershore_draft_validate",qR,async({product:e,env:r})=>{let i=AR(),n=await DR(i,e,r);return CR({ok:!0,...n,result:await i.validateProductConfigDraft(n.productId,{env:n.env})})}),t.tool("farthershore_apply",{...qR,toFile:xn.string().optional(),dryRun:xn.boolean().default(!0)},async({product:e,env:r,toFile:i,dryRun:n})=>{let o=AR(),s=await DR(o,e,r),a=i&&n5(i)?MR.default.parse(i5(i,"utf-8")):void 0;return CR({ok:!0,...s,result:await o.applyProductConfig(s.productId,{spec:a,env:s.env,dryRun:n,source:"MCP"})})}),t}async function s5(){let t=o5(),e=new Am;await t.connect(e)}import.meta.url===`file://${process.argv[1]}`&&s5();export{o5 as createMcpServer};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@farthershore/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "FartherShore CLI — create and configure API products",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -43,7 +43,7 @@
|
|
|
43
43
|
"author": "Farther Shore",
|
|
44
44
|
"license": "MIT",
|
|
45
45
|
"devDependencies": {
|
|
46
|
-
"@farther-shore/shared-types": "^0.
|
|
46
|
+
"@farther-shore/shared-types": "^0.39.0",
|
|
47
47
|
"@modelcontextprotocol/sdk": "^1.18.0",
|
|
48
48
|
"@types/node": "^22.19.17",
|
|
49
49
|
"chalk": "^5.4.1",
|