trueline-mcp 2.5.1 → 2.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/server.js +2 -2
- package/package.json +1 -1
- package/scripts/resolve-binary.cjs +32 -0
package/dist/server.js
CHANGED
|
@@ -42,7 +42,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
42
42
|
`:`[${J[z]}\r
|
|
43
43
|
]`;continue}if(Y+=J[z],J[z]==="\\")G=!0;else if(W&&J[z]==="]")W=!1;else if(!W&&J[z]==="[")W=!0}try{new RegExp(Y)}catch{return console.warn(`Could not convert regex pattern at ${X.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),Q.source}return Y}function SX(Q,X){if(X.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if(X.target==="openApi3"&&Q.keyType?._def.typeName===S.ZodEnum)return{type:"object",required:Q.keyType._def.values,properties:Q.keyType._def.values.reduce((J,Y)=>({...J,[Y]:c(Q.valueType._def,{...X,currentPath:[...X.currentPath,"properties",Y]})??S0(X)}),{}),additionalProperties:X.rejectedAdditionalProperties};let $={type:"object",additionalProperties:c(Q.valueType._def,{...X,currentPath:[...X.currentPath,"additionalProperties"]})??X.allowedAdditionalProperties};if(X.target==="openApi3")return $;if(Q.keyType?._def.typeName===S.ZodString&&Q.keyType._def.checks?.length){let{type:J,...Y}=MX(Q.keyType._def,X);return{...$,propertyNames:Y}}else if(Q.keyType?._def.typeName===S.ZodEnum)return{...$,propertyNames:{enum:Q.keyType._def.values}};else if(Q.keyType?._def.typeName===S.ZodBranded&&Q.keyType._def.type._def.typeName===S.ZodString&&Q.keyType._def.type._def.checks?.length){let{type:J,...Y}=EX(Q.keyType._def,X);return{...$,propertyNames:Y}}return $}function YW(Q,X){if(X.mapStrategy==="record")return SX(Q,X);let $=c(Q.keyType._def,{...X,currentPath:[...X.currentPath,"items","items","0"]})||S0(X),J=c(Q.valueType._def,{...X,currentPath:[...X.currentPath,"items","items","1"]})||S0(X);return{type:"array",maxItems:125,items:{type:"array",items:[$,J],minItems:2,maxItems:2}}}function GW(Q){let X=Q.values,J=Object.keys(Q.values).filter((G)=>{return typeof X[X[G]]!=="number"}).map((G)=>X[G]),Y=Array.from(new Set(J.map((G)=>typeof G)));return{type:Y.length===1?Y[0]==="string"?"string":"number":["string","number"],enum:J}}function WW(Q){return Q.target==="openAi"?void 0:{not:S0({...Q,currentPath:[...Q.currentPath,"not"]})}}function HW(Q){return Q.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Q8={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function KW(Q,X){if(X.target==="openApi3")return zW(Q,X);let $=Q.options instanceof Map?Array.from(Q.options.values()):Q.options;if($.every((J)=>(J._def.typeName in Q8)&&(!J._def.checks||!J._def.checks.length))){let J=$.reduce((Y,G)=>{let W=Q8[G._def.typeName];return W&&!Y.includes(W)?[...Y,W]:Y},[]);return{type:J.length>1?J:J[0]}}else if($.every((J)=>J._def.typeName==="ZodLiteral"&&!J.description)){let J=$.reduce((Y,G)=>{let W=typeof G._def.value;switch(W){case"string":case"number":case"boolean":return[...Y,W];case"bigint":return[...Y,"integer"];case"object":if(G._def.value===null)return[...Y,"null"];case"symbol":case"undefined":case"function":default:return Y}},[]);if(J.length===$.length){let Y=J.filter((G,W,H)=>H.indexOf(G)===W);return{type:Y.length>1?Y:Y[0],enum:$.reduce((G,W)=>{return G.includes(W._def.value)?G:[...G,W._def.value]},[])}}}else if($.every((J)=>J._def.typeName==="ZodEnum"))return{type:"string",enum:$.reduce((J,Y)=>[...J,...Y._def.values.filter((G)=>!J.includes(G))],[])};return zW(Q,X)}var zW=(Q,X)=>{let $=(Q.options instanceof Map?Array.from(Q.options.values()):Q.options).map((J,Y)=>c(J._def,{...X,currentPath:[...X.currentPath,"anyOf",`${Y}`]})).filter((J)=>!!J&&(!X.strictUnions||typeof J==="object"&&Object.keys(J).length>0));return $.length?{anyOf:$}:void 0};function qW(Q,X){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(Q.innerType._def.typeName)&&(!Q.innerType._def.checks||!Q.innerType._def.checks.length)){if(X.target==="openApi3")return{type:Q8[Q.innerType._def.typeName],nullable:!0};return{type:[Q8[Q.innerType._def.typeName],"null"]}}if(X.target==="openApi3"){let J=c(Q.innerType._def,{...X,currentPath:[...X.currentPath]});if(J&&"$ref"in J)return{allOf:[J],nullable:!0};return J&&{...J,nullable:!0}}let $=c(Q.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","0"]});return $&&{anyOf:[$,{type:"null"}]}}function BW(Q,X){let $={type:"number"};if(!Q.checks)return $;for(let J of Q.checks)switch(J.kind){case"int":$.type="integer",tJ($,"type",J.message,X);break;case"min":if(X.target==="jsonSchema7")if(J.inclusive)J0($,"minimum",J.value,J.message,X);else J0($,"exclusiveMinimum",J.value,J.message,X);else{if(!J.inclusive)$.exclusiveMinimum=!0;J0($,"minimum",J.value,J.message,X)}break;case"max":if(X.target==="jsonSchema7")if(J.inclusive)J0($,"maximum",J.value,J.message,X);else J0($,"exclusiveMaximum",J.value,J.message,X);else{if(!J.inclusive)$.exclusiveMaximum=!0;J0($,"maximum",J.value,J.message,X)}break;case"multipleOf":J0($,"multipleOf",J.value,J.message,X);break}return $}function VW(Q,X){let $=X.target==="openAi",J={type:"object",properties:{}},Y=[],G=Q.shape();for(let H in G){let z=G[H];if(z===void 0||z._def===void 0)continue;let K=sA(z);if(K&&$){if(z._def.typeName==="ZodOptional")z=z._def.innerType;if(!z.isNullable())z=z.nullable();K=!1}let q=c(z._def,{...X,currentPath:[...X.currentPath,"properties",H],propertyPath:[...X.currentPath,"properties",H]});if(q===void 0)continue;if(J.properties[H]=q,!K)Y.push(H)}if(Y.length)J.required=Y;let W=aA(Q,X);if(W!==void 0)J.additionalProperties=W;return J}function aA(Q,X){if(Q.catchall._def.typeName!=="ZodNever")return c(Q.catchall._def,{...X,currentPath:[...X.currentPath,"additionalProperties"]});switch(Q.unknownKeys){case"passthrough":return X.allowedAdditionalProperties;case"strict":return X.rejectedAdditionalProperties;case"strip":return X.removeAdditionalStrategy==="strict"?X.allowedAdditionalProperties:X.rejectedAdditionalProperties}}function sA(Q){try{return Q.isOptional()}catch{return!0}}var UW=(Q,X)=>{if(X.currentPath.toString()===X.propertyPath?.toString())return c(Q.innerType._def,X);let $=c(Q.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","1"]});return $?{anyOf:[{not:S0(X)},$]}:S0(X)};var AW=(Q,X)=>{if(X.pipeStrategy==="input")return c(Q.in._def,X);else if(X.pipeStrategy==="output")return c(Q.out._def,X);let $=c(Q.in._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),J=c(Q.out._def,{...X,currentPath:[...X.currentPath,"allOf",$?"1":"0"]});return{allOf:[$,J].filter((Y)=>Y!==void 0)}};function DW(Q,X){return c(Q.type._def,X)}function FW(Q,X){let J={type:"array",uniqueItems:!0,items:c(Q.valueType._def,{...X,currentPath:[...X.currentPath,"items"]})};if(Q.minSize)J0(J,"minItems",Q.minSize.value,Q.minSize.message,X);if(Q.maxSize)J0(J,"maxItems",Q.maxSize.value,Q.maxSize.message,X);return J}function OW(Q,X){if(Q.rest)return{type:"array",minItems:Q.items.length,items:Q.items.map(($,J)=>c($._def,{...X,currentPath:[...X.currentPath,"items",`${J}`]})).reduce(($,J)=>J===void 0?$:[...$,J],[]),additionalItems:c(Q.rest._def,{...X,currentPath:[...X.currentPath,"additionalItems"]})};else return{type:"array",minItems:Q.items.length,maxItems:Q.items.length,items:Q.items.map(($,J)=>c($._def,{...X,currentPath:[...X.currentPath,"items",`${J}`]})).reduce(($,J)=>J===void 0?$:[...$,J],[])}}function LW(Q){return{not:S0(Q)}}function wW(Q){return S0(Q)}var jW=(Q,X)=>{return c(Q.innerType._def,X)};var NW=(Q,X,$)=>{switch(X){case S.ZodString:return MX(Q,$);case S.ZodNumber:return BW(Q,$);case S.ZodObject:return VW(Q,$);case S.ZodBigInt:return rG(Q,$);case S.ZodBoolean:return tG();case S.ZodDate:return aJ(Q,$);case S.ZodUndefined:return LW($);case S.ZodNull:return HW($);case S.ZodArray:return oG(Q,$);case S.ZodUnion:case S.ZodDiscriminatedUnion:return KW(Q,$);case S.ZodIntersection:return XW(Q,$);case S.ZodTuple:return OW(Q,$);case S.ZodRecord:return SX(Q,$);case S.ZodLiteral:return $W(Q,$);case S.ZodEnum:return QW(Q);case S.ZodNativeEnum:return GW(Q);case S.ZodNullable:return qW(Q,$);case S.ZodOptional:return UW(Q,$);case S.ZodMap:return YW(Q,$);case S.ZodSet:return FW(Q,$);case S.ZodLazy:return()=>Q.getter()._def;case S.ZodPromise:return DW(Q,$);case S.ZodNaN:case S.ZodNever:return WW($);case S.ZodEffects:return eG(Q,$);case S.ZodAny:return S0($);case S.ZodUnknown:return wW($);case S.ZodDefault:return sG(Q,$);case S.ZodBranded:return EX(Q,$);case S.ZodReadonly:return jW(Q,$);case S.ZodCatch:return aG(Q,$);case S.ZodPipeline:return AW(Q,$);case S.ZodFunction:case S.ZodVoid:case S.ZodSymbol:return;default:return((J)=>{return})(X)}};function c(Q,X,$=!1){let J=X.seen.get(Q);if(X.override){let H=X.override?.(Q,X,J,$);if(H!==iG)return H}if(J&&!$){let H=eA(J,X);if(H!==void 0)return H}let Y={def:Q,path:X.currentPath,jsonSchema:void 0};X.seen.set(Q,Y);let G=NW(Q,Q.typeName,X),W=typeof G==="function"?c(G(),X):G;if(W)QD(Q,X,W);if(X.postProcess){let H=X.postProcess(W,Q,X);return Y.jsonSchema=W,H}return Y.jsonSchema=W,W}var eA=(Q,X)=>{switch(X.$refStrategy){case"root":return{$ref:Q.path.join("/")};case"relative":return{$ref:NX(X.currentPath,Q.path)};case"none":case"seen":{if(Q.path.length<X.currentPath.length&&Q.path.every(($,J)=>X.currentPath[J]===$))return console.warn(`Recursive reference detected at ${X.currentPath.join("/")}! Defaulting to any`),S0(X);return X.$refStrategy==="seen"?S0(X):void 0}}},QD=(Q,X,$)=>{if(Q.description){if($.description=Q.description,X.markdownDescription)$.markdownDescription=Q.description}return $};var Q7=(Q,X)=>{let $=dG(X),J=typeof X==="object"&&X.definitions?Object.entries(X.definitions).reduce((z,[K,q])=>({...z,[K]:c(q._def,{...$,currentPath:[...$.basePath,$.definitionPath,K]},!0)??S0($)}),{}):void 0,Y=typeof X==="string"?X:X?.nameStrategy==="title"?void 0:X?.name,G=c(Q._def,Y===void 0?$:{...$,currentPath:[...$.basePath,$.definitionPath,Y]},!1)??S0($),W=typeof X==="object"&&X.name!==void 0&&X.nameStrategy==="title"?X.name:void 0;if(W!==void 0)G.title=W;if($.flags.hasReferencedOpenAiAnyType){if(!J)J={};if(!J[$.openAiAnyTypeName])J[$.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:$.$refStrategy==="relative"?"1":[...$.basePath,$.definitionPath,$.openAiAnyTypeName].join("/")}}}let H=Y===void 0?J?{...G,[$.definitionPath]:J}:G:{$ref:[...$.$refStrategy==="relative"?[]:$.basePath,$.definitionPath,Y].join("/"),[$.definitionPath]:{...J,[Y]:G}};if($.target==="jsonSchema7")H.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="jsonSchema2019-09"||$.target==="openAi")H.$schema="https://json-schema.org/draft/2019-09/schema#";if($.target==="openAi"&&(("anyOf"in H)||("oneOf"in H)||("allOf"in H)||("type"in H)&&Array.isArray(H.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return H};function XD(Q){if(!Q)return"draft-7";if(Q==="jsonSchema7"||Q==="draft-7")return"draft-7";if(Q==="jsonSchema2019-09"||Q==="draft-2020-12")return"draft-2020-12";return"draft-7"}function X7(Q,X){if(z6(Q))return MJ(Q,{target:XD(X?.target),io:X?.pipeStrategy??"input"});return Q7(Q,{strictUnions:X?.strictUnions??!0,pipeStrategy:X?.pipeStrategy??"input"})}function $7(Q){let $=J9(Q)?.method;if(!$)throw Error("Schema is missing a method literal");let J=a8($);if(typeof J!=="string")throw Error("Schema method literal must be a string");return J}function J7(Q,X){let $=$9(Q,X);if(!$.success)throw $.error;return $.data}var $D=60000;class Y7{constructor(Q){if(this._options=Q,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(YX,(X)=>{this._oncancel(X)}),this.setNotificationHandler(WX,(X)=>{this._onprogress(X)}),this.setRequestHandler(GX,(X)=>({})),this._taskStore=Q?.taskStore,this._taskMessageQueue=Q?.taskMessageQueue,this._taskStore)this.setRequestHandler(HX,async(X,$)=>{let J=await this._taskStore.getTask(X.params.taskId,$.sessionId);if(!J)throw new x(h.InvalidParams,"Failed to retrieve task: Task not found");return{...J}}),this.setRequestHandler(KX,async(X,$)=>{let J=async()=>{let Y=X.params.taskId;if(this._taskMessageQueue){let W;while(W=await this._taskMessageQueue.dequeue(Y,$.sessionId)){if(W.type==="response"||W.type==="error"){let H=W.message,z=H.id,K=this._requestResolvers.get(z);if(K)if(this._requestResolvers.delete(z),W.type==="response")K(H);else{let q=H,V=new x(q.error.code,q.error.message,q.error.data);K(V)}else{let q=W.type==="response"?"Response":"Error";this._onerror(Error(`${q} handler missing for request ${z}`))}continue}await this._transport?.send(W.message,{relatedRequestId:$.requestId})}}let G=await this._taskStore.getTask(Y,$.sessionId);if(!G)throw new x(h.InvalidParams,`Task not found: ${Y}`);if(!G9(G.status))return await this._waitForTaskUpdate(Y,$.signal),await J();if(G9(G.status)){let W=await this._taskStore.getTaskResult(Y,$.sessionId);return this._clearTaskQueue(Y),{...W,_meta:{...W._meta,[Y9]:{taskId:Y}}}}return await J()};return await J()}),this.setRequestHandler(qX,async(X,$)=>{try{let{tasks:J,nextCursor:Y}=await this._taskStore.listTasks(X.params?.cursor,$.sessionId);return{tasks:J,nextCursor:Y,_meta:{}}}catch(J){throw new x(h.InvalidParams,`Failed to list tasks: ${J instanceof Error?J.message:String(J)}`)}}),this.setRequestHandler(VX,async(X,$)=>{try{let J=await this._taskStore.getTask(X.params.taskId,$.sessionId);if(!J)throw new x(h.InvalidParams,`Task not found: ${X.params.taskId}`);if(G9(J.status))throw new x(h.InvalidParams,`Cannot cancel task in terminal status: ${J.status}`);await this._taskStore.updateTaskStatus(X.params.taskId,"cancelled","Client cancelled task execution.",$.sessionId),this._clearTaskQueue(X.params.taskId);let Y=await this._taskStore.getTask(X.params.taskId,$.sessionId);if(!Y)throw new x(h.InvalidParams,`Task not found after cancellation: ${X.params.taskId}`);return{_meta:{},...Y}}catch(J){if(J instanceof x)throw J;throw new x(h.InvalidRequest,`Failed to cancel task: ${J instanceof Error?J.message:String(J)}`)}})}async _oncancel(Q){if(!Q.params.requestId)return;this._requestHandlerAbortControllers.get(Q.params.requestId)?.abort(Q.params.reason)}_setupTimeout(Q,X,$,J,Y=!1){this._timeoutInfo.set(Q,{timeoutId:setTimeout(J,X),startTime:Date.now(),timeout:X,maxTotalTimeout:$,resetTimeoutOnProgress:Y,onTimeout:J})}_resetTimeout(Q){let X=this._timeoutInfo.get(Q);if(!X)return!1;let $=Date.now()-X.startTime;if(X.maxTotalTimeout&&$>=X.maxTotalTimeout)throw this._timeoutInfo.delete(Q),x.fromError(h.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:X.maxTotalTimeout,totalElapsed:$});return clearTimeout(X.timeoutId),X.timeoutId=setTimeout(X.onTimeout,X.timeout),!0}_cleanupTimeout(Q){let X=this._timeoutInfo.get(Q);if(X)clearTimeout(X.timeoutId),this._timeoutInfo.delete(Q)}async connect(Q){if(this._transport)throw Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=Q;let X=this.transport?.onclose;this._transport.onclose=()=>{X?.(),this._onclose()};let $=this.transport?.onerror;this._transport.onerror=(Y)=>{$?.(Y),this._onerror(Y)};let J=this._transport?.onmessage;this._transport.onmessage=(Y,G)=>{if(J?.(Y,G),iQ(Y)||kG(Y))this._onresponse(Y);else if(gJ(Y))this._onrequest(Y,G);else if(TG(Y))this._onnotification(Y);else this._onerror(Error(`Unknown message type: ${JSON.stringify(Y)}`))},await this._transport.start()}_onclose(){let Q=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let $ of this._requestHandlerAbortControllers.values())$.abort();this._requestHandlerAbortControllers.clear();let X=x.fromError(h.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let $ of Q.values())$(X)}_onerror(Q){this.onerror?.(Q)}_onnotification(Q){let X=this._notificationHandlers.get(Q.method)??this.fallbackNotificationHandler;if(X===void 0)return;Promise.resolve().then(()=>X(Q)).catch(($)=>this._onerror(Error(`Uncaught error in notification handler: ${$}`)))}_onrequest(Q,X){let $=this._requestHandlers.get(Q.method)??this.fallbackRequestHandler,J=this._transport,Y=Q.params?._meta?.[Y9]?.taskId;if($===void 0){let K={jsonrpc:"2.0",id:Q.id,error:{code:h.MethodNotFound,message:"Method not found"}};if(Y&&this._taskMessageQueue)this._enqueueTaskMessage(Y,{type:"error",message:K,timestamp:Date.now()},J?.sessionId).catch((q)=>this._onerror(Error(`Failed to enqueue error response: ${q}`)));else J?.send(K).catch((q)=>this._onerror(Error(`Failed to send an error response: ${q}`)));return}let G=new AbortController;this._requestHandlerAbortControllers.set(Q.id,G);let W=IG(Q.params)?Q.params.task:void 0,H=this._taskStore?this.requestTaskStore(Q,J?.sessionId):void 0,z={signal:G.signal,sessionId:J?.sessionId,_meta:Q.params?._meta,sendNotification:async(K)=>{if(G.signal.aborted)return;let q={relatedRequestId:Q.id};if(Y)q.relatedTask={taskId:Y};await this.notification(K,q)},sendRequest:async(K,q,V)=>{if(G.signal.aborted)throw new x(h.ConnectionClosed,"Request was cancelled");let D={...V,relatedRequestId:Q.id};if(Y&&!D.relatedTask)D.relatedTask={taskId:Y};let U=D.relatedTask?.taskId??Y;if(U&&H)await H.updateTaskStatus(U,"input_required");return await this.request(K,q,D)},authInfo:X?.authInfo,requestId:Q.id,requestInfo:X?.requestInfo,taskId:Y,taskStore:H,taskRequestedTtl:W?.ttl,closeSSEStream:X?.closeSSEStream,closeStandaloneSSEStream:X?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(W)this.assertTaskHandlerCapability(Q.method)}).then(()=>$(Q,z)).then(async(K)=>{if(G.signal.aborted)return;let q={result:K,jsonrpc:"2.0",id:Q.id};if(Y&&this._taskMessageQueue)await this._enqueueTaskMessage(Y,{type:"response",message:q,timestamp:Date.now()},J?.sessionId);else await J?.send(q)},async(K)=>{if(G.signal.aborted)return;let q={jsonrpc:"2.0",id:Q.id,error:{code:Number.isSafeInteger(K.code)?K.code:h.InternalError,message:K.message??"Internal error",...K.data!==void 0&&{data:K.data}}};if(Y&&this._taskMessageQueue)await this._enqueueTaskMessage(Y,{type:"error",message:q,timestamp:Date.now()},J?.sessionId);else await J?.send(q)}).catch((K)=>this._onerror(Error(`Failed to send response: ${K}`))).finally(()=>{this._requestHandlerAbortControllers.delete(Q.id)})}_onprogress(Q){let{progressToken:X,...$}=Q.params,J=Number(X),Y=this._progressHandlers.get(J);if(!Y){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(Q)}`));return}let G=this._responseHandlers.get(J),W=this._timeoutInfo.get(J);if(W&&G&&W.resetTimeoutOnProgress)try{this._resetTimeout(J)}catch(H){this._responseHandlers.delete(J),this._progressHandlers.delete(J),this._cleanupTimeout(J),G(H);return}Y($)}_onresponse(Q){let X=Number(Q.id),$=this._requestResolvers.get(X);if($){if(this._requestResolvers.delete(X),iQ(Q))$(Q);else{let G=new x(Q.error.code,Q.error.message,Q.error.data);$(G)}return}let J=this._responseHandlers.get(X);if(J===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(Q)}`));return}this._responseHandlers.delete(X),this._cleanupTimeout(X);let Y=!1;if(iQ(Q)&&Q.result&&typeof Q.result==="object"){let G=Q.result;if(G.task&&typeof G.task==="object"){let W=G.task;if(typeof W.taskId==="string")Y=!0,this._taskProgressTokens.set(W.taskId,X)}}if(!Y)this._progressHandlers.delete(X);if(iQ(Q))J(Q);else{let G=x.fromError(Q.error.code,Q.error.message,Q.error.data);J(G)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(Q,X,$){let{task:J}=$??{};if(!J){try{yield{type:"result",result:await this.request(Q,X,$)}}catch(G){yield{type:"error",error:G instanceof x?G:new x(h.InternalError,String(G))}}return}let Y;try{let G=await this.request(Q,XQ,$);if(G.task)Y=G.task.taskId,yield{type:"taskCreated",task:G.task};else throw new x(h.InternalError,"Task creation did not return a task");while(!0){let W=await this.getTask({taskId:Y},$);if(yield{type:"taskStatus",task:W},G9(W.status)){if(W.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:Y},X,$)};else if(W.status==="failed")yield{type:"error",error:new x(h.InternalError,`Task ${Y} failed`)};else if(W.status==="cancelled")yield{type:"error",error:new x(h.InternalError,`Task ${Y} was cancelled`)};return}if(W.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:Y},X,$)};return}let H=W.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((z)=>setTimeout(z,H)),$?.signal?.throwIfAborted()}}catch(G){yield{type:"error",error:G instanceof x?G:new x(h.InternalError,String(G))}}}request(Q,X,$){let{relatedRequestId:J,resumptionToken:Y,onresumptiontoken:G,task:W,relatedTask:H}=$??{};return new Promise((z,K)=>{let q=(O)=>{K(O)};if(!this._transport){q(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(Q.method),W)this.assertTaskCapability(Q.method)}catch(O){q(O);return}$?.signal?.throwIfAborted();let V=this._requestMessageId++,D={...Q,jsonrpc:"2.0",id:V};if($?.onprogress)this._progressHandlers.set(V,$.onprogress),D.params={...Q.params,_meta:{...Q.params?._meta||{},progressToken:V}};if(W)D.params={...D.params,task:W};if(H)D.params={...D.params,_meta:{...D.params?._meta||{},[Y9]:H}};let U=(O)=>{this._responseHandlers.delete(V),this._progressHandlers.delete(V),this._cleanupTimeout(V),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:V,reason:String(O)}},{relatedRequestId:J,resumptionToken:Y,onresumptiontoken:G}).catch((E)=>this._onerror(Error(`Failed to send cancellation: ${E}`)));let w=O instanceof x?O:new x(h.RequestTimeout,String(O));K(w)};this._responseHandlers.set(V,(O)=>{if($?.signal?.aborted)return;if(O instanceof Error)return K(O);try{let w=$9(X,O.result);if(!w.success)K(w.error);else z(w.data)}catch(w){K(w)}}),$?.signal?.addEventListener("abort",()=>{U($?.signal?.reason)});let A=$?.timeout??$D,F=()=>U(x.fromError(h.RequestTimeout,"Request timed out",{timeout:A}));this._setupTimeout(V,A,$?.maxTotalTimeout,F,$?.resetTimeoutOnProgress??!1);let L=H?.taskId;if(L){let O=(w)=>{let E=this._responseHandlers.get(V);if(E)E(w);else this._onerror(Error(`Response handler missing for side-channeled request ${V}`))};this._requestResolvers.set(V,O),this._enqueueTaskMessage(L,{type:"request",message:D,timestamp:Date.now()}).catch((w)=>{this._cleanupTimeout(V),K(w)})}else this._transport.send(D,{relatedRequestId:J,resumptionToken:Y,onresumptiontoken:G}).catch((O)=>{this._cleanupTimeout(V),K(O)})})}async getTask(Q,X){return this.request({method:"tasks/get",params:Q},zX,X)}async getTaskResult(Q,X,$){return this.request({method:"tasks/result",params:Q},X,$)}async listTasks(Q,X){return this.request({method:"tasks/list",params:Q},BX,X)}async cancelTask(Q,X){return this.request({method:"tasks/cancel",params:Q},xG,X)}async notification(Q,X){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(Q.method);let $=X?.relatedTask?.taskId;if($){let W={...Q,jsonrpc:"2.0",params:{...Q.params,_meta:{...Q.params?._meta||{},[Y9]:X.relatedTask}}};await this._enqueueTaskMessage($,{type:"notification",message:W,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(Q.method)&&!Q.params&&!X?.relatedRequestId&&!X?.relatedTask){if(this._pendingDebouncedNotifications.has(Q.method))return;this._pendingDebouncedNotifications.add(Q.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(Q.method),!this._transport)return;let W={...Q,jsonrpc:"2.0"};if(X?.relatedTask)W={...W,params:{...W.params,_meta:{...W.params?._meta||{},[Y9]:X.relatedTask}}};this._transport?.send(W,X).catch((H)=>this._onerror(H))});return}let G={...Q,jsonrpc:"2.0"};if(X?.relatedTask)G={...G,params:{...G.params,_meta:{...G.params?._meta||{},[Y9]:X.relatedTask}}};await this._transport.send(G,X)}setRequestHandler(Q,X){let $=$7(Q);this.assertRequestHandlerCapability($),this._requestHandlers.set($,(J,Y)=>{let G=J7(Q,J);return Promise.resolve(X(G,Y))})}removeRequestHandler(Q){this._requestHandlers.delete(Q)}assertCanSetRequestHandler(Q){if(this._requestHandlers.has(Q))throw Error(`A request handler for ${Q} already exists, which would be overridden`)}setNotificationHandler(Q,X){let $=$7(Q);this._notificationHandlers.set($,(J)=>{let Y=J7(Q,J);return Promise.resolve(X(Y))})}removeNotificationHandler(Q){this._notificationHandlers.delete(Q)}_cleanupTaskProgressHandler(Q){let X=this._taskProgressTokens.get(Q);if(X!==void 0)this._progressHandlers.delete(X),this._taskProgressTokens.delete(Q)}async _enqueueTaskMessage(Q,X,$){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let J=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(Q,X,$,J)}async _clearTaskQueue(Q,X){if(this._taskMessageQueue){let $=await this._taskMessageQueue.dequeueAll(Q,X);for(let J of $)if(J.type==="request"&&gJ(J.message)){let Y=J.message.id,G=this._requestResolvers.get(Y);if(G)G(new x(h.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(Y);else this._onerror(Error(`Resolver missing for request ${Y} during task ${Q} cleanup`))}}}async _waitForTaskUpdate(Q,X){let $=this._options?.defaultTaskPollInterval??1000;try{let J=await this._taskStore?.getTask(Q);if(J?.pollInterval)$=J.pollInterval}catch{}return new Promise((J,Y)=>{if(X.aborted){Y(new x(h.InvalidRequest,"Request cancelled"));return}let G=setTimeout(J,$);X.addEventListener("abort",()=>{clearTimeout(G),Y(new x(h.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(Q,X){let $=this._taskStore;if(!$)throw Error("No task store configured");return{createTask:async(J)=>{if(!Q)throw Error("No request provided");return await $.createTask(J,Q.id,{method:Q.method,params:Q.params},X)},getTask:async(J)=>{let Y=await $.getTask(J,X);if(!Y)throw new x(h.InvalidParams,"Failed to retrieve task: Task not found");return Y},storeTaskResult:async(J,Y,G)=>{await $.storeTaskResult(J,Y,G,X);let W=await $.getTask(J,X);if(W){let H=tQ.parse({method:"notifications/tasks/status",params:W});if(await this.notification(H),G9(W.status))this._cleanupTaskProgressHandler(J)}},getTaskResult:(J)=>{return $.getTaskResult(J,X)},updateTaskStatus:async(J,Y,G)=>{let W=await $.getTask(J,X);if(!W)throw new x(h.InvalidParams,`Task "${J}" not found - it may have been cleaned up`);if(G9(W.status))throw new x(h.InvalidParams,`Cannot update task "${J}" from terminal status "${W.status}" to "${Y}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await $.updateTaskStatus(J,Y,G,X);let H=await $.getTask(J,X);if(H){let z=tQ.parse({method:"notifications/tasks/status",params:H});if(await this.notification(z),G9(H.status))this._cleanupTaskProgressHandler(J)}},listTasks:(J)=>{return $.listTasks(J,X)}}}}function EW(Q){return Q!==null&&typeof Q==="object"&&!Array.isArray(Q)}function MW(Q,X){let $={...Q};for(let J in X){let Y=J,G=X[Y];if(G===void 0)continue;let W=$[Y];if(EW(W)&&EW(G))$[Y]={...W,...G};else $[Y]=G}return $}var Q1=w4(s7(),1),X1=w4(eK(),1);function VM(){let Q=new Q1.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return X1.default(Q),Q}class zY{constructor(Q){this._ajv=Q??VM()}getValidator(Q){let X="$id"in Q&&typeof Q.$id==="string"?this._ajv.getSchema(Q.$id)??this._ajv.compile(Q):this._ajv.compile(Q);return($)=>{if(X($))return{valid:!0,data:$,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(X.errors)}}}}class KY{constructor(Q){this._server=Q}requestStream(Q,X,$){return this._server.requestStream(Q,X,$)}createMessageStream(Q,X){let $=this._server.getClientCapabilities();if((Q.tools||Q.toolChoice)&&!$?.sampling?.tools)throw Error("Client does not support sampling tools capability.");if(Q.messages.length>0){let J=Q.messages[Q.messages.length-1],Y=Array.isArray(J.content)?J.content:[J.content],G=Y.some((K)=>K.type==="tool_result"),W=Q.messages.length>1?Q.messages[Q.messages.length-2]:void 0,H=W?Array.isArray(W.content)?W.content:[W.content]:[],z=H.some((K)=>K.type==="tool_use");if(G){if(Y.some((K)=>K.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!z)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(z){let K=new Set(H.filter((V)=>V.type==="tool_use").map((V)=>V.id)),q=new Set(Y.filter((V)=>V.type==="tool_result").map((V)=>V.toolUseId));if(K.size!==q.size||![...K].every((V)=>q.has(V)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:Q},eQ,X)}elicitInputStream(Q,X){let $=this._server.getClientCapabilities(),J=Q.mode??"form";switch(J){case"url":{if(!$?.elicitation?.url)throw Error("Client does not support url elicitation.");break}case"form":{if(!$?.elicitation?.form)throw Error("Client does not support form elicitation.");break}}let Y=J==="form"&&Q.mode===void 0?{...Q,mode:"form"}:Q;return this.requestStream({method:"elicitation/create",params:Y},YQ,X)}async getTask(Q,X){return this._server.getTask({taskId:Q},X)}async getTaskResult(Q,X,$){return this._server.getTaskResult({taskId:Q},X,$)}async listTasks(Q,X){return this._server.listTasks(Q?{cursor:Q}:void 0,X)}async cancelTask(Q,X){return this._server.cancelTask({taskId:Q},X)}}function $1(Q,X,$){if(!Q)throw Error(`${$} does not support task creation (required for ${X})`);switch(X){case"tools/call":if(!Q.tools?.call)throw Error(`${$} does not support task creation for tools/call (required for ${X})`);break;default:break}}function J1(Q,X,$){if(!Q)throw Error(`${$} does not support task creation (required for ${X})`);switch(X){case"sampling/createMessage":if(!Q.sampling?.createMessage)throw Error(`${$} does not support task creation for sampling/createMessage (required for ${X})`);break;case"elicitation/create":if(!Q.elicitation?.create)throw Error(`${$} does not support task creation for elicitation/create (required for ${X})`);break;default:break}}class qY extends Y7{constructor(Q,X){super(X);if(this._serverInfo=Q,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(sQ.options.map(($,J)=>[$,J])),this.isMessageIgnored=($,J)=>{let Y=this._loggingLevels.get(J);return Y?this.LOG_LEVEL_SEVERITY.get($)<this.LOG_LEVEL_SEVERITY.get(Y):!1},this._capabilities=X?.capabilities??{},this._instructions=X?.instructions,this._jsonSchemaValidator=X?.jsonSchemaValidator??new zY,this.setRequestHandler(fJ,($)=>this._oninitialize($)),this.setNotificationHandler(uJ,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(dJ,async($,J)=>{let Y=J.sessionId||J.requestInfo?.headers["mcp-session-id"]||void 0,{level:G}=$.params,W=sQ.safeParse(G);if(W.success)this._loggingLevels.set(Y,W.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new KY(this)};return this._experimental}registerCapabilities(Q){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=MW(this._capabilities,Q)}setRequestHandler(Q,X){let J=J9(Q)?.method;if(!J)throw Error("Schema is missing a method literal");let Y;if(z6(J)){let W=J;Y=W._zod?.def?.value??W.value}else{let W=J;Y=W._def?.value??W.value}if(typeof Y!=="string")throw Error("Schema method literal must be a string");if(Y==="tools/call"){let W=async(H,z)=>{let K=$9(JQ,H);if(!K.success){let U=K.error instanceof Error?K.error.message:String(K.error);throw new x(h.InvalidParams,`Invalid tools/call request: ${U}`)}let{params:q}=K.data,V=await Promise.resolve(X(H,z));if(q.task){let U=$9(XQ,V);if(!U.success){let A=U.error instanceof Error?U.error.message:String(U.error);throw new x(h.InvalidParams,`Invalid task creation result: ${A}`)}return U.data}let D=$9(wX,V);if(!D.success){let U=D.error instanceof Error?D.error.message:String(D.error);throw new x(h.InvalidParams,`Invalid tools/call result: ${U}`)}return D.data};return super.setRequestHandler(Q,W)}return super.setRequestHandler(Q,X)}assertCapabilityForMethod(Q){switch(Q){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${Q})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${Q})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${Q})`);break;case"ping":break}}assertNotificationCapability(Q){switch(Q){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${Q})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${Q})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${Q})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${Q})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(Q){if(!this._capabilities)return;switch(Q){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${Q})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${Q})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${Q})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${Q})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${Q})`);break;case"ping":case"initialize":break}}assertTaskCapability(Q){J1(this._clientCapabilities?.tasks?.requests,Q,"Client")}assertTaskHandlerCapability(Q){if(!this._capabilities)return;$1(this._capabilities.tasks?.requests,Q,"Server")}async _oninitialize(Q){let X=Q.params.protocolVersion;return this._clientCapabilities=Q.params.capabilities,this._clientVersion=Q.params.clientInfo,{protocolVersion:RG.includes(X)?X:_J,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"},JX)}async createMessage(Q,X){if(Q.tools||Q.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(Q.messages.length>0){let $=Q.messages[Q.messages.length-1],J=Array.isArray($.content)?$.content:[$.content],Y=J.some((z)=>z.type==="tool_result"),G=Q.messages.length>1?Q.messages[Q.messages.length-2]:void 0,W=G?Array.isArray(G.content)?G.content:[G.content]:[],H=W.some((z)=>z.type==="tool_use");if(Y){if(J.some((z)=>z.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!H)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(H){let z=new Set(W.filter((q)=>q.type==="tool_use").map((q)=>q.id)),K=new Set(J.filter((q)=>q.type==="tool_result").map((q)=>q.toolUseId));if(z.size!==K.size||![...z].every((q)=>K.has(q)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(Q.tools)return this.request({method:"sampling/createMessage",params:Q},oJ,X);return this.request({method:"sampling/createMessage",params:Q},eQ,X)}async elicitInput(Q,X){switch(Q.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let J=Q;return this.request({method:"elicitation/create",params:J},YQ,X)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let J=Q.mode==="form"?Q:{...Q,mode:"form"},Y=await this.request({method:"elicitation/create",params:J},YQ,X);if(Y.action==="accept"&&Y.content&&J.requestedSchema)try{let W=this._jsonSchemaValidator.getValidator(J.requestedSchema)(Y.content);if(!W.valid)throw new x(h.InvalidParams,`Elicitation response content does not match requested schema: ${W.errorMessage}`)}catch(G){if(G instanceof x)throw G;throw new x(h.InternalError,`Error validating elicitation response: ${G instanceof Error?G.message:String(G)}`)}return Y}}}createElicitationCompletionNotifier(Q,X){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:Q}},X)}async listRoots(Q,X){return this.request({method:"roots/list",params:Q},rJ,X)}async sendLoggingMessage(Q,X){if(this._capabilities.logging){if(!this.isMessageIgnored(Q.level,X))return this.notification({method:"notifications/message",params:Q})}}async sendResourceUpdated(Q){return this.notification({method:"notifications/resources/updated",params:Q})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}var G1=Symbol.for("mcp.completable");function BY(Q){return!!Q&&typeof Q==="object"&&G1 in Q}function W1(Q){return Q[G1]?.complete}var Y1;(function(Q){Q.Completable="McpCompletable"})(Y1||(Y1={}));var UM=/^[A-Za-z0-9._-]{1,128}$/;function AM(Q){let X=[];if(Q.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(Q.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${Q.length})`]};if(Q.includes(" "))X.push("Tool name contains spaces, which may cause parsing issues");if(Q.includes(","))X.push("Tool name contains commas, which may cause parsing issues");if(Q.startsWith("-")||Q.endsWith("-"))X.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");if(Q.startsWith(".")||Q.endsWith("."))X.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");if(!UM.test(Q)){let $=Q.split("").filter((J)=>!/[A-Za-z0-9._-]/.test(J)).filter((J,Y,G)=>G.indexOf(J)===Y);return X.push(`Tool name contains invalid characters: ${$.map((J)=>`"${J}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:X}}return{isValid:!0,warnings:X}}function DM(Q,X){if(X.length>0){console.warn(`Tool name validation warning for "${Q}":`);for(let $ of X)console.warn(` - ${$}`);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 VY(Q){let X=AM(Q);return DM(Q,X.warnings),X.isValid}class UY{constructor(Q){this._mcpServer=Q}registerToolTask(Q,X,$){let J={taskSupport:"required",...X.execution};if(J.taskSupport==="forbidden")throw Error(`Cannot register task-based tool '${Q}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(Q,X.title,X.description,X.inputSchema,X.outputSchema,X.annotations,J,X._meta,$)}}class DY{constructor(Q,X){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new qY(Q,X)}get experimental(){if(!this._experimental)this._experimental={tasks:new UY(this)};return this._experimental}async connect(Q){return await this.server.connect(Q)}async close(){await this.server.close()}setToolRequestHandlers(){if(this._toolHandlersInitialized)return;this.server.assertCanSetRequestHandler(U9(LX)),this.server.assertCanSetRequestHandler(U9(JQ)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(LX,()=>({tools:Object.entries(this._registeredTools).filter(([,Q])=>Q.enabled).map(([Q,X])=>{let $={name:Q,title:X.title,description:X.description,inputSchema:(()=>{let J=e9(X.inputSchema);return J?X7(J,{strictUnions:!0,pipeStrategy:"input"}):FM})(),annotations:X.annotations,execution:X.execution,_meta:X._meta};if(X.outputSchema){let J=e9(X.outputSchema);if(J)$.outputSchema=X7(J,{strictUnions:!0,pipeStrategy:"output"})}return $})})),this.server.setRequestHandler(JQ,async(Q,X)=>{try{let $=this._registeredTools[Q.params.name];if(!$)throw new x(h.InvalidParams,`Tool ${Q.params.name} not found`);if(!$.enabled)throw new x(h.InvalidParams,`Tool ${Q.params.name} disabled`);let J=!!Q.params.task,Y=$.execution?.taskSupport,G="createTask"in $.handler;if((Y==="required"||Y==="optional")&&!G)throw new x(h.InternalError,`Tool ${Q.params.name} has taskSupport '${Y}' but was not registered with registerToolTask`);if(Y==="required"&&!J)throw new x(h.MethodNotFound,`Tool ${Q.params.name} requires task augmentation (taskSupport: 'required')`);if(Y==="optional"&&!J&&G)return await this.handleAutomaticTaskPolling($,Q,X);let W=await this.validateToolInput($,Q.params.arguments,Q.params.name),H=await this.executeToolHandler($,W,X);if(J)return H;return await this.validateToolOutput($,H,Q.params.name),H}catch($){if($ instanceof x){if($.code===h.UrlElicitationRequired)throw $}return this.createToolError($ instanceof Error?$.message:String($))}}),this._toolHandlersInitialized=!0}createToolError(Q){return{content:[{type:"text",text:Q}],isError:!0}}async validateToolInput(Q,X,$){if(!Q.inputSchema)return;let Y=e9(Q.inputSchema)??Q.inputSchema,G=await r8(Y,X);if(!G.success){let W="error"in G?G.error:"Unknown error",H=t8(W);throw new x(h.InvalidParams,`Input validation error: Invalid arguments for tool ${$}: ${H}`)}return G.data}async validateToolOutput(Q,X,$){if(!Q.outputSchema)return;if(!("content"in X))return;if(X.isError)return;if(!X.structuredContent)throw new x(h.InvalidParams,`Output validation error: Tool ${$} has an output schema but no structured content was provided`);let J=e9(Q.outputSchema),Y=await r8(J,X.structuredContent);if(!Y.success){let G="error"in Y?Y.error:"Unknown error",W=t8(G);throw new x(h.InvalidParams,`Output validation error: Invalid structured content for tool ${$}: ${W}`)}}async executeToolHandler(Q,X,$){let J=Q.handler;if("createTask"in J){if(!$.taskStore)throw Error("No task store provided.");let G={...$,taskStore:$.taskStore};if(Q.inputSchema)return await Promise.resolve(J.createTask(X,G));else return await Promise.resolve(J.createTask(G))}if(Q.inputSchema)return await Promise.resolve(J(X,$));else return await Promise.resolve(J($))}async handleAutomaticTaskPolling(Q,X,$){if(!$.taskStore)throw Error("No task store provided for task-capable tool.");let J=await this.validateToolInput(Q,X.params.arguments,X.params.name),Y=Q.handler,G={...$,taskStore:$.taskStore},W=J?await Promise.resolve(Y.createTask(J,G)):await Promise.resolve(Y.createTask(G)),H=W.task.taskId,z=W.task,K=z.pollInterval??5000;while(z.status!=="completed"&&z.status!=="failed"&&z.status!=="cancelled"){await new Promise((V)=>setTimeout(V,K));let q=await $.taskStore.getTask(H);if(!q)throw new x(h.InternalError,`Task ${H} not found during polling`);z=q}return await $.taskStore.getTaskResult(H)}setCompletionRequestHandler(){if(this._completionHandlerInitialized)return;this.server.assertCanSetRequestHandler(U9(jX)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(jX,async(Q)=>{switch(Q.params.ref.type){case"ref/prompt":return mG(Q),this.handlePromptCompletion(Q,Q.params.ref);case"ref/resource":return lG(Q),this.handleResourceCompletion(Q,Q.params.ref);default:throw new x(h.InvalidParams,`Invalid completion reference: ${Q.params.ref}`)}}),this._completionHandlerInitialized=!0}async handlePromptCompletion(Q,X){let $=this._registeredPrompts[X.name];if(!$)throw new x(h.InvalidParams,`Prompt ${X.name} not found`);if(!$.enabled)throw new x(h.InvalidParams,`Prompt ${X.name} disabled`);if(!$.argsSchema)return S8;let Y=J9($.argsSchema)?.[Q.params.argument.name];if(!BY(Y))return S8;let G=W1(Y);if(!G)return S8;let W=await G(Q.params.argument.value,Q.params.context);return z1(W)}async handleResourceCompletion(Q,X){let $=Object.values(this._registeredResourceTemplates).find((G)=>G.resourceTemplate.uriTemplate.toString()===X.uri);if(!$){if(this._registeredResources[X.uri])return S8;throw new x(h.InvalidParams,`Resource template ${Q.params.ref.uri} not found`)}let J=$.resourceTemplate.completeCallback(Q.params.argument.name);if(!J)return S8;let Y=await J(Q.params.argument.value,Q.params.context);return z1(Y)}setResourceRequestHandlers(){if(this._resourceHandlersInitialized)return;this.server.assertCanSetRequestHandler(U9(UX)),this.server.assertCanSetRequestHandler(U9(AX)),this.server.assertCanSetRequestHandler(U9(DX)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(UX,async(Q,X)=>{let $=Object.entries(this._registeredResources).filter(([Y,G])=>G.enabled).map(([Y,G])=>({uri:Y,name:G.name,...G.metadata})),J=[];for(let Y of Object.values(this._registeredResourceTemplates)){if(!Y.resourceTemplate.listCallback)continue;let G=await Y.resourceTemplate.listCallback(X);for(let W of G.resources)J.push({...Y.metadata,...W})}return{resources:[...$,...J]}}),this.server.setRequestHandler(AX,async()=>{return{resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([X,$])=>({name:X,uriTemplate:$.resourceTemplate.uriTemplate.toString(),...$.metadata}))}}),this.server.setRequestHandler(DX,async(Q,X)=>{let $=new URL(Q.params.uri),J=this._registeredResources[$.toString()];if(J){if(!J.enabled)throw new x(h.InvalidParams,`Resource ${$} disabled`);return J.readCallback($,X)}for(let Y of Object.values(this._registeredResourceTemplates)){let G=Y.resourceTemplate.uriTemplate.match($.toString());if(G)return Y.readCallback($,G,X)}throw new x(h.InvalidParams,`Resource ${$} not found`)}),this._resourceHandlersInitialized=!0}setPromptRequestHandlers(){if(this._promptHandlersInitialized)return;this.server.assertCanSetRequestHandler(U9(FX)),this.server.assertCanSetRequestHandler(U9(OX)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(FX,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,Q])=>Q.enabled).map(([Q,X])=>{return{name:Q,title:X.title,description:X.description,arguments:X.argsSchema?LM(X.argsSchema):void 0}})})),this.server.setRequestHandler(OX,async(Q,X)=>{let $=this._registeredPrompts[Q.params.name];if(!$)throw new x(h.InvalidParams,`Prompt ${Q.params.name} not found`);if(!$.enabled)throw new x(h.InvalidParams,`Prompt ${Q.params.name} disabled`);if($.argsSchema){let J=e9($.argsSchema),Y=await r8(J,Q.params.arguments);if(!Y.success){let H="error"in Y?Y.error:"Unknown error",z=t8(H);throw new x(h.InvalidParams,`Invalid arguments for prompt ${Q.params.name}: ${z}`)}let G=Y.data,W=$.callback;return await Promise.resolve(W(G,X))}else{let J=$.callback;return await Promise.resolve(J(X))}}),this._promptHandlersInitialized=!0}resource(Q,X,...$){let J;if(typeof $[0]==="object")J=$.shift();let Y=$[0];if(typeof X==="string"){if(this._registeredResources[X])throw Error(`Resource ${X} is already registered`);let G=this._createRegisteredResource(Q,void 0,X,J,Y);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),G}else{if(this._registeredResourceTemplates[Q])throw Error(`Resource template ${Q} is already registered`);let G=this._createRegisteredResourceTemplate(Q,void 0,X,J,Y);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),G}}registerResource(Q,X,$,J){if(typeof X==="string"){if(this._registeredResources[X])throw Error(`Resource ${X} is already registered`);let Y=this._createRegisteredResource(Q,$.title,X,$,J);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),Y}else{if(this._registeredResourceTemplates[Q])throw Error(`Resource template ${Q} is already registered`);let Y=this._createRegisteredResourceTemplate(Q,$.title,X,$,J);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),Y}}_createRegisteredResource(Q,X,$,J,Y){let G={name:Q,title:X,metadata:J,readCallback:Y,enabled:!0,disable:()=>G.update({enabled:!1}),enable:()=>G.update({enabled:!0}),remove:()=>G.update({uri:null}),update:(W)=>{if(typeof W.uri<"u"&&W.uri!==$){if(delete this._registeredResources[$],W.uri)this._registeredResources[W.uri]=G}if(typeof W.name<"u")G.name=W.name;if(typeof W.title<"u")G.title=W.title;if(typeof W.metadata<"u")G.metadata=W.metadata;if(typeof W.callback<"u")G.readCallback=W.callback;if(typeof W.enabled<"u")G.enabled=W.enabled;this.sendResourceListChanged()}};return this._registeredResources[$]=G,G}_createRegisteredResourceTemplate(Q,X,$,J,Y){let G={resourceTemplate:$,title:X,metadata:J,readCallback:Y,enabled:!0,disable:()=>G.update({enabled:!1}),enable:()=>G.update({enabled:!0}),remove:()=>G.update({name:null}),update:(z)=>{if(typeof z.name<"u"&&z.name!==Q){if(delete this._registeredResourceTemplates[Q],z.name)this._registeredResourceTemplates[z.name]=G}if(typeof z.title<"u")G.title=z.title;if(typeof z.template<"u")G.resourceTemplate=z.template;if(typeof z.metadata<"u")G.metadata=z.metadata;if(typeof z.callback<"u")G.readCallback=z.callback;if(typeof z.enabled<"u")G.enabled=z.enabled;this.sendResourceListChanged()}};this._registeredResourceTemplates[Q]=G;let W=$.uriTemplate.variableNames;if(Array.isArray(W)&&W.some((z)=>!!$.completeCallback(z)))this.setCompletionRequestHandler();return G}_createRegisteredPrompt(Q,X,$,J,Y){let G={title:X,description:$,argsSchema:J===void 0?void 0:I9(J),callback:Y,enabled:!0,disable:()=>G.update({enabled:!1}),enable:()=>G.update({enabled:!0}),remove:()=>G.update({name:null}),update:(W)=>{if(typeof W.name<"u"&&W.name!==Q){if(delete this._registeredPrompts[Q],W.name)this._registeredPrompts[W.name]=G}if(typeof W.title<"u")G.title=W.title;if(typeof W.description<"u")G.description=W.description;if(typeof W.argsSchema<"u")G.argsSchema=I9(W.argsSchema);if(typeof W.callback<"u")G.callback=W.callback;if(typeof W.enabled<"u")G.enabled=W.enabled;this.sendPromptListChanged()}};if(this._registeredPrompts[Q]=G,J){if(Object.values(J).some((H)=>{let z=H instanceof $6?H._def?.innerType:H;return BY(z)}))this.setCompletionRequestHandler()}return G}_createRegisteredTool(Q,X,$,J,Y,G,W,H,z){VY(Q);let K={title:X,description:$,inputSchema:H1(J),outputSchema:H1(Y),annotations:G,execution:W,_meta:H,handler:z,enabled:!0,disable:()=>K.update({enabled:!1}),enable:()=>K.update({enabled:!0}),remove:()=>K.update({name:null}),update:(q)=>{if(typeof q.name<"u"&&q.name!==Q){if(typeof q.name==="string")VY(q.name);if(delete this._registeredTools[Q],q.name)this._registeredTools[q.name]=K}if(typeof q.title<"u")K.title=q.title;if(typeof q.description<"u")K.description=q.description;if(typeof q.paramsSchema<"u")K.inputSchema=I9(q.paramsSchema);if(typeof q.outputSchema<"u")K.outputSchema=I9(q.outputSchema);if(typeof q.callback<"u")K.handler=q.callback;if(typeof q.annotations<"u")K.annotations=q.annotations;if(typeof q._meta<"u")K._meta=q._meta;if(typeof q.enabled<"u")K.enabled=q.enabled;this.sendToolListChanged()}};return this._registeredTools[Q]=K,this.setToolRequestHandlers(),this.sendToolListChanged(),K}tool(Q,...X){if(this._registeredTools[Q])throw Error(`Tool ${Q} is already registered`);let $,J,Y,G;if(typeof X[0]==="string")$=X.shift();if(X.length>1){let H=X[0];if(AY(H)){if(J=X.shift(),X.length>1&&typeof X[0]==="object"&&X[0]!==null&&!AY(X[0]))G=X.shift()}else if(typeof H==="object"&&H!==null)G=X.shift()}let W=X[0];return this._createRegisteredTool(Q,void 0,$,J,Y,G,{taskSupport:"forbidden"},void 0,W)}registerTool(Q,X,$){if(this._registeredTools[Q])throw Error(`Tool ${Q} is already registered`);let{title:J,description:Y,inputSchema:G,outputSchema:W,annotations:H,_meta:z}=X;return this._createRegisteredTool(Q,J,Y,G,W,H,{taskSupport:"forbidden"},z,$)}prompt(Q,...X){if(this._registeredPrompts[Q])throw Error(`Prompt ${Q} is already registered`);let $;if(typeof X[0]==="string")$=X.shift();let J;if(X.length>1)J=X.shift();let Y=X[0],G=this._createRegisteredPrompt(Q,void 0,$,J,Y);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),G}registerPrompt(Q,X,$){if(this._registeredPrompts[Q])throw Error(`Prompt ${Q} is already registered`);let{title:J,description:Y,argsSchema:G}=X,W=this._createRegisteredPrompt(Q,J,Y,G,$);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),W}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(Q,X){return this.server.sendLoggingMessage(Q,X)}sendResourceListChanged(){if(this.isConnected())this.server.sendResourceListChanged()}sendToolListChanged(){if(this.isConnected())this.server.sendToolListChanged()}sendPromptListChanged(){if(this.isConnected())this.server.sendPromptListChanged()}}var FM={type:"object",properties:{}};function K1(Q){return Q!==null&&typeof Q==="object"&&"parse"in Q&&typeof Q.parse==="function"&&"safeParse"in Q&&typeof Q.safeParse==="function"}function OM(Q){return"_def"in Q||"_zod"in Q||K1(Q)}function AY(Q){if(typeof Q!=="object"||Q===null)return!1;if(OM(Q))return!1;if(Object.keys(Q).length===0)return!0;return Object.values(Q).some(K1)}function H1(Q){if(!Q)return;if(AY(Q))return I9(Q);return Q}function LM(Q){let X=J9(Q);if(!X)return[];return Object.entries(X).map(([$,J])=>{let Y=$G(J),G=JG(J);return{name:$,description:Y,required:!G}})}function U9(Q){let $=J9(Q)?.method;if(!$)throw Error("Schema is missing a method literal");let J=a8($);if(typeof J==="string")return J;throw Error("Schema method literal must be a string")}function z1(Q){return{completion:{values:Q.slice(0,100),total:Q.length,hasMore:Q.length>100}}}var S8={completion:{values:[],hasMore:!1}};import B1 from"node:process";class FY{append(Q){this._buffer=this._buffer?Buffer.concat([this._buffer,Q]):Q}readMessage(){if(!this._buffer)return null;let Q=this._buffer.indexOf(`
|
|
44
44
|
`);if(Q===-1)return null;let X=this._buffer.toString("utf8",0,Q).replace(/\r$/,"");return this._buffer=this._buffer.subarray(Q+1),wM(X)}clear(){this._buffer=void 0}}function wM(Q){return vG.parse(JSON.parse(Q))}function q1(Q){return JSON.stringify(Q)+`
|
|
45
|
-
`}class OY{constructor(Q=B1.stdin,X=B1.stdout){this._stdin=Q,this._stdout=X,this._readBuffer=new FY,this._started=!1,this._ondata=($)=>{this._readBuffer.append($),this.processReadBuffer()},this._onerror=($)=>{this.onerror?.($)}}async start(){if(this._started)throw 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(){while(!0)try{let Q=this._readBuffer.readMessage();if(Q===null)break;this.onmessage?.(Q)}catch(Q){this.onerror?.(Q)}}async close(){if(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(Q){return new Promise((X)=>{let $=q1(Q);if(this._stdout.write($))X();else this._stdout.once("drain",X)})}}var V1={name:"trueline-mcp",version:"2.5.
|
|
45
|
+
`}class OY{constructor(Q=B1.stdin,X=B1.stdout){this._stdin=Q,this._stdout=X,this._readBuffer=new FY,this._started=!1,this._ondata=($)=>{this._readBuffer.append($),this.processReadBuffer()},this._onerror=($)=>{this.onerror?.($)}}async start(){if(this._started)throw 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(){while(!0)try{let Q=this._readBuffer.readMessage();if(Q===null)break;this.onmessage?.(Q)}catch(Q){this.onerror?.(Q)}}async close(){if(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(Q){return new Promise((X)=>{let $=q1(Q);if(this._stdout.write($))X();else this._stdout.once("drain",X)})}}var V1={name:"trueline-mcp",version:"2.5.2",type:"module",description:"Truth-verified file editing for AI coding agents via MCP",license:"Apache-2.0",repository:{type:"git",url:"https://github.com/rjkaes/trueline-mcp.git"},homepage:"https://github.com/rjkaes/trueline-mcp#readme",bugs:{url:"https://github.com/rjkaes/trueline-mcp/issues"},keywords:["mcp","trueline","editing","verification","claude-code","gemini-cli","copilot"],bin:{"trueline-mcp":"./bin/trueline-mcp.js","trueline-hook":"./bin/trueline-hook.js"},files:["dist/","bin/","scripts/resolve-binary.cjs","hooks/","configs/","src/security.js","README.md","INSTALL.md","LICENSE"],scripts:{dev:"bun run src/server.ts",build:"bun build src/server.ts --target=node --minify --outfile dist/server.js",prepublishOnly:"bun run build",typecheck:"bun x tsc --noEmit",test:"bun test",lint:"bunx biome ci .","lint:fix":"bunx biome check --write .",benchmark:"bun run benchmarks/token-benchmark.ts && bun run benchmarks/perf-benchmark.ts"},dependencies:{"@modelcontextprotocol/sdk":"^1.26.0","tree-sitter-wasms":"0.1.13","web-tree-sitter":"0.24.7",zod:"^3.25.0"},devDependencies:{"@biomejs/biome":"2.4.5","@types/node":"^22.19.0","@xmldom/xmldom":"^0.8.11","bun-types":"^1.3.10",lefthook:"^2.1.2",typescript:"^5.7.0"}};function k0(Q){return{content:[{type:"text",text:Q}]}}function X0(Q){return{content:[{type:"text",text:Q}],isError:!0}}import{unlink as uM}from"node:fs/promises";import{relative as mM}from"node:path";class LY{entries=[];context(Q){this.entries.push({type:"ctx",text:Q})}delete(Q){this.entries.push({type:"del",text:Q})}insert(Q){this.entries.push({type:"ins",text:Q})}format(Q,X,$=3){let J=this.entries;if(J.length===0)return"";let Y=[];for(let K=0;K<J.length;K++)if(J[K].type!=="ctx")Y.push(K);if(Y.length===0)return"";let G=[],W=Y[0],H=Y[0];for(let K=1;K<Y.length;K++)if(Y[K]-H-1<=2*$)H=Y[K];else G.push([W,H]),W=Y[K],H=Y[K];G.push([W,H]);let z=[`--- ${Q}`,`+++ ${X}`];for(let[K,q]of G){let V=Math.max(0,K-$),D=Math.min(J.length-1,q+$),U=1,A=1;for(let R=0;R<V;R++){if(J[R].type!=="ins")U++;if(J[R].type!=="del")A++}let F=0,L=0,O=[];for(let R=V;R<=D;R++){let I=J[R];switch(I.type){case"ctx":O.push(` ${I.text}`),F++,L++;break;case"del":O.push(`-${I.text}`),F++;break;case"ins":O.push(`+${I.text}`),L++;break}}let w=F===1?`${U}`:`${U},${F}`,E=L===1?`${A}`:`${A},${L}`;z.push(`@@ -${w} +${E} @@`),z.push(...O)}return`${z.join(`
|
|
46
46
|
`)}
|
|
47
47
|
`}}import{randomBytes as MM}from"node:crypto";import{chmod as SM,open as RM,rename as PM,stat as bM,unlink as IM}from"node:fs/promises";import{dirname as ZM,resolve as CM}from"node:path";var y6=2166136261;var z4="0-0:00000000";function n6(Q,X,$){let J=2166136261;for(let Y=X;Y<$;Y++)J=Math.imul(J^Q[Y],16777619)>>>0;return J}function d6(Q,X){return Q=Math.imul(Q^X&255,16777619)>>>0,Q=Math.imul(Q^X>>>8&255,16777619)>>>0,Q=Math.imul(Q^X>>>16&255,16777619)>>>0,Q=Math.imul(Q^X>>>24&255,16777619)>>>0,Q}function Z6(Q,X,$){return`${Q}-${X}:${$.toString(16).padStart(8,"0")}`}var U1="abcdefghijklmnopqrstuvwxyz234567",NM=(()=>{let Q=Array(1024);for(let X=0;X<32;X++)for(let $=0;$<32;$++)Q[X*32+$]=U1[X]+U1[$];return Q})();function OQ(Q){return NM[(Q&31)<<5|Q>>>8&31]}import{open as EM}from"node:fs/promises";var R8=Buffer.from(`
|
|
48
48
|
`),wY=Buffer.from(`\r
|
|
@@ -63,7 +63,7 @@ checksum: ${Z6(w,E,O)}
|
|
|
63
63
|
checksum: ${z4}`);if(w===0&&q[0].start>R)return X0(`start_line ${q[0].start} out of range (file has ${R} lines)`);if(w>0&&E>0){let b=`
|
|
64
64
|
checksum: ${Z6(w,E,O)}`,o=Buffer.from(b);U.push(o),A+=o.length}if(f){let o=`
|
|
65
65
|
|
|
66
|
-
(truncated at ${I>V?`${V} line`:"20 MB output"} limit — use ranges for specific sections)`,H0=Buffer.from(o);U.push(H0),A+=H0.length}return k0(Buffer.concat(U,A).toString(z))}import{readFileSync as KS}from"node:fs";import{extname as qS}from"node:path";var A4=w4(R1(),1);import{createRequire as iM}from"node:module";import{resolve as nM,dirname as dM}from"node:path";var oM=iM(import.meta.url),P1=!1,b1=new Map;async function I1(){if(P1)return;await A4.default.init(),P1=!0}function rM(Q){let X=oM.resolve("tree-sitter-wasms/package.json");return nM(dM(X),"out",`tree-sitter-${Q}.wasm`)}async function tM(Q){let X=b1.get(Q);if(X)return X;await I1();let $=await A4.default.Language.load(rM(Q));return b1.set(Q,$),$}async function Z1(Q){await I1();let X=new A4.default,$=await tM(Q);return X.setLanguage($),X}async function C1(Q,X,$=1/0){let Y=(await Z1(X.grammar)).parse(Q),G=Q.split(`
|
|
66
|
+
(truncated at ${I>V?`${V} line`:"20 MB output"} limit — use ranges for specific sections)`,H0=Buffer.from(o);U.push(H0),A+=H0.length}return k0(Buffer.concat(U,A).toString(z))}import{readFileSync as KS}from"node:fs";import{extname as qS}from"node:path";var A4=w4(R1(),1);import{createRequire as iM}from"node:module";import{resolve as nM,dirname as dM}from"node:path";var oM=iM(import.meta.url),P1=!1,b1=new Map;async function I1(){if(P1)return;let Q=new Promise((X,$)=>setTimeout(()=>$(Error("tree-sitter WASM init timed out after 10 s")),1e4));await Promise.race([A4.default.init(),Q]),P1=!0}function rM(Q){let X=oM.resolve("tree-sitter-wasms/package.json");return nM(dM(X),"out",`tree-sitter-${Q}.wasm`)}async function tM(Q){let X=b1.get(Q);if(X)return X;await I1();let $=await A4.default.Language.load(rM(Q));return b1.set(Q,$),$}async function Z1(Q){await I1();let X=new A4.default,$=await tM(Q);return X.setLanguage($),X}async function C1(Q,X,$=1/0){let Y=(await Z1(X.grammar)).parse(Q),G=Q.split(`
|
|
67
67
|
`),W=[];function H(F){let L=F.startPosition.row,O=F.endPosition.row,w=G[L]?.trimEnd()??"";if(L===O||w.includes("{"))return w.length>200?`${w.slice(0,197)}...`:w;let E=[w.trimEnd()];for(let I=L+1;I<=Math.min(O,L+20);I++){let f=(G[I]??"").trimEnd();if(E.push(f.trim()),f.includes("{"))break}let R=E.join(" ").replace(/\s+/g," ").replace(/\(\s+/g,"(").replace(/,\s*\)/g,")").replace(/\s*\{\s*$/,"");if(R.length>200)R=`${R.slice(0,197)}...`;return R}let z=-1,K=-1,q=0,V="";function D(){if(q===0)return;let F=q===1?`1 ${V}`:`${q} ${V}s`;W.push({startLine:z,endLine:K,depth:0,nodeType:"_skipped",text:`(${F})`}),z=-1,K=-1,q=0,V=""}function U(F){let L=F.startPosition.row+1,O=F.endPosition.row+1,w=F.type.replace(/_/g," ").replace(/ statement$/,"").replace(/ declaration$/,"");if(q===0||w===V){if(q===0)z=L,V=w;K=O,q++}else D(),z=L,K=O,q=1,V=w}function A(F,L,O){if(O&&X.skip.has(F.type)){U(F);return}if(X.skip.has(F.type))return;let w=X.outline.has(F.type),E=X.topLevelOnly?.has(F.type)??!1;if(E&&!O)return;if(w||E&&O){if(O)D();if(W.push({startLine:F.startPosition.row+1,endLine:F.endPosition.row+1,depth:L,nodeType:F.type,text:H(F)}),L+1<=$)for(let R of F.children){if(!R.isNamed)continue;if(X.recurse.has(R.type))for(let I of R.children){if(!I.isNamed)continue;A(I,L+1,!1)}}return}}for(let F of Y.rootNode.children)A(F,0,!0);return D(),W}function T1(Q,X){let $=[];for(let J of Q){let Y=" ".repeat(J.depth);$.push(`${Y}${J.startLine}-${J.endLine}: ${J.text}`)}return $.push(""),$.push(`(${Q.length} symbols, ${X} source lines)`),$.join(`
|
|
68
68
|
`)}var h1={grammar:"typescript",outline:new Set(["function_declaration","class_declaration","interface_declaration","type_alias_declaration","enum_declaration","lexical_declaration","variable_declaration","export_statement","method_definition","public_field_definition"]),skip:new Set(["import_statement"]),recurse:new Set(["class_body"]),topLevelOnly:new Set(["expression_statement"])},aM={...h1,grammar:"tsx"},D4={grammar:"javascript",outline:new Set(["function_declaration","class_declaration","lexical_declaration","variable_declaration","export_statement","expression_statement","method_definition","field_definition"]),skip:new Set(["import_statement"]),recurse:new Set(["class_body"])},k1={grammar:"python",outline:new Set(["function_definition","class_definition","decorated_definition","expression_statement"]),skip:new Set(["import_statement","import_from_statement"]),recurse:new Set(["block"])},sM={grammar:"go",outline:new Set(["function_declaration","method_declaration","type_declaration","const_declaration","var_declaration"]),skip:new Set(["package_clause","import_declaration"]),recurse:new Set([])},eM={grammar:"rust",outline:new Set(["function_item","struct_item","enum_item","trait_item","impl_item","const_item","static_item","mod_item","type_item","macro_definition"]),skip:new Set(["use_declaration"]),recurse:new Set(["declaration_list"])},QS={grammar:"java",outline:new Set(["class_declaration","interface_declaration","enum_declaration","method_declaration","constructor_declaration","field_declaration"]),skip:new Set(["package_declaration","import_declaration"]),recurse:new Set(["class_body"])},XS={grammar:"ruby",outline:new Set(["method","class","module","assignment","call"]),skip:new Set([]),recurse:new Set(["body_statement"])},P8={grammar:"cpp",outline:new Set(["function_definition","class_specifier","struct_specifier","enum_specifier","namespace_definition","declaration","template_declaration"]),skip:new Set(["preproc_include"]),recurse:new Set(["declaration_list","field_declaration_list"])},v1={grammar:"c",outline:new Set(["function_definition","struct_specifier","enum_specifier","declaration","type_definition"]),skip:new Set(["preproc_include"]),recurse:new Set([])},$S={grammar:"c_sharp",outline:new Set(["class_declaration","interface_declaration","struct_declaration","enum_declaration","method_declaration","constructor_declaration","property_declaration","namespace_declaration"]),skip:new Set(["using_directive"]),recurse:new Set(["declaration_list"])},_1={grammar:"kotlin",outline:new Set(["function_declaration","class_declaration","object_declaration","property_declaration"]),skip:new Set(["import_list","package_header"]),recurse:new Set(["class_body"])},JS={grammar:"swift",outline:new Set(["function_declaration","class_declaration","struct_declaration","enum_declaration","protocol_declaration","extension_declaration","property_declaration"]),skip:new Set(["import_declaration"]),recurse:new Set(["class_body"])},YS={grammar:"php",outline:new Set(["function_definition","class_declaration","interface_declaration","trait_declaration","method_declaration","property_declaration"]),skip:new Set(["namespace_use_declaration"]),recurse:new Set(["declaration_list"])},x1={grammar:"scala",outline:new Set(["function_definition","class_definition","object_definition","trait_definition","val_definition","var_definition","type_definition"]),skip:new Set(["import_declaration"]),recurse:new Set(["template_body"])},g1={grammar:"elixir",outline:new Set(["call"]),skip:new Set([]),recurse:new Set([])},GS={grammar:"lua",outline:new Set(["function_declaration","local_function","variable_declaration","local_variable_declaration","assignment_statement"]),skip:new Set([]),recurse:new Set([])},WS={grammar:"dart",outline:new Set(["function_signature","class_definition","enum_declaration","mixin_declaration","extension_declaration","type_alias"]),skip:new Set(["import_or_export"]),recurse:new Set(["class_body"])},HS={grammar:"zig",outline:new Set(["TopLevelDecl","VarDecl","FnProto"]),skip:new Set([]),recurse:new Set([])},y1={grammar:"bash",outline:new Set(["function_definition","variable_assignment"]),skip:new Set([]),recurse:new Set([])},zS={".ts":h1,".tsx":aM,".js":D4,".jsx":D4,".mjs":D4,".cjs":D4,".py":k1,".pyi":k1,".go":sM,".rs":eM,".java":QS,".c":v1,".h":v1,".cpp":P8,".cc":P8,".cxx":P8,".hpp":P8,".hh":P8,".cs":$S,".rb":XS,".php":YS,".kt":_1,".kts":_1,".swift":JS,".scala":x1,".sc":x1,".ex":g1,".exs":g1,".lua":GS,".dart":WS,".zig":HS,".sh":y1,".bash":y1};function f1(Q){return zS[Q]}async function m1(Q){let{projectDir:X,allowedDirs:$}=Q,J=Q.file_paths;if(J.length===0)return X0("Provide at least one file path in file_paths.");if(J.length===1)return u1(J[0],Q.depth,X,$);let Y=[],G=0,W=0;for(let K of J){let q=await u1(K,Q.depth,X,$),V=q.content[0].type==="text"?q.content[0].text:"",D=V.match(/\((\d+) symbols?, (\d+) source lines?\)/);if(D)G+=Number(D[1]),W+=Number(D[2]);let U=X&&K.startsWith(X)?K.slice(X.length+1):K;Y.push(`--- ${U} ---
|
|
69
69
|
${V}`)}let H=Y.join(`
|
package/package.json
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
"use strict";
|
|
3
3
|
|
|
4
4
|
const { spawn, execFileSync } = require("node:child_process");
|
|
5
|
+
const { existsSync } = require("node:fs");
|
|
5
6
|
const path = require("node:path");
|
|
6
7
|
|
|
7
8
|
const pluginRoot = path.join(__dirname, "..");
|
|
@@ -30,10 +31,41 @@ function hasDeno() {
|
|
|
30
31
|
}
|
|
31
32
|
}
|
|
32
33
|
|
|
34
|
+
// ==============================================================================
|
|
35
|
+
// Dependency Installation
|
|
36
|
+
// ==============================================================================
|
|
37
|
+
|
|
38
|
+
// When installed as a Claude Code plugin, node_modules won't exist.
|
|
39
|
+
// Install dependencies on first launch so tree-sitter WASMs (needed by
|
|
40
|
+
// trueline_outline) and other native deps are available.
|
|
41
|
+
function ensureDeps() {
|
|
42
|
+
if (existsSync(path.join(pluginRoot, "node_modules"))) return;
|
|
43
|
+
|
|
44
|
+
process.stderr.write("trueline-mcp: installing dependencies (first run)...\n");
|
|
45
|
+
try {
|
|
46
|
+
// Prefer bun for speed, fall back to npm (ships with node).
|
|
47
|
+
const installer = hasBun() ? "bun" : "npm";
|
|
48
|
+
const args = installer === "bun" ? ["install"] : ["install", "--production"];
|
|
49
|
+
execFileSync(installer, args, {
|
|
50
|
+
cwd: pluginRoot,
|
|
51
|
+
stdio: ["ignore", "ignore", "inherit"],
|
|
52
|
+
timeout: 120_000,
|
|
53
|
+
});
|
|
54
|
+
process.stderr.write("trueline-mcp: dependencies installed.\n");
|
|
55
|
+
} catch (err) {
|
|
56
|
+
// Non-fatal: outline won't work, but read/edit/search/diff/verify will.
|
|
57
|
+
process.stderr.write(
|
|
58
|
+
`trueline-mcp: dependency install failed (${err.message}). ` + "trueline_outline will be unavailable.\n",
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
33
63
|
// ==============================================================================
|
|
34
64
|
// Launch
|
|
35
65
|
// ==============================================================================
|
|
36
66
|
|
|
67
|
+
ensureDeps();
|
|
68
|
+
|
|
37
69
|
let cmd, args;
|
|
38
70
|
if (hasBun()) {
|
|
39
71
|
cmd = "bun";
|