@juspay/neurolink 13.12.2 → 13.12.3

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.
@@ -1239,7 +1239,7 @@ Audio processing failed. Error: ${n instanceof Error?n.message:String(n)}`}}asyn
1239
1239
  - ARCHIVE (zip): Use entry_path to extract a specific file from the archive
1240
1240
  - TEXT/CODE: Use page_range as line range for targeted reading
1241
1241
 
1242
- For video extraction, the result includes images (frames) that will be visible to you. Always call list_attached_files first to discover file IDs.`,inputSchema:R.object({file_id:R.string().describe("File ID (UUID) or exact filename from list_attached_files"),start_time:R.number().optional().describe("Start timestamp in seconds (video only)"),end_time:R.number().optional().describe("End timestamp in seconds (video only)"),frame_count:R.number().int().min(1).max(20).optional().describe("Number of frames to extract in time range (video only, default: 5, max: 20)"),pages:R.array(R.number().int().min(1)).optional().describe("Specific page/slide numbers to extract (1-indexed)"),page_range:R.object({start:R.number().int().min(1),end:R.number().int().min(1)}).optional().describe("Page/slide range to extract (1-indexed, inclusive)"),sheet:R.string().optional().describe("Sheet name or 0-based index as string e.g. '0', '1' (spreadsheet only, default: first sheet)"),row_range:R.object({start:R.number().int().min(1),end:R.number().int().min(1)}).optional().describe("Row range (1-indexed, spreadsheet only)"),columns:R.array(R.string()).optional().describe("Specific column letters to include (e.g., ['A', 'B', 'D'], spreadsheet only)"),entry_path:R.string().optional().describe("File path within archive to extract (archive only)"),format:R.enum(["text","detailed","summary"]).optional().describe("Output format hint (default: text)")}),execute:async t=>{try{const r={...t,sheet:t.sheet!==void 0?/^\d+$/.test(t.sheet)?parseInt(t.sheet,10):t.sheet:void 0},n=await e.extractContent(r);return n.success?{success:!0,text:n.text,metadata:n.metadata,imageCount:n.images?.length??0,_images:n.images,error:void 0}:{success:!1,error:n.error,text:void 0,metadata:void 0,imageCount:0,_images:void 0}}catch(r){return{success:!1,error:r instanceof Error?r.message:String(r),text:void 0,metadata:void 0,imageCount:0,_images:void 0}}},toModelOutput:({output:t})=>{const r=[];if(t.text?r.push({type:"text",text:t.text}):t.error&&r.push({type:"text",text:`Error: ${t.error}`}),t._images&&t._images.length>0)for(const n of t._images)r.push({type:"image-data",data:n.toString("base64"),mediaType:"image/jpeg"});return r.length===0&&r.push({type:"text",text:"(No content extracted)"}),{type:"content",value:r}}}}function Pwr(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${(e/(1024*1024*1024)).toFixed(2)} GB`}var Y3n=E({"src/lib/files/fileTools.ts"(){"use strict";An(),su()}}),Owr={};ae(Owr,{AuthError:()=>Nt,AuthErrorCodes:()=>hB});var hB,Nt,Oa=E({"src/lib/auth/errors.ts"(){"use strict";m1(),hB={INVALID_TOKEN:"AUTH-001",EXPIRED_TOKEN:"AUTH-002",MISSING_TOKEN:"AUTH-003",TOKEN_DECODE_FAILED:"AUTH-004",INVALID_SIGNATURE:"AUTH-005",SESSION_NOT_FOUND:"AUTH-010",SESSION_EXPIRED:"AUTH-011",SESSION_REVOKED:"AUTH-012",INSUFFICIENT_PERMISSIONS:"AUTH-020",INSUFFICIENT_ROLES:"AUTH-021",ACCESS_DENIED:"AUTH-022",USER_NOT_FOUND:"AUTH-030",USER_DISABLED:"AUTH-031",EMAIL_NOT_VERIFIED:"AUTH-032",MFA_REQUIRED:"AUTH-033",PROVIDER_ERROR:"AUTH-040",PROVIDER_NOT_FOUND:"AUTH-041",PROVIDER_INIT_FAILED:"AUTH-042",CONFIGURATION_ERROR:"AUTH-043",CREATION_FAILED:"AUTH-050",REGISTRATION_FAILED:"AUTH-051",DUPLICATE_REGISTRATION:"AUTH-052",MIDDLEWARE_ERROR:"AUTH-060",RATE_LIMITED:"AUTH-061",JWKS_FETCH_FAILED:"AUTH-070",JWKS_KEY_NOT_FOUND:"AUTH-071"},Nt=Py("Auth",hB)}}),fB={};ae(fB,{AuthContextHolder:()=>yB,createAuthenticatedContext:()=>qwr,getAuthContext:()=>aS,getCurrentSession:()=>Nwr,getCurrentUser:()=>R4,globalAuthContext:()=>e_,hasAllPermissions:()=>Uwr,hasAnyRole:()=>Fwr,hasPermission:()=>gB,hasRole:()=>h0e,isAuthenticated:()=>Lwr,requireAuth:()=>m0e,requirePermission:()=>Bwr,requireRole:()=>zwr,requireUser:()=>$wr,runWithAuthContext:()=>Dwr});function Dwr(e,t){return cS.run(e,t)}function aS(){return cS.getStore()??e_.get()}function R4(){return(cS.getStore()??e_.get())?.user}function Nwr(){return(cS.getStore()??e_.get())?.session}function Lwr(){return cS.getStore()!==void 0||e_.isAuthenticated()}function m0e(){const e=aS();if(!e)throw Nt.create("MISSING_TOKEN","Authentication required");return e}function $wr(e){const t=m0e();if(t.user.id!==e)throw Nt.create("ACCESS_DENIED","User mismatch");return t}function gB(e){const t=R4();if(!t)return!1;if(t.permissions.includes(e)||t.permissions.includes("*"))return!0;const r=e.split(":");for(let n=r.length-1;n>0;n--){const o=[...r.slice(0,n),"*"].join(":");if(t.permissions.includes(o))return!0}return!1}function h0e(e){return R4()?.roles.includes(e)??!1}function Fwr(e){const t=R4();return t?e.some(r=>t.roles.includes(r)):!1}function Uwr(e){return e.every(t=>gB(t))}function Bwr(e){if(!gB(e))throw Nt.create("INSUFFICIENT_PERMISSIONS",`Permission denied: ${e}`)}function zwr(e){if(!h0e(e))throw Nt.create("INSUFFICIENT_ROLES",`Role required: ${e}`)}function qwr(e,t,r,n){return{...r,user:e,session:t,request:r,authenticatedAt:new Date,provider:n}}var cS,yB,e_,lS=E({"src/lib/auth/authContext.ts"(){"use strict";eB(),Oa(),cS=new tS,yB=class{context;set(e){this.context=e}get(){return this.context}clear(){this.context=void 0}getUser(){return this.context?.user}getSession(){return this.context?.session}isAuthenticated(){return this.context!==void 0}hasPermission(e){const t=this.context?.user;if(!t)return!1;if(t.permissions.includes(e)||t.permissions.includes("*"))return!0;const r=e.split(":");for(let n=r.length-1;n>0;n--){const o=[...r.slice(0,n),"*"].join(":");if(t.permissions.includes(o))return!0}return!1}hasRole(e){return this.context?.user.roles.includes(e)??!1}},e_=new yB}}),vB,Gwr,f0e,_B,jwr,Z3n=E({"src/lib/mcp/batching/requestBatcher.ts"(){"use strict";To(),G(),st(),qr(),gr(),vB=class extends On{config;pending=new Map;serverQueues=new Map;flushTimer;executor;activeBatches=0;batchCounter=0;requestCounter=0;isDestroyed=!1;constructor(e){super(),this.config={maxBatchSize:e.maxBatchSize,maxWaitMs:e.maxWaitMs,enableParallel:e.enableParallel??!0,maxConcurrentBatches:e.maxConcurrentBatches??5,groupByServer:e.groupByServer??!0}}setExecutor(e){this.executor=e}async add(e,t,r){if(this.isDestroyed)throw Te.invalidConfiguration("batcher","Batcher has been destroyed");if(!this.executor)throw Te.missingConfiguration("batchExecutor",{hint:"Call setExecutor() before adding requests"});const n=this.generateRequestId();return new Promise((o,i)=>{const s={id:n,tool:e,args:t,serverId:r,resolve:o,reject:i,addedAt:Date.now()};if(this.pending.set(n,s),this.config.groupByServer&&r){this.serverQueues.has(r)||this.serverQueues.set(r,new Set);const a=this.serverQueues.get(r);a&&a.add(n)}this.emit("requestQueued",{requestId:n,queueSize:this.pending.size}),this.pending.size>=this.config.maxBatchSize?this.scheduleFlush("size"):this.flushTimer||(this.flushTimer=setTimeout(()=>{this.scheduleFlush("timeout")},this.config.maxWaitMs))})}async flush(){this.clearFlushTimer(),this.pending.size!==0&&(this.emit("flushTriggered",{reason:"manual",queueSize:this.pending.size}),await this.executeBatch())}get queueSize(){return this.pending.size}get activeBatchCount(){return this.activeBatches}get isIdle(){return this.pending.size===0&&this.activeBatches===0}async drain(){await this.flush();const e=3e4,t=Date.now()+e;for(;!this.isIdle;){if(Date.now()>=t)throw Te.toolTimeout("batchDrain",e);await new Promise(r=>setTimeout(r,10))}}destroy(){this.isDestroyed=!0,this.clearFlushTimer();for(const e of this.pending.values())e.reject(Te.invalidConfiguration("batcher","Batcher was destroyed before request could complete"));this.pending.clear(),this.serverQueues.clear()}generateRequestId(){return`req-${Date.now()}-${++this.requestCounter}`}generateBatchId(){return`batch-${Date.now()}-${++this.batchCounter}`}scheduleFlush(e){this.clearFlushTimer(),this.emit("flushTriggered",{reason:e,queueSize:this.pending.size}),setImmediate(()=>{this.executeBatch().catch(t=>{g.error("Batch execution failed:",t)})})}clearFlushTimer(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0)}async executeBatch(){if(this.pending.size===0)return;if(this.activeBatches>=this.config.maxConcurrentBatches){this.clearFlushTimer(),this.flushTimer=setTimeout(()=>{this.executeBatch().catch(n=>{g.error("Rescheduled batch execution failed:",n)})},10);return}const e=this.selectBatchRequests();if(e.length===0)return;const t=this.generateBatchId(),r=Date.now();this.activeBatches++,this.emit("batchStarted",{batchId:t,size:e.length}),await wt({name:"mcp.batch.execute",tracer:We.mcp,attributes:{"mcp.batch.id":t,"mcp.batch.size":e.length,"mcp.batch.active_batches":this.activeBatches}},async n=>{let o=0,i=0;try{if(!this.executor)throw Te.missingConfiguration("batchExecutor",{hint:"Call setExecutor() before executing batches"});const s=this.executor(e.map(p=>({tool:p.tool,args:p.args,serverId:p.serverId}))),a=Math.max(5e3,Number(process.env.MCP_TOOL_TIMEOUT)||6e4);let c;const l=new Promise((p,m)=>{c=setTimeout(()=>m(Te.toolTimeout("batchExecution",a)),a)});s.catch(p=>{});const u=await Promise.race([s,l]).finally(()=>{c&&clearTimeout(c)}),d=[];for(let p=0;p<e.length;p++){const m=e[p],h=u[p],f=Date.now()-r;if(!h){const y=Te.toolExecutionFailed(m.tool,new Error(`Batch executor returned no result for request ${p}`));m.reject(y),d.push({id:m.id,success:!1,error:y,executionTime:f}),i++;continue}if(h.success)m.resolve(h.result),d.push({id:m.id,success:!0,result:h.result,executionTime:f}),o++;else{const y=h.error??Te.toolExecutionFailed(m.tool,new Error("Unknown batch execution error"));m.reject(y),d.push({id:m.id,success:!1,error:y,executionTime:f}),i++}}n.setAttribute("mcp.batch.success_count",o),n.setAttribute("mcp.batch.error_count",i),this.emit("batchCompleted",{batchId:t,results:d})}catch(s){const a=s instanceof Error?s:Te.toolExecutionFailed("batch",new Error(String(s)));for(const c of e)c.reject(a);throw this.emit("batchFailed",{batchId:t,error:a}),a}finally{this.activeBatches--}}).catch(n=>{g.error("Batch span execution failed:",n)}),this.pending.size>0&&(this.clearFlushTimer(),this.flushTimer=setTimeout(()=>{this.executeBatch().catch(n=>{g.error("Follow-up batch execution failed:",n)})},0))}selectBatchRequests(){const e=[];if(this.config.groupByServer&&this.serverQueues.size>0){const[t,r]=this.serverQueues.entries().next().value;for(const n of r){if(e.length>=this.config.maxBatchSize)break;const o=this.pending.get(n);o&&(e.push(o),this.pending.delete(n),r.delete(n))}r.size===0&&this.serverQueues.delete(t)}else{const t=Array.from(this.pending.values()).sort((r,n)=>r.addedAt-n.addedAt);for(const r of t){if(e.length>=this.config.maxBatchSize)break;e.push(r),this.pending.delete(r.id)}}return e}},Gwr=e=>new vB(e),f0e={maxBatchSize:10,maxWaitMs:100,enableParallel:!0,maxConcurrentBatches:5,groupByServer:!0},_B=class{batcher;toolExecutor;constructor(e){this.batcher=new vB({...f0e,...e}),this.batcher.setExecutor(async t=>{if(!this.toolExecutor)throw Te.missingConfiguration("toolExecutor",{hint:"Call setToolExecutor() before executing tool calls"});const r=this.toolExecutor;return await Promise.all(t.map(async o=>{try{return{success:!0,result:await r(o.tool,o.args,o.serverId)}}catch(i){return{success:!1,error:i instanceof Error?i:Te.toolExecutionFailed(o.tool,new Error(String(i)))}}}))})}setToolExecutor(e){this.toolExecutor=e}async execute(e,t,r){return this.batcher.add(e,t,r)}async flush(){return this.batcher.flush()}async drain(){return this.batcher.drain()}get queueSize(){return this.batcher.queueSize}get isIdle(){return this.batcher.isIdle}destroy(){this.batcher.destroy()}},jwr=e=>new _B(e)}}),Vwr=E({"src/lib/mcp/batching/index.ts"(){"use strict";Z3n()}}),t_,Hwr,g0e,wB,Wwr,Q3n=E({"src/lib/mcp/caching/toolCache.ts"(){"use strict";tr(),To(),on(),t_=class extends On{cache=new Map;config;stats;cleanupTimer;constructor(e){super(),this.config={ttl:e.ttl,maxSize:e.maxSize,strategy:e.strategy,enableAutoCleanup:e.enableAutoCleanup??!0,cleanupInterval:e.cleanupInterval??6e4,namespace:e.namespace??""},this.stats={hits:0,misses:0,evictions:0,size:0,maxSize:this.config.maxSize,hitRate:0},this.config.enableAutoCleanup&&this.startAutoCleanup()}get(e){const t=this.getFullKey(e),r=this.cache.get(t);if(!r){this.stats.misses++,this.updateHitRate(),this.emit("miss",{key:t});return}if(this.isExpired(r)){this.deleteWithReason(t,"expired"),this.stats.misses++,this.updateHitRate(),this.emit("miss",{key:t});return}r.accessedAt=Date.now(),r.accessCount++,this.stats.hits++,this.updateHitRate();const n=this.cloneCachedValue(r.value);return this.listenerCount("hit")>0&&this.emit("hit",{key:t,value:this.cloneCachedValue(r.value)}),n}set(e,t,r){const n=this.getFullKey(e),o=r??this.config.ttl,i=Date.now();this.cache.size>=this.config.maxSize&&!this.cache.has(n)&&this.evictOne();const s={value:this.cloneCachedValue(t),expires:i+o,createdAt:i,accessedAt:i,accessCount:1,key:n};this.cache.set(n,s),this.stats.size=this.cache.size,this.emit("set",{key:n,value:t,ttl:o})}has(e){const t=this.getFullKey(e),r=this.cache.get(t);return r?this.isExpired(r)?(this.deleteWithReason(t,"expired"),!1):!0:!1}delete(e){const t=this.getFullKey(e),r=this.cache.delete(t);return r&&(this.stats.size=this.cache.size,this.emit("evict",{key:t,reason:"manual"})),r}invalidate(e){const t=this.getFullKey(e),r=this.patternToRegex(t);let n=0;for(const o of this.cache.keys())r.test(o)&&(this.cache.delete(o),n++,this.emit("evict",{key:o,reason:"manual"}));return this.stats.size=this.cache.size,n}clear(){const e=this.cache.size;this.cache.clear(),this.stats.size=0,this.emit("clear",{entriesRemoved:e})}async getOrSet(e,t,r){const n=this.get(e);if(n!==void 0)return n;const o=3e4,i=await Dt(Promise.resolve(t()),o,`ToolCache getOrSet factory timed out after ${o}ms for key "${e}"`);return i===void 0||this.set(e,i,r),i}getStats(){return{...this.stats}}resetStats(){this.stats.hits=0,this.stats.misses=0,this.stats.evictions=0,this.updateHitRate()}keys(){return Array.from(this.cache.keys())}get size(){return this.cache.size}static generateKey(e,t){const r=(o,i=new WeakSet)=>{if(o===null||typeof o!="object")return JSON.stringify(o);if(o instanceof Date)return`{"$date":${JSON.stringify(o.toISOString())}}`;if(i.has(o))throw new TypeError("Circular structures are not supported in cache keys");if(i.add(o),Array.isArray(o)){const c="["+o.map(l=>r(l,i)).join(",")+"]";return i.delete(o),c}const a=Object.keys(o).sort().map(c=>JSON.stringify(c)+":"+r(o[c],i));return i.delete(o),"{"+a.join(",")+"}"},n=Bu("sha256").update(r(t)).digest("hex").substring(0,16);return`${e}:${n}`}destroy(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.clear()}cloneCachedValue(e){if(e===null||typeof e!="object")return e;try{return structuredClone(e)}catch{return JSON.parse(JSON.stringify(e))}}getFullKey(e){return this.config.namespace?`${this.config.namespace}:${e}`:e}isExpired(e){return Date.now()>e.expires}deleteWithReason(e,t){const r=this.cache.delete(e);return r&&(this.stats.evictions++,this.stats.size=this.cache.size,this.emit("evict",{key:e,reason:t})),r}evictOne(){const e=this.selectEvictionCandidate();e&&(this.cache.delete(e.key),this.stats.evictions++,this.stats.size=this.cache.size,this.emit("evict",{key:e.key,reason:"capacity"}))}selectEvictionCandidate(){if(this.cache.size!==0)switch(this.config.strategy){case"lru":return this.findLRU();case"fifo":return this.findFIFO();case"lfu":return this.findLFU();default:return this.findLRU()}}findLRU(){let e,t=1/0;for(const r of this.cache.values())r.accessedAt<t&&(t=r.accessedAt,e=r);return e}findFIFO(){let e,t=1/0;for(const r of this.cache.values())r.createdAt<t&&(t=r.createdAt,e=r);return e}findLFU(){let e,t=1/0;for(const r of this.cache.values())r.accessCount<t&&(t=r.accessCount,e=r);return e}patternToRegex(e){const r=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^:]*");return new RegExp(`^${r}$`)}updateHitRate(){const e=this.stats.hits+this.stats.misses;this.stats.hitRate=e>0?this.stats.hits/e:0}startAutoCleanup(){this.cleanupTimer=setInterval(()=>{this.cleanupExpired()},this.config.cleanupInterval),this.cleanupTimer.unref&&this.cleanupTimer.unref()}cleanupExpired(){const e=Date.now();for(const[t,r]of this.cache.entries())e>r.expires&&(this.cache.delete(t),this.stats.evictions++,this.emit("evict",{key:t,reason:"expired"}));this.stats.size=this.cache.size}},Hwr=e=>new t_(e),g0e={ttl:300*1e3,maxSize:500,strategy:"lru",enableAutoCleanup:!0,cleanupInterval:6e4},wB=class{cache;constructor(e){this.cache=new t_({...g0e,...e,namespace:e?.namespace??"tool-results"})}cacheResult(e,t,r,n){const o=t_.generateKey(e,t);this.cache.set(o,r,n)}getCachedResult(e,t){const r=t_.generateKey(e,t);return this.cache.get(r)}hasCachedResult(e,t){const r=t_.generateKey(e,t);return this.cache.has(r)}invalidateTool(e){return this.cache.invalidate(`${e}:*`)}getStats(){return this.cache.getStats()}clear(){this.cache.clear()}destroy(){this.cache.destroy()}},Wwr=e=>new wB(e)}}),Kwr=E({"src/lib/mcp/caching/index.ts"(){"use strict";Q3n()}}),Jwr={};ae(Jwr,{createAnnotatedTool:()=>Ywr,filterToolsByAnnotations:()=>ebr,getAnnotationSummary:()=>tbr,getToolSafetyLevel:()=>Qwr,inferAnnotations:()=>sh,isSafeToRetry:()=>v0e,mergeAnnotations:()=>y0e,requiresConfirmation:()=>Zwr,validateAnnotations:()=>Xwr});function sh(e){const t=e.name,r=e.description.toLowerCase(),n={},o=(l,u)=>new RegExp(`\\b${u}\\b`,"i").test(l)?!0:l.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase().split(/[_-]/).some(p=>p===u.toLowerCase());return["get","list","read","fetch","query","search","find","show","display","view","retrieve","check","inspect","look"].some(l=>o(r,l)||o(t,l))&&(n.readOnlyHint=!0),["delete","remove","drop","destroy","clear","purge","erase","wipe","truncate","reset"].some(l=>o(r,l)||o(t,l))&&(n.destructiveHint=!0,n.requiresConfirmation=!0),["set","update","put","upsert","replace"].some(l=>o(r,l)||o(t,l))&&!n.destructiveHint&&(n.idempotentHint=!0),["complex","analyze","process","generate","transform","compute","calculate"].some(l=>o(r,l)||o(t,l))?n.complexity="complex":r.length>100?n.complexity="medium":n.complexity="simple",n}function y0e(...e){const t={};for(const r of e)if(r){const n=t.tags?[...t.tags]:[];if(Object.assign(t,r),n.length>0||r.tags){const o=r.tags??[];t.tags=[...new Set([...n,...o])]}}return t}function Xwr(e){const t=[];if(e.readOnlyHint&&e.destructiveHint&&t.push("Tool cannot be both readOnly and destructive - these are conflicting hints"),e.rateLimitHint!==void 0&&(e.rateLimitHint<0||!Number.isFinite(e.rateLimitHint))&&t.push("rateLimitHint must be a non-negative number"),e.estimatedDuration!==void 0&&(e.estimatedDuration<0||!Number.isFinite(e.estimatedDuration))&&t.push("estimatedDuration must be a non-negative number"),e.costHint!==void 0&&(e.costHint<0||!Number.isFinite(e.costHint))&&t.push("costHint must be a non-negative number"),e.tags){for(const r of e.tags)if(typeof r!="string"||r.length===0){t.push("All tags must be non-empty strings");break}}return t}function Ywr(e){const t=sh(e),r=y0e(t,e.annotations);return{...e,annotations:r}}function Zwr(e){return!!(e.annotations?.requiresConfirmation||e.annotations?.destructiveHint)}function v0e(e){return!!(e.annotations?.idempotentHint||e.annotations?.readOnlyHint)}function Qwr(e){return e.annotations?.destructiveHint?"dangerous":e.annotations?.readOnlyHint?"safe":(e.annotations?.idempotentHint,"moderate")}function ebr(e,t){return e.filter(r=>{const n=r.annotations??{};return t(n)})}function tbr(e){const t=[];return e.title&&t.push(e.title),e.readOnlyHint&&t.push("read-only"),e.destructiveHint&&t.push("DESTRUCTIVE"),e.idempotentHint&&t.push("idempotent"),e.requiresConfirmation&&t.push("requires confirmation"),e.complexity&&t.push(`${e.complexity} complexity`),e.estimatedDuration!==void 0&&t.push(`~${e.estimatedDuration}ms`),e.tags?.length&&t.push(`tags: ${e.tags.join(", ")}`),t.length>0?`[${t.join(" | ")}]`:"[no annotations]"}var M4=E({"src/lib/mcp/toolAnnotations.ts"(){"use strict"}}),rbr={};ae(rbr,{MultiServerManager:()=>P4,globalMultiServerManager:()=>_0e});var P4,_0e,w0e=E({"src/lib/mcp/multiServerManager.ts"(){"use strict";To(),G(),st(),P4=class extends On{config;servers=new Map;groups=new Map;metrics=new Map;roundRobinCounters=new Map;toolPreferences=new Map;constructor(e={}){super(),this.config={defaultStrategy:e.defaultStrategy??"round-robin",healthAwareRouting:e.healthAwareRouting??!0,healthCheckInterval:e.healthCheckInterval??3e4,maxFailoverRetries:e.maxFailoverRetries??3,namespaceSeparator:e.namespaceSeparator??".",autoNamespace:e.autoNamespace??!1,conflictResolution:e.conflictResolution??"first-wins"}}addServer(e){this.servers.set(e.id,e),this.metrics.set(e.id,{activeRequests:0,totalRequests:0,completedRequests:0,averageResponseTime:0,errorRate:0,isHealthy:e.status==="connected"}),this.emit("serverAdded",{serverId:e.id,server:e}),g.debug(`[MultiServerManager] Added server: ${e.id} (${e.name})`)}removeServer(e){if(!this.servers.get(e))return!1;for(const[r,n]of this.groups){const o=n.servers.indexOf(e);o!==-1&&(n.servers.splice(o,1),n.servers.length===0&&(this.groups.delete(r),this.roundRobinCounters.delete(r)))}this.servers.delete(e),this.metrics.delete(e);for(const[r,n]of this.toolPreferences)n===e&&this.toolPreferences.delete(r);return this.emit("serverRemoved",{serverId:e}),g.debug(`[MultiServerManager] Removed server: ${e}`),!0}updateServer(e,t){const r=this.servers.get(e);if(!r)throw Te.invalidConfiguration("serverId",`Server '${e}' not found`,{serverId:e});const n={...r,...t,id:e};this.servers.set(e,n);const o=this.metrics.get(e);o&&t.status!==void 0&&(o.isHealthy=t.status==="connected"),this.emit("serverUpdated",{serverId:e,server:n})}createGroup(e){for(const t of e.servers)if(!this.servers.has(t))throw Te.invalidConfiguration("serverGroup.servers",`Server '${t}' not found when creating group '${e.id}'`,{serverId:t,groupId:e.id});this.groups.set(e.id,e),this.roundRobinCounters.set(e.id,0),this.emit("groupCreated",{group:e}),g.debug(`[MultiServerManager] Created group: ${e.id} with ${e.servers.length} servers`)}removeGroup(e){const t=this.groups.delete(e);return t&&(this.roundRobinCounters.delete(e),this.emit("groupRemoved",{groupId:e})),t}addServerToGroup(e,t){const r=this.groups.get(t);if(!r)throw Te.invalidConfiguration("groupId",`Group '${t}' not found`,{groupId:t});if(!this.servers.has(e))throw Te.invalidConfiguration("serverId",`Server '${e}' not found`,{serverId:e,groupId:t});r.servers.includes(e)||(r.servers.push(e),this.emit("serverAddedToGroup",{serverId:e,groupId:t}))}removeServerFromGroup(e,t){const r=this.groups.get(t);if(!r)return!1;const n=r.servers.indexOf(e);return n!==-1?(r.servers.splice(n,1),this.emit("serverRemovedFromGroup",{serverId:e,groupId:t}),!0):!1}getUnifiedTools(){const e=new Map;for(const[t,r]of this.servers){const o=this.metrics.get(t)?.isHealthy??!0;if(!(this.config.healthAwareRouting&&!o))for(const i of r.tools||[]){const s=e.get(i.name);s?(s.hasConflict=!0,s.servers.push({serverId:t,serverName:r.name,inputSchema:i.inputSchema,priority:this.getServerPriority(t)})):e.set(i.name,{name:i.name,description:i.description,servers:[{serverId:t,serverName:r.name,inputSchema:i.inputSchema,priority:this.getServerPriority(t)}],hasConflict:!1,preferredServerId:this.toolPreferences.get(i.name)})}}for(const t of e.values())t.servers.sort((r,n)=>r.priority-n.priority),!t.preferredServerId&&t.servers.length>0&&(t.preferredServerId=t.servers[0].serverId);return Array.from(e.values())}getNamespacedTools(){const e=[];for(const[t,r]of this.servers)if(!(this.config.healthAwareRouting&&!(this.metrics.get(t)?.isHealthy??!0)))for(const n of r.tools||[])e.push({fullName:`${t}${this.config.namespaceSeparator}${n.name}`,toolName:n.name,serverId:t,serverName:r.name,description:n.description,inputSchema:n.inputSchema});return e}setToolPreference(e,t){if(!this.servers.has(t))throw Te.invalidConfiguration("serverId",`Server '${t}' not found`,{serverId:t,toolName:e});this.toolPreferences.set(e,t),this.emit("toolPreferenceSet",{toolName:e,serverId:t})}clearToolPreference(e){this.toolPreferences.delete(e)}selectServer(e,t){const r=this.toolPreferences.get(e);if(r){const c=this.servers.get(r),l=this.metrics.get(r);if(c&&(!this.config.healthAwareRouting||l?.isHealthy)&&c.tools?.some(u=>u.name===e))return{serverId:r,server:c}}let n;if(t){const c=this.groups.get(t);if(!c)return g.warn(`[MultiServerManager] Group '${t}' not found`),null;n=c.servers.filter(l=>this.servers.get(l)?.tools?.some(d=>d.name===e))}else{n=[];for(const[c,l]of this.servers)l.tools?.some(u=>u.name===e)&&n.push(c)}if(n.length===0)return null;if((t?this.groups.get(t)?.healthAware??this.config.healthAwareRouting:this.config.healthAwareRouting)&&(n=n.filter(c=>this.metrics.get(c)?.isHealthy??!0),n.length===0))return g.warn(`[MultiServerManager] No healthy servers available for tool '${e}'`),null;const i=t?this.groups.get(t)?.strategy??this.config.defaultStrategy:this.config.defaultStrategy,s=this.applyStrategy(i,n,t);if(!s)return null;const a=this.servers.get(s);return a?{serverId:s,server:a}:null}applyStrategy(e,t,r){if(t.length===0)return null;if(t.length===1)return t[0];switch(e){case"round-robin":{const n=r??"default",o=this.roundRobinCounters.get(n)??0,i=t[o%t.length];return this.roundRobinCounters.set(n,o+1),i}case"least-loaded":{let n=1/0,o=t[0];for(const i of t){const a=this.metrics.get(i)?.activeRequests??0;a<n&&(n=a,o=i)}return o}case"random":{const n=Math.floor(Math.random()*t.length);return t[n]}case"weighted":{if(!r){const c=Math.floor(Math.random()*t.length);return t[c]}const n=this.groups.get(r);if(!n?.weights){const c=Math.floor(Math.random()*t.length);return t[c]}const o=1,i=t.map(c=>{const u=(n.weights??[]).find(d=>d.serverId===c);return{serverId:c,weight:u?.weight??o}}),s=i.reduce((c,l)=>c+l.weight,0);if(s===0){const c=Math.floor(Math.random()*t.length);return t[c]}let a=Math.random()*s;for(const c of i)if(a-=c.weight,a<=0)return c.serverId;return t[0]}case"failover-only":return t.map(o=>({id:o,priority:this.getServerPriority(o,r)})).sort((o,i)=>o.priority-i.priority)[0]?.id??null;default:return t[0]}}getServerPriority(e,t){if(t){const n=this.groups.get(t);if(n?.weights){const o=n.weights.find(i=>i.serverId===e);if(o)return o.priority}}for(const n of this.groups.values())if(n.weights){const o=n.weights.find(i=>i.serverId===e);if(o)return o.priority}return Array.from(this.servers.keys()).indexOf(e)}updateMetrics(e,t){const r=this.metrics.get(e);r&&(Object.assign(r,t),this.emit("metricsUpdated",{serverId:e,metrics:{...r}}))}requestStarted(e){const t=this.metrics.get(e);t&&(t.activeRequests++,t.totalRequests++)}requestCompleted(e,t,r){const n=this.metrics.get(e);if(n){n.activeRequests=Math.max(0,n.activeRequests-1),n.completedRequests++;const o=n.averageResponseTime*(n.completedRequests-1)+t;n.averageResponseTime=o/n.completedRequests;const i=.1;n.errorRate=n.errorRate*(1-i)+(r?0:1)*i}}getServers(){return Array.from(this.servers.values())}getServer(e){return this.servers.get(e)}getGroups(){return Array.from(this.groups.values())}getGroup(e){return this.groups.get(e)}getServerMetrics(e){return this.metrics.get(e)}getAllMetrics(){return new Map(this.metrics)}getStatistics(){let e=0,t=0,r=0;for(const i of this.metrics.values())i.isHealthy&&e++,t+=i.totalRequests,r+=i.activeRequests;const n=this.getUnifiedTools(),o=n.filter(i=>i.hasConflict).length;return{totalServers:this.servers.size,healthyServers:e,totalGroups:this.groups.size,totalTools:n.length,conflictingTools:o,totalRequests:t,activeRequests:r}}},_0e=new P4}}),nbr={};ae(nbr,{EnhancedToolDiscovery:()=>bB});var bB,b0e=E({"src/lib/mcp/enhancedToolDiscovery.ts"(){"use strict";To(),G(),on(),st(),M4(),w0e(),bB=class extends On{toolRegistry=new Map;serverToolsMap=new Map;multiServerManager;discoveryInProgress=new Set;constructor(e){super(),this.multiServerManager=e??new P4}async discoverToolsWithAnnotations(e,t,r=1e4){const n=Date.now();if(this.discoveryInProgress.has(e))return{success:!1,error:`Discovery already in progress for server: ${e}`,toolCount:0,tools:[],duration:Date.now()-n,serverId:e};this.discoveryInProgress.add(e);try{g.info(`[EnhancedToolDiscovery] Starting discovery with annotations for: ${e}`);const o=await Dt(t.listTools(),r,"Discovery timeout");if(!o?.tools)throw Te.toolExecutionFailed("discoverTools",new Error("No tools returned from server"),e);this.clearServerTools(e);const i=[];for(const s of o.tools){const a=this.createEnhancedToolInfo(e,s),c=this.createToolKey(e,s.name);this.toolRegistry.set(c,a);let l=this.serverToolsMap.get(e);l||(l=new Set,this.serverToolsMap.set(e,l)),l.add(s.name),i.push(a),this.emit("toolDiscovered",{serverId:e,toolName:s.name,annotations:a.annotations,timestamp:new Date})}return g.info(`[EnhancedToolDiscovery] Discovered ${i.length} tools with annotations from ${e}`),{success:!0,toolCount:i.length,tools:i,duration:Date.now()-n,serverId:e}}catch(o){const i=o instanceof Error?o.message:String(o);return g.error(`[EnhancedToolDiscovery] Discovery failed for ${e}:`,o),{success:!1,error:i,toolCount:0,tools:[],duration:Date.now()-n,serverId:e}}finally{this.discoveryInProgress.delete(e)}}createEnhancedToolInfo(e,t){const r=sh({name:t.name,description:t.description??""});return{name:t.name,description:t.description??"No description provided",serverId:e,inputSchema:t.inputSchema,isAvailable:!0,annotations:r,version:"1.0.0",stats:{totalCalls:0,successfulCalls:0,failedCalls:0,averageExecutionTime:0,lastExecutionTime:0},metadata:{category:this.inferCategory(t),deprecated:!1}}}inferCategory(e){const t=e.name.toLowerCase(),r=(e.description??"").toLowerCase();return t.includes("git")||r.includes("git")?"version-control":t.includes("file")||t.includes("read")||t.includes("write")?"file-system":t.includes("api")||t.includes("http")?"api":t.includes("data")||t.includes("query")?"data":t.includes("auth")||t.includes("login")?"authentication":t.includes("deploy")||t.includes("build")?"deployment":"general"}searchTools(e){const t=Date.now();let r=Array.from(this.toolRegistry.values());if(e.name){const o=e.name.toLowerCase();r=r.filter(i=>i.name.toLowerCase().includes(o))}if(e.description){const o=e.description.toLowerCase().split(/\s+/);r=r.filter(i=>{const s=i.description.toLowerCase();return o.some(a=>s.includes(a))})}if(e.serverIds?.length){const o=e.serverIds;r=r.filter(i=>o.includes(i.serverId))}if(e.category&&(r=r.filter(o=>o.metadata?.category===e.category)),e.tags?.length){const o=e.tags;r=r.filter(i=>{const s=i.annotations?.tags??[];return o.some(a=>s.includes(a))})}if(e.annotations){const o=e.annotations;r=r.filter(i=>{if(!i.annotations)return!1;for(const[s,a]of Object.entries(o)){const c=s;if(i.annotations[c]!==a)return!1}return!0})}if(e.includeUnavailable||(r=r.filter(o=>o.isAvailable)),e.sortBy){const o=e.sortDirection==="desc"?-1:1;r.sort((i,s)=>{let a=0;switch(e.sortBy){case"name":a=i.name.localeCompare(s.name);break;case"calls":a=i.stats.totalCalls-s.stats.totalCalls;break;case"successRate":{const c=i.stats.totalCalls>0?i.stats.successfulCalls/i.stats.totalCalls:0,l=s.stats.totalCalls>0?s.stats.successfulCalls/s.stats.totalCalls:0;a=c-l;break}case"avgExecutionTime":a=i.stats.averageExecutionTime-s.stats.averageExecutionTime;break}return a*o})}const n=r.length;return e.limit&&e.limit>0&&(r=r.slice(0,e.limit)),{tools:r,totalCount:n,criteria:e,executionTime:Date.now()-t}}getToolsBySafetyLevel(e){return Array.from(this.toolRegistry.values()).filter(t=>{const r=t.annotations??{};switch(e){case"dangerous":return r.destructiveHint===!0;case"safe":return r.readOnlyHint===!0;case"moderate":return!r.destructiveHint&&!r.readOnlyHint;default:return!1}})}getToolsRequiringConfirmation(){return Array.from(this.toolRegistry.values()).filter(e=>e.annotations?.requiresConfirmation===!0||e.annotations?.destructiveHint===!0)}getReadOnlyTools(){return Array.from(this.toolRegistry.values()).filter(e=>e.annotations?.readOnlyHint===!0)}getUnifiedTools(){return this.multiServerManager.getUnifiedTools()}registerServer(e){this.multiServerManager.addServer(e)}updateToolAnnotations(e,t,r){const n=this.createToolKey(e,t),o=this.toolRegistry.get(n);return o?(o.annotations={...o.annotations,...r},this.emit("annotationsUpdated",{serverId:e,toolName:t,annotations:o.annotations,timestamp:new Date}),!0):!1}checkCompatibility(e,t,r){const n=this.createToolKey(t,e),o=this.toolRegistry.get(n),i=[],s=[],a=[];if(!o)return{compatible:!1,issues:[`Tool '${e}' not found on server '${t}'`],warnings:[],recommendations:[]};if(r&&o.version){const c=o.version.split(".").map(Number),l=r.split(".").map(Number);c.some(isNaN)||l.some(isNaN)?s.push(`Non-standard version format: tool=${o.version}, target=${r}`):c[0]!==l[0]?i.push(`Major version mismatch: tool is v${o.version}, target is v${r}`):c[1]<l[1]&&s.push(`Minor version mismatch: tool is v${o.version}, target is v${r}`)}return o.metadata?.deprecated&&(s.push("This tool is marked as deprecated"),a.push("Consider using an alternative tool if available")),o.annotations?.securityLevel==="restricted"&&a.push("This tool requires elevated permissions"),{compatible:i.length===0,issues:i,warnings:s,recommendations:a}}getTool(e,t){return this.toolRegistry.get(this.createToolKey(e,t))}getAllTools(){return Array.from(this.toolRegistry.values())}getServerTools(e){const t=this.serverToolsMap.get(e);return t?Array.from(t).map(r=>this.getTool(e,r)).filter(r=>r!==void 0):[]}clearServerTools(e){const t=this.serverToolsMap.get(e);if(t){for(const r of t)this.toolRegistry.delete(this.createToolKey(e,r));this.serverToolsMap.delete(e)}}createToolKey(e,t){return`${e}:${t}`}getStatistics(){const e={},t={},r={safe:0,moderate:0,dangerous:0};let n=0,o=0;for(const i of this.toolRegistry.values()){e[i.serverId]=(e[i.serverId]??0)+1;const s=i.metadata?.category??"general";t[s]=(t[s]??0)+1,i.annotations?.destructiveHint?r.dangerous++:i.annotations?.readOnlyHint?r.safe++:r.moderate++,i.annotations&&Object.keys(i.annotations).length>0&&n++,i.metadata?.deprecated&&o++}return{totalTools:this.toolRegistry.size,toolsByServer:e,toolsByCategory:t,toolsBySafetyLevel:r,toolsWithAnnotations:n,deprecatedTools:o}}}}}),obr,T0e,E0e,O4,S0e=E({"src/lib/mcp/mcpCircuitBreaker.ts"(){"use strict";To(),Gt(),G(),ft(),ft(),obr=Math.max(1e4,Number(process.env.MCP_OPERATION_TIMEOUT)||6e4),T0e=class extends On{constructor(e,t={}){super(),this.name=e,this.config={failureThreshold:t.failureThreshold??5,resetTimeout:t.resetTimeout??6e4,halfOpenMaxCalls:t.halfOpenMaxCalls??3,operationTimeout:t.operationTimeout??obr,minimumCallsBeforeCalculation:t.minimumCallsBeforeCalculation??10,statisticsWindowSize:t.statisticsWindowSize??3e5},this.cleanupTimer=setInterval(()=>this.cleanupCallHistory(),6e4),this.cleanupTimer.unref&&this.cleanupTimer.unref()}name;state="closed";config;callHistory=[];lastFailureTime=0;halfOpenCalls=0;lastStateChange=new Date;cleanupTimer;async execute(e){const t=Date.now();try{if(this.state==="open"){const i=this.config.resetTimeout-(Date.now()-this.lastFailureTime);if(i>0)throw new ef({breakerName:this.name,retryAfter:new Date(this.lastFailureTime+this.config.resetTimeout),retryAfterMs:i,breakerState:"open",failureCount:this.getStats().failedCalls});this.changeState("half-open","Reset timeout reached")}if(this.state==="half-open"&&this.halfOpenCalls>=this.config.halfOpenMaxCalls)throw this.lastFailureTime=Date.now(),this.changeState("open","Half-open call limit reached, reverting to open"),new ef({breakerName:this.name,retryAfter:new Date(this.lastFailureTime+this.config.resetTimeout),retryAfterMs:this.config.resetTimeout,breakerState:"open",failureCount:this.getStats().failedCalls});if(this.state==="half-open"){const i=Xt.getActiveSpan();i&&i.addEvent("circuit.half_open_test",{"circuit.name":this.name,"circuit.half_open_call":this.halfOpenCalls+1,"circuit.half_open_max_calls":this.config.halfOpenMaxCalls})}let r;const n=i=>{r=i||"Operation resolved a failure result"},o=await this.raceWithTimeout(e(n),this.config.operationTimeout);return r!==void 0?(this.recordFailureOutcome(r,Date.now()-t),o):(this.recordCall(!0,Date.now()-t),this.state==="half-open"&&(this.halfOpenCalls++,this.halfOpenCalls>=this.config.halfOpenMaxCalls&&this.changeState("closed","Half-open test successful")),o)}catch(r){const n=Date.now()-t,o=r instanceof Error?r.message:String(r);throw this.recordFailureOutcome(o,n),r}}recordFailureOutcome(e,t){this.recordCall(!1,t),this.emit("callFailure",{error:e,duration:t,timestamp:new Date}),this.state==="half-open"?this.changeState("open",`Half-open test failed: ${e}`):this.state==="closed"&&this.checkFailureThreshold()}recordCall(e,t){const r=Date.now();this.callHistory.push({timestamp:r,success:e,duration:t}),e&&this.emit("callSuccess",{duration:t,timestamp:new Date}),e||(this.lastFailureTime=r)}checkFailureThreshold(){const e=Date.now()-this.config.statisticsWindowSize,t=this.callHistory.filter(o=>o.timestamp>=e);if(t.length<this.config.minimumCallsBeforeCalculation)return;const r=t.filter(o=>!o.success).length,n=r/t.length;le.debug(`[CircuitBreaker:${this.name}] Failure rate: ${(n*100).toFixed(1)}% (${r}/${t.length})`),r>=this.config.failureThreshold&&(this.changeState("open",`Failure threshold exceeded: ${r} failures`),this.emit("circuitOpen",{failureRate:n,totalCalls:t.length,timestamp:new Date}))}changeState(e,t){const r=this.state;this.state=e,this.lastStateChange=new Date;const n=Xt.getActiveSpan();n&&n.addEvent("circuit.state_change",{"circuit.name":this.name,"circuit.from_state":r,"circuit.to_state":e,"circuit.reason":t.slice(0,128),"circuit.failure_count":this.callHistory.filter(o=>!o.success).length}),e==="half-open"?(this.halfOpenCalls=0,this.emit("circuitHalfOpen",{timestamp:new Date})):e==="closed"&&(this.halfOpenCalls=0,this.emit("circuitClosed",{timestamp:new Date})),le.info(`[CircuitBreaker:${this.name}] State changed: ${r} -> ${e} (${t})`),this.emit("stateChange",{oldState:r,newState:e,reason:t,timestamp:new Date})}async raceWithTimeout(e,t){let r;const n=new Promise((o,i)=>{r=setTimeout(()=>{i(new Error(`Operation timed out after ${t}ms`))},t)});try{return await Promise.race([e,n])}finally{clearTimeout(r)}}cleanupCallHistory(){const e=Date.now()-this.config.statisticsWindowSize,t=this.callHistory.length;this.callHistory=this.callHistory.filter(n=>n.timestamp>=e);const r=t-this.callHistory.length;r>0&&le.debug(`[CircuitBreaker:${this.name}] Cleaned up ${r} old call records`)}getStats(){const e=Date.now()-this.config.statisticsWindowSize,t=this.callHistory.filter(i=>i.timestamp>=e),r=t.filter(i=>i.success).length,n=t.length-r,o=t.length>0?n/t.length:0;return{state:this.state,totalCalls:this.callHistory.length,successfulCalls:this.callHistory.filter(i=>i.success).length,failedCalls:this.callHistory.filter(i=>!i.success).length,failureRate:o,windowCalls:t.length,lastStateChange:this.lastStateChange,nextRetryTime:this.state==="open"?new Date(this.lastFailureTime+this.config.resetTimeout):void 0,halfOpenCalls:this.halfOpenCalls}}reset(){this.changeState("closed","Manual reset"),this.callHistory=[],this.lastFailureTime=0,this.halfOpenCalls=0}forceOpen(e="Manual force open"){this.changeState("open",e),this.lastFailureTime=Date.now()}getName(){return this.name}isOpen(){return this.state==="open"}isClosed(){return this.state==="closed"}isHalfOpen(){return this.state==="half-open"}destroy(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0,le.debug(`[CircuitBreaker:${this.name}] Cleanup timer cleared`)),this.removeAllListeners(),this.callHistory=[],le.debug(`[CircuitBreaker:${this.name}] Destroyed and cleaned up`)}},E0e=class{breakers=new Map;getBreaker(e,t){if(!this.breakers.has(e)){const n=new T0e(e,t);this.breakers.set(e,n),le.debug(`[CircuitBreakerManager] Created circuit breaker: ${e}`)}const r=this.breakers.get(e);if(!r)throw new Error(`Circuit breaker ${e} not found after creation`);return r}removeBreaker(e){const t=this.breakers.get(e);return t?(t.destroy(),this.breakers.delete(e),le.debug(`[CircuitBreakerManager] Removed and cleaned up circuit breaker: ${e}`),!0):!1}getBreakerNames(){return Array.from(this.breakers.keys())}getAllStats(){const e={};for(const[t,r]of this.breakers)e[t]=r.getStats();return e}resetAll(){for(const e of this.breakers.values())e.reset();le.info("[CircuitBreakerManager] Reset all circuit breakers")}getHealthSummary(){let e=0,t=0,r=0;const n=[];for(const[o,i]of this.breakers)switch(i.getStats().state){case"closed":e++;break;case"open":t++,n.push(o);break;case"half-open":r++;break}return{totalBreakers:this.breakers.size,closedBreakers:e,openBreakers:t,halfOpenBreakers:r,unhealthyBreakers:n}}destroyAll(){for(const e of this.breakers.values())e.destroy();this.breakers.clear(),le.info("[CircuitBreakerManager] Destroyed all circuit breakers")}},O4=new E0e}});function eLn(e){return new Promise(t=>setTimeout(t,e))}function TB(e,t=Jp){return t.retryableStatusCodes.includes(e)}function ibr(e,t=Jp){if(!e||typeof e!="object")return!1;const r=e;if(cr(e))return!1;if(r.name==="TimeoutError"||r.code==="TIMEOUT"||r.code==="ETIMEDOUT"||r.code==="ECONNRESET"||r.code==="ENOTFOUND"||r.code==="ECONNREFUSED"||r.code==="ECONNABORTED"||r.code==="EPIPE"||r.code==="ENETUNREACH"||r.code==="EHOSTUNREACH")return!0;if(r.name==="TypeError"&&typeof r.message=="string"){const n=r.message.toLowerCase();if(n.includes("fetch")||n.includes("network")||n.includes("connection"))return!0}return typeof r.status=="number"?TB(r.status,t):r.response&&typeof r.response=="object"&&typeof r.response.status=="number"?TB(r.response.status,t):typeof r.statusCode=="number"?TB(r.statusCode,t):!1}async function sbr(e,t={}){const r={...Jp,...t},{traceId:n,parentSpanId:o}=Cy(),i=Oe.createSpan("mcp.transport","mcp.retry",{"mcp.transport":"http","mcp.operation":"retry","mcp.maxAttempts":r.maxAttempts},o,n),s=Date.now();let a,c=0;for(let u=1;u<=r.maxAttempts;u++){c=u;try{const d=await e();i.durationMs=Date.now()-s,i.attributes["mcp.retryAttempt"]=u;const p=Oe.endSpan(i,1);return pt().recordSpan(p),d}catch(d){if(a=d,u===r.maxAttempts){g.debug(`HTTP retry: All ${r.maxAttempts} attempts exhausted`);break}if(!ibr(d,r)){g.debug("HTTP retry: Non-retryable error encountered",d instanceof Error?d.message:String(d));break}const p=x2t(u,r.initialDelay,r.backoffMultiplier,r.maxDelay,!0),m=d instanceof Error?d.message:String(d);g.warn(`HTTP retry: Attempt ${u}/${r.maxAttempts} failed: ${m}. Retrying in ${Math.round(p)}ms...`),await eLn(p)}}i.durationMs=Date.now()-s,i.attributes["mcp.retryAttempt"]=c;const l=Oe.endSpan(i,2);throw l.statusMessage=a instanceof Error?a.message:String(a),pt().recordSpan(l),a}var Jp,abr=E({"src/lib/mcp/httpRetryHandler.ts"(){"use strict";st(),O2t(),G(),wo(),xy(),Jp={maxAttempts:3,initialDelay:1e3,maxDelay:3e4,backoffMultiplier:2,retryableStatusCodes:[408,429,500,502,503,504]}}}),k0e,A0e,C0e,x0e,cbr=E({"src/lib/mcp/httpRateLimiter.ts"(){"use strict";G(),HC(),wo(),xy(),k0e={requestsPerWindow:60,windowMs:6e4,useTokenBucket:!0,refillRate:1,maxBurst:10},A0e=class{tokens;lastRefill;config;waitQueue=[];processingQueue=!1;constructor(e={}){this.config={...k0e,...e},this.tokens=this.config.maxBurst,this.lastRefill=Date.now(),le.debug("[HTTPRateLimiter] Initialized with config:",{requestsPerWindow:this.config.requestsPerWindow,windowMs:this.config.windowMs,useTokenBucket:this.config.useTokenBucket,refillRate:this.config.refillRate,maxBurst:this.config.maxBurst})}refillTokens(){const e=Date.now(),n=(e-this.lastRefill)/1e3*this.config.refillRate;if(n>=1){const o=this.tokens;this.tokens=Math.min(this.config.maxBurst,this.tokens+n),this.lastRefill=e,this.tokens>o&&le.debug(`[HTTPRateLimiter] Refilled tokens: ${o.toFixed(2)} -> ${this.tokens.toFixed(2)} (+${n.toFixed(2)})`)}}async acquire(){const{traceId:e,parentSpanId:t}=Cy(),r=Oe.createSpan("mcp.transport","mcp.rateLimit",{"mcp.transport":"http","mcp.operation":"rateLimit","mcp.rateLimit.tokensAvailable":this.tokens,"mcp.rateLimit.maxBurst":this.config.maxBurst},t,e),n=Date.now();try{if(this.tryAcquire()){r.durationMs=Date.now()-n,r.attributes["mcp.rateLimit.waited"]=!1;const i=Oe.endSpan(r,1);pt().recordSpan(i);return}await new Promise((i,s)=>{this.waitQueue.push({resolve:i,reject:s}),le.debug(`[HTTPRateLimiter] Request queued, queue length: ${this.waitQueue.length}`),this.processingQueue||this.processQueue()}),r.durationMs=Date.now()-n,r.attributes["mcp.rateLimit.waited"]=!0;const o=Oe.endSpan(r,1);pt().recordSpan(o)}catch(o){r.durationMs=Date.now()-n;const i=Oe.endSpan(r,2);throw i.statusMessage=o instanceof Error?o.message:String(o),pt().recordSpan(i),o}}async processQueue(){if(!this.processingQueue){for(this.processingQueue=!0;this.waitQueue.length>0;)if(this.refillTokens(),this.tokens>=1){const e=this.waitQueue.shift();e&&(this.tokens-=1,le.debug(`[HTTPRateLimiter] Token granted from queue, remaining: ${this.tokens.toFixed(2)}, queue: ${this.waitQueue.length}`),e.resolve())}else{const t=(1-this.tokens)/this.config.refillRate*1e3,r=Math.max(10,Math.ceil(t));le.debug(`[HTTPRateLimiter] Waiting ${r}ms for token refill`),await this.sleep(r)}this.processingQueue=!1}}sleep(e){return new Promise(t=>setTimeout(t,e))}tryAcquire(){return this.refillTokens(),this.tokens>=1?(this.tokens-=1,le.debug(`[HTTPRateLimiter] Token acquired, remaining: ${this.tokens.toFixed(2)}`),!0):(le.debug(`[HTTPRateLimiter] No tokens available, current: ${this.tokens.toFixed(2)}`),!1)}handleRateLimitResponse(e){const t=Sb(e),r=e.get("Retry-After");if(r&&t!==void 0){const i=parseInt(r,10);if(isNaN(i)){const s=new Date(r);if(!isNaN(s.getTime()))return le.info(`[HTTPRateLimiter] Server requested retry at ${s.toISOString()} (${t}ms)`),t}else return le.info(`[HTTPRateLimiter] Server requested retry after ${i} seconds`),t}const n=e.get("X-RateLimit-Reset");if(n&&t!==void 0){const i=parseInt(n,10);if(!isNaN(i)){const s=i>1e12?i:i*1e3;return le.info(`[HTTPRateLimiter] Rate limit resets at ${new Date(s).toISOString()} (${t}ms)`),t}}return e.get("X-RateLimit-Remaining")==="0"&&t!==void 0?(le.info(`[HTTPRateLimiter] Rate limit exhausted, using default backoff: ${t}ms`),t):t??0}getRemainingTokens(){return this.refillTokens(),this.tokens}reset(){for(this.tokens=this.config.maxBurst,this.lastRefill=Date.now();this.waitQueue.length>0;){const e=this.waitQueue.shift();e&&e.reject(new Error("Rate limiter was reset"))}le.info(`[HTTPRateLimiter] Reset to initial state, tokens: ${this.tokens}`)}getStats(){return this.refillTokens(),{tokens:this.tokens,maxBurst:this.config.maxBurst,refillRate:this.config.refillRate,queueLength:this.waitQueue.length,lastRefill:new Date(this.lastRefill)}}updateConfig(e){Object.assign(this.config,e),le.info("[HTTPRateLimiter] Configuration updated:",e)}getConfig(){return{...this.config}}},C0e=class{limiters=new Map;getLimiter(e,t){let r=this.limiters.get(e);return r?t&&r.updateConfig(t):(r=new A0e(t),this.limiters.set(e,r),le.debug(`[RateLimiterManager] Created rate limiter for server: ${e}`)),r}hasLimiter(e){return this.limiters.has(e)}removeLimiter(e){const t=this.limiters.get(e);t&&(t.reset(),this.limiters.delete(e),le.debug(`[RateLimiterManager] Removed rate limiter for server: ${e}`))}getServerIds(){return Array.from(this.limiters.keys())}getAllStats(){const e={};for(const[t,r]of this.limiters)e[t]=r.getStats();return e}resetAll(){for(const e of this.limiters.values())e.reset();le.info("[RateLimiterManager] Reset all rate limiters")}destroyAll(){for(const e of this.limiters.values())e.reset();this.limiters.clear(),le.info("[RateLimiterManager] Destroyed all rate limiters")}getHealthSummary(){const e=[];let t=0,r=0;for(const[o,i]of this.limiters){const s=i.getStats();s.queueLength>0&&(e.push(o),t+=s.queueLength),r+=s.tokens}const n=this.limiters.size>0?r/this.limiters.size:0;return{totalLimiters:this.limiters.size,serversWithQueuedRequests:e,totalQueuedRequests:t,averageTokensAvailable:n}}},x0e=new C0e}});function lbr(e,t=60){if(!e.expiresAt)return!1;const r=t*1e3,n=Date.now();return e.expiresAt-r<=n}function I0e(e){return Date.now()+e*1e3}var EB,ubr,dbr=E({"src/lib/mcp/auth/tokenStorage.ts"(){"use strict";G(),EB=class{tokens=new Map;async getTokens(e){return this.tokens.get(e)??null}async saveTokens(e,t){this.tokens.set(e,t)}async deleteTokens(e){this.tokens.delete(e)}async hasTokens(e){return this.tokens.has(e)}async clearAll(){this.tokens.clear()}get size(){return this.tokens.size}getServerIds(){return Array.from(this.tokens.keys())}},ubr=class{filePath;tokens=new Map;loaded=!1;constructor(e){this.filePath=e}async loadTokens(){if(!this.loaded)try{const t=await(await Promise.resolve().then(()=>(Fi(),Xy))).readFile(this.filePath,"utf-8"),r=JSON.parse(t);this.tokens=new Map(Object.entries(r)),this.loaded=!0}catch(e){e instanceof Error&&"code"in e&&e.code!=="ENOENT"&&g.warn(`[FileTokenStorage] Error loading tokens: ${e.message}`),this.tokens=new Map,this.loaded=!0}}async saveToFile(){try{const e=await Promise.resolve().then(()=>(Fi(),Xy)),t=await Promise.resolve().then(()=>(Nr(),qh)),{randomBytes:r}=await Promise.resolve().then(()=>(tr(),Ew)),n=t.dirname(this.filePath);await e.mkdir(n,{recursive:!0,mode:448});const o=Object.fromEntries(this.tokens.entries()),i=`${this.filePath}.${process.pid}.${r(6).toString("hex")}.tmp`;try{await e.writeFile(i,JSON.stringify(o,null,2),{encoding:"utf-8",mode:384,flag:"wx"}),await e.rename(i,this.filePath),await e.chmod(this.filePath,384)}catch(s){throw await e.rm(i,{force:!0}),s}}catch(e){throw g.error(`[FileTokenStorage] Error saving tokens: ${e instanceof Error?e.message:String(e)}`),e}}async getTokens(e){return await this.loadTokens(),this.tokens.get(e)??null}async saveTokens(e,t){await this.loadTokens(),this.tokens.set(e,t),await this.saveToFile()}async deleteTokens(e){await this.loadTokens(),this.tokens.delete(e),await this.saveToFile()}async hasTokens(e){return await this.loadTokens(),this.tokens.has(e)}async clearAll(){this.tokens.clear(),await this.saveToFile()}}}});function tLn(e,t){return new SB({clientId:e.clientId,clientSecret:e.clientSecret,authorizationUrl:e.authorizationUrl,tokenUrl:e.tokenUrl,redirectUrl:e.redirectUrl,scope:e.scope,usePKCE:e.usePKCE??!0},t)}var r_,SB,rLn=E({"src/lib/mcp/auth/oauthClientProvider.ts"(){"use strict";tr(),dbr(),G(),st(),r_=3e4,SB=class{config;storage;pendingChallenges=new Map;pendingStates=new Set;constructor(e,t){this.config={...e,usePKCE:e.usePKCE??!0},this.storage=t??new EB}async tokens(e){const t=await this.storage.getTokens(e);if(!t)return null;if(lbr(t)){if(t.refreshToken)try{return await this.refreshTokens(e,t.refreshToken)}catch(r){return g.warn(`[NeuroLinkOAuthProvider] Token refresh failed: ${r instanceof Error?r.message:String(r)}`),await this.storage.deleteTokens(e),null}return await this.storage.deleteTokens(e),null}return t}async saveTokens(e,t){await this.storage.saveTokens(e,t)}async deleteTokens(e){await this.storage.deleteTokens(e)}clientInformation(){return{clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:this.config.redirectUrl}}redirectToAuthorization(e){const t=this.generateState();this.pendingStates.add(t);const r=new URL(this.config.authorizationUrl);r.searchParams.set("response_type","code"),r.searchParams.set("client_id",this.config.clientId),r.searchParams.set("redirect_uri",this.config.redirectUrl),r.searchParams.set("state",t),this.config.scope&&r.searchParams.set("scope",this.config.scope);let n;if(this.config.usePKCE){const o=this.generatePKCE();n=o.codeVerifier,this.pendingChallenges.set(t,o),r.searchParams.set("code_challenge",o.codeChallenge),r.searchParams.set("code_challenge_method",o.codeChallengeMethod)}if(this.config.additionalParams)for(const[o,i]of Object.entries(this.config.additionalParams))r.searchParams.set(o,i);return{url:r.toString(),state:t,codeVerifier:n}}async exchangeCode(e,t){if(!this.pendingStates.has(t.state))throw new Error("Invalid or expired state parameter");this.pendingStates.delete(t.state);let r=t.codeVerifier;if(this.config.usePKCE&&!r){const a=this.pendingChallenges.get(t.state);a&&(r=a.codeVerifier,this.pendingChallenges.delete(t.state))}const n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",t.code),n.set("redirect_uri",this.config.redirectUrl),n.set("client_id",this.config.clientId),this.config.clientSecret&&n.set("client_secret",this.config.clientSecret),r&&n.set("code_verifier",r);const o=await Je(fetch(this.config.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:n.toString()}),r_,new Error(`OAuth token exchange timed out after ${r_}ms`));if(!o.ok){const a=await o.text();throw new Error(`Token exchange failed: ${o.status} ${o.statusText} - ${a}`)}const i=await o.json(),s={accessToken:i.access_token,refreshToken:i.refresh_token,expiresAt:i.expires_in?I0e(i.expires_in):void 0,tokenType:i.token_type??"Bearer",scope:i.scope};return await this.saveTokens(e,s),s}async refreshTokens(e,t){const r=new URLSearchParams;r.set("grant_type","refresh_token"),r.set("refresh_token",t),r.set("client_id",this.config.clientId),this.config.clientSecret&&r.set("client_secret",this.config.clientSecret);const n=await Je(fetch(this.config.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:r.toString()}),r_,new Error(`OAuth token refresh timed out after ${r_}ms`));if(!n.ok){const s=await n.text();throw new Error(`Token refresh failed: ${n.status} ${n.statusText} - ${s}`)}const o=await n.json(),i={accessToken:o.access_token,refreshToken:o.refresh_token??t,expiresAt:o.expires_in?I0e(o.expires_in):void 0,tokenType:o.token_type??"Bearer",scope:o.scope};return await this.saveTokens(e,i),i}async revokeTokens(e,t){const r=await this.storage.getTokens(e);if(!r)return;const n=new URLSearchParams;n.set("token",r.accessToken),n.set("client_id",this.config.clientId),this.config.clientSecret&&n.set("client_secret",this.config.clientSecret);try{await Je(fetch(t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()}),r_,new Error(`OAuth token revocation timed out after ${r_}ms`))}catch(o){g.warn(`[NeuroLinkOAuthProvider] Token revocation failed: ${o instanceof Error?o.message:String(o)}`)}await this.storage.deleteTokens(e)}async getAuthorizationHeader(e){const t=await this.tokens(e);return t?`${t.tokenType} ${t.accessToken}`:null}async hasValidTokens(e){return await this.tokens(e)!==null}generateState(){return f0(32).toString("base64url")}generatePKCE(){const e=f0(32).toString("base64url"),t=Bu("sha256").update(e).digest("base64url");return{codeVerifier:e,codeChallenge:t,codeChallengeMethod:"S256"}}getConfig(){return{...this.config}}getStorage(){return this.storage}cleanupPendingRequests(){this.pendingStates.size>100&&this.pendingStates.clear(),this.pendingChallenges.size>100&&this.pendingChallenges.clear()}}}}),pbr=E({"src/lib/mcp/auth/index.ts"(){"use strict";dbr(),rLn()}});function nLn(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function oLn(e){const t=e.endsWith(".")?e.slice(0,-1):e;return t==="localhost"||t.endsWith(".localhost")}function R0e(e){const t=CT(e);if(t===0)throw new Error(`"${e}" is not an IP address`);const r=t===4?"ipv4":"ipv6";return kB.check(e,r)?"loopback":nc.check(e,r)?"private":"public"}function gd(e){return e.serverId?`MCP server "${e.serverId}" (${e.transport})`:`MCP ${e.transport} transport`}async function iLn(e){return(await u$(e,{all:!0,verbatim:!0})).map(r=>r.address)}async function mbr(e,t){let r;try{r=new URL(e)}catch{throw new Error(`${gd(t)}: "${e}" is not a valid URL`)}const n=r.protocol,o=fbr.has(n);if(!o&&!hbr.has(n))throw new Error(`${gd(t)}: scheme "${n}" is not allowed (use https:, wss:, or http:/ws: for a loopback host)`);const i=nLn(r.hostname).toLowerCase();if(i.length===0)throw new Error(`${gd(t)}: "${e}" has no host`);if(t.hostOwnedEgress===!0)return;const s=t.allowPrivateNetwork===!0,a=oLn(i)?"loopback":CT(i)!==0?R0e(i):void 0;if(a!==void 0){if(a==="loopback")return;if(!s){if(a==="private")throw new Error(`${gd(t)}: "${e}" points at a private, link-local or metadata address; set "allowPrivateNetwork": true on this server if that is intended`);if(!o)throw new Error(`${gd(t)}: "${e}" uses plaintext ${n} to a non-loopback host; use ${n==="ws:"?"wss:":"https:"}`);return}if(a==="public"&&!o)throw new Error(`${gd(t)}: "${e}" uses plaintext ${n} to a public host; allowPrivateNetwork only permits plaintext to private addresses`);return}if(!o&&!s)throw new Error(`${gd(t)}: "${e}" uses plaintext ${n} to a non-loopback host; use ${n==="ws:"?"wss:":"https:"}, or set "allowPrivateNetwork": true for a server on your own network`);let c;try{c=await iLn(i)}catch(u){throw new Error(`${gd(t)}: host "${i}" could not be resolved (${u instanceof Error?u.message:String(u)})`,{cause:u})}if(c.length===0)throw new Error(`${gd(t)}: host "${i}" resolved to no addresses`);const l=c.map(u=>({address:u,cls:R0e(u)}));if(!s){const u=l.find(d=>d.cls!=="public");if(u)throw new Error(`${gd(t)}: host "${i}" resolves to ${u.address}, a ${u.cls} address; set "allowPrivateNetwork": true on this server if that is intended`);return}if(!o&&l.some(u=>u.cls==="public"))throw new Error(`${gd(t)}: "${e}" uses plaintext ${n} to a host that resolves to a public address; allowPrivateNetwork only permits plaintext to private addresses`)}var hbr,fbr,kB,nc,gbr=E({"src/lib/mcp/transportUrlPolicy.ts"(){"use strict";rPt(),_se(),hbr=new Set(["http:","ws:"]),fbr=new Set(["https:","wss:"]),kB=new yse,kB.addSubnet("127.0.0.0",8,"ipv4"),kB.addAddress("::1","ipv6"),nc=new yse,nc.addSubnet("0.0.0.0",8,"ipv4"),nc.addSubnet("10.0.0.0",8,"ipv4"),nc.addSubnet("100.64.0.0",10,"ipv4"),nc.addSubnet("169.254.0.0",16,"ipv4"),nc.addSubnet("172.16.0.0",12,"ipv4"),nc.addSubnet("192.0.0.0",24,"ipv4"),nc.addSubnet("192.168.0.0",16,"ipv4"),nc.addSubnet("198.18.0.0",15,"ipv4"),nc.addSubnet("224.0.0.0",4,"ipv4"),nc.addSubnet("240.0.0.0",4,"ipv4"),nc.addAddress("::","ipv6"),nc.addSubnet("fc00::",7,"ipv6"),nc.addSubnet("fe80::",10,"ipv6")}}),sLn=E({"node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/mini/parse.js"(){dc()}}),aLn=E({"node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/mini/schemas.js"(){}}),cLn=E({"node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/mini/checks.js"(){}}),lLn=E({"node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/mini/iso.js"(){}}),uLn=E({"node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/mini/coerce.js"(){}}),dLn=E({"node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/mini/external.js"(){dc(),sLn(),aLn(),cLn(),XH(),lLn(),uLn()}}),pLn=E({"node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4-mini/index.js"(){dLn()}});function M0e(e){return!!e._zod}function Eg(e,t){return M0e(e)?yj(e,t):e.safeParse(t)}function ybr(e){if(!e)return;let t;if(M0e(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function vbr(e){if(M0e(e)){const i=e._zod?.def;if(i){if(i.value!==void 0)return i.value;if(Array.isArray(i.values)&&i.values.length>0)return i.values[0]}}const r=e._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}const n=e.value;if(n!==void 0)return n}var P0e=E({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js"(){pLn()}}),mLn=E({"node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/index.js"(){_J()}}),_br=E({"node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/index.js"(){mLn()}}),D4,wbr,Sg,N4,us,O0e,D0e,hLn,bbr,Tbr,AB,Bc,uS,Ebr,Xs,Pl,Ol,Ys,L4,N0e,CB,L0e,Sbr,xB,dS,rr,IB,kbr,n_,fLn,o_,Abr,RB,Cbr,pS,i_,$0e,xbr,Ibr,Rbr,Mbr,Pbr,Obr,Dbr,Nbr,F0e,U0e,Lbr,MB,$br,Fbr,PB,Ubr,mS,hS,Bbr,fS,gS,zbr,$4,OB,DB,NB,gLn,LB,$B,FB,qbr,B0e,z0e,UB,q0e,yS,s_,G0e,Gbr,jbr,j0e,Vbr,V0e,BB,Hbr,Wbr,H0e,W0e,Kbr,Jbr,Xbr,Ybr,Zbr,Qbr,eTr,tTr,rTr,K0e,nTr,oTr,zB,qB,GB,iTr,sTr,aTr,jB,cTr,J0e,X0e,lTr,uTr,Y0e,dTr,Z0e,F4,yLn,pTr,mTr,Q0e,hTr,eye,fTr,gTr,yTr,vTr,_Tr,wTr,bTr,TTr,ETr,U4,STr,kTr,tye,rye,nye,ATr,CTr,xTr,ITr,RTr,MTr,PTr,OTr,DTr,NTr,LTr,$Tr,FTr,UTr,BTr,oye,zTr,qTr,iye,GTr,jTr,VTr,HTr,sye,WTr,KTr,JTr,XTr,vLn,_Ln,wLn,bLn,TLn,ELn,Wt,YTr,kg=E({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js"(){_br(),D4="2025-11-25",wbr=[D4,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Sg="io.modelcontextprotocol/related-task",N4="2.0",us=sJ(e=>e!==null&&(typeof e=="object"||typeof e=="function")),O0e=Mn([ce(),Yr().int()]),D0e=ce(),hLn=Ts({ttl:Yr().optional(),pollInterval:Yr().optional()}),bbr=mt({ttl:Yr().optional()}),Tbr=mt({taskId:ce()}),AB=Ts({progressToken:O0e.optional(),[Sg]:Tbr.optional()}),Bc=mt({_meta:AB.optional()}),uS=Bc.extend({task:bbr.optional()}),Ebr=e=>uS.safeParse(e).success,Xs=mt({method:ce(),params:Bc.loose().optional()}),Pl=mt({_meta:AB.optional()}),Ol=mt({method:ce(),params:Pl.loose().optional()}),Ys=Ts({_meta:AB.optional()}),L4=Mn([ce(),Yr().int()]),N0e=mt({jsonrpc:Mt(N4),id:L4,...Xs.shape}).strict(),CB=e=>N0e.safeParse(e).success,L0e=mt({jsonrpc:Mt(N4),...Ol.shape}).strict(),Sbr=e=>L0e.safeParse(e).success,xB=mt({jsonrpc:Mt(N4),id:L4,result:Ys}).strict(),dS=e=>xB.safeParse(e).success,(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(rr||(rr={})),IB=mt({jsonrpc:Mt(N4),id:L4.optional(),error:mt({code:Yr().int(),message:ce(),data:Bn().optional()})}).strict(),kbr=e=>IB.safeParse(e).success,n_=Mn([N0e,L0e,xB,IB]),fLn=Mn([xB,IB]),o_=Ys.strict(),Abr=Pl.extend({requestId:L4.optional(),reason:ce().optional()}),RB=Ol.extend({method:Mt("notifications/cancelled"),params:Abr}),Cbr=mt({src:ce(),mimeType:ce().optional(),sizes:ct(ce()).optional(),theme:_a(["light","dark"]).optional()}),pS=mt({icons:ct(Cbr).optional()}),i_=mt({name:ce(),title:ce().optional()}),$0e=i_.extend({...i_.shape,...pS.shape,version:ce(),websiteUrl:ce().optional(),description:ce().optional()}),xbr=tC(mt({applyDefaults:Rn().optional()}),Pn(ce(),Bn())),Ibr=zD(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,tC(mt({form:xbr.optional(),url:us.optional()}),Pn(ce(),Bn()).optional())),Rbr=Ts({list:us.optional(),cancel:us.optional(),requests:Ts({sampling:Ts({createMessage:us.optional()}).optional(),elicitation:Ts({create:us.optional()}).optional()}).optional()}),Mbr=Ts({list:us.optional(),cancel:us.optional(),requests:Ts({tools:Ts({call:us.optional()}).optional()}).optional()}),Pbr=mt({experimental:Pn(ce(),us).optional(),sampling:mt({context:us.optional(),tools:us.optional()}).optional(),elicitation:Ibr.optional(),roots:mt({listChanged:Rn().optional()}).optional(),tasks:Rbr.optional(),extensions:Pn(ce(),us).optional()}),Obr=Bc.extend({protocolVersion:ce(),capabilities:Pbr,clientInfo:$0e}),Dbr=Xs.extend({method:Mt("initialize"),params:Obr}),Nbr=mt({experimental:Pn(ce(),us).optional(),logging:us.optional(),completions:us.optional(),prompts:mt({listChanged:Rn().optional()}).optional(),resources:mt({subscribe:Rn().optional(),listChanged:Rn().optional()}).optional(),tools:mt({listChanged:Rn().optional()}).optional(),tasks:Mbr.optional(),extensions:Pn(ce(),us).optional()}),F0e=Ys.extend({protocolVersion:ce(),capabilities:Nbr,serverInfo:$0e,instructions:ce().optional()}),U0e=Ol.extend({method:Mt("notifications/initialized"),params:Pl.optional()}),Lbr=e=>U0e.safeParse(e).success,MB=Xs.extend({method:Mt("ping"),params:Bc.optional()}),$br=mt({progress:Yr(),total:zn(Yr()),message:zn(ce())}),Fbr=mt({...Pl.shape,...$br.shape,progressToken:O0e}),PB=Ol.extend({method:Mt("notifications/progress"),params:Fbr}),Ubr=Bc.extend({cursor:D0e.optional()}),mS=Xs.extend({params:Ubr.optional()}),hS=Ys.extend({nextCursor:D0e.optional()}),Bbr=_a(["working","input_required","completed","failed","cancelled"]),fS=mt({taskId:ce(),status:Bbr,ttl:Mn([Yr(),ND()]),createdAt:ce(),lastUpdatedAt:ce(),pollInterval:zn(Yr()),statusMessage:zn(ce())}),gS=Ys.extend({task:fS}),zbr=Pl.merge(fS),$4=Ol.extend({method:Mt("notifications/tasks/status"),params:zbr}),OB=Xs.extend({method:Mt("tasks/get"),params:Bc.extend({taskId:ce()})}),DB=Ys.merge(fS),NB=Xs.extend({method:Mt("tasks/result"),params:Bc.extend({taskId:ce()})}),gLn=Ys.loose(),LB=mS.extend({method:Mt("tasks/list")}),$B=hS.extend({tasks:ct(fS)}),FB=Xs.extend({method:Mt("tasks/cancel"),params:Bc.extend({taskId:ce()})}),qbr=Ys.merge(fS),B0e=mt({uri:ce(),mimeType:zn(ce()),_meta:Pn(ce(),Bn()).optional()}),z0e=B0e.extend({text:ce()}),UB=ce().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),q0e=B0e.extend({blob:UB}),yS=_a(["user","assistant"]),s_=mt({audience:ct(yS).optional(),priority:Yr().min(0).max(1).optional(),lastModified:bN.datetime({offset:!0}).optional()}),G0e=mt({...i_.shape,...pS.shape,uri:ce(),description:zn(ce()),mimeType:zn(ce()),size:zn(Yr()),annotations:s_.optional(),_meta:zn(Ts({}))}),Gbr=mt({...i_.shape,...pS.shape,uriTemplate:ce(),description:zn(ce()),mimeType:zn(ce()),annotations:s_.optional(),_meta:zn(Ts({}))}),jbr=mS.extend({method:Mt("resources/list")}),j0e=hS.extend({resources:ct(G0e)}),Vbr=mS.extend({method:Mt("resources/templates/list")}),V0e=hS.extend({resourceTemplates:ct(Gbr)}),BB=Bc.extend({uri:ce()}),Hbr=BB,Wbr=Xs.extend({method:Mt("resources/read"),params:Hbr}),H0e=Ys.extend({contents:ct(Mn([z0e,q0e]))}),W0e=Ol.extend({method:Mt("notifications/resources/list_changed"),params:Pl.optional()}),Kbr=BB,Jbr=Xs.extend({method:Mt("resources/subscribe"),params:Kbr}),Xbr=BB,Ybr=Xs.extend({method:Mt("resources/unsubscribe"),params:Xbr}),Zbr=Pl.extend({uri:ce()}),Qbr=Ol.extend({method:Mt("notifications/resources/updated"),params:Zbr}),eTr=mt({name:ce(),description:zn(ce()),required:zn(Rn())}),tTr=mt({...i_.shape,...pS.shape,description:zn(ce()),arguments:zn(ct(eTr)),_meta:zn(Ts({}))}),rTr=mS.extend({method:Mt("prompts/list")}),K0e=hS.extend({prompts:ct(tTr)}),nTr=Bc.extend({name:ce(),arguments:Pn(ce(),ce()).optional()}),oTr=Xs.extend({method:Mt("prompts/get"),params:nTr}),zB=mt({type:Mt("text"),text:ce(),annotations:s_.optional(),_meta:Pn(ce(),Bn()).optional()}),qB=mt({type:Mt("image"),data:UB,mimeType:ce(),annotations:s_.optional(),_meta:Pn(ce(),Bn()).optional()}),GB=mt({type:Mt("audio"),data:UB,mimeType:ce(),annotations:s_.optional(),_meta:Pn(ce(),Bn()).optional()}),iTr=mt({type:Mt("tool_use"),name:ce(),id:ce(),input:Pn(ce(),Bn()),_meta:Pn(ce(),Bn()).optional()}),sTr=mt({type:Mt("resource"),resource:Mn([z0e,q0e]),annotations:s_.optional(),_meta:Pn(ce(),Bn()).optional()}),aTr=G0e.extend({type:Mt("resource_link")}),jB=Mn([zB,qB,GB,aTr,sTr]),cTr=mt({role:yS,content:jB}),J0e=Ys.extend({description:ce().optional(),messages:ct(cTr)}),X0e=Ol.extend({method:Mt("notifications/prompts/list_changed"),params:Pl.optional()}),lTr=mt({title:ce().optional(),readOnlyHint:Rn().optional(),destructiveHint:Rn().optional(),idempotentHint:Rn().optional(),openWorldHint:Rn().optional()}),uTr=mt({taskSupport:_a(["required","optional","forbidden"]).optional()}),Y0e=mt({...i_.shape,...pS.shape,description:ce().optional(),inputSchema:mt({type:Mt("object"),properties:Pn(ce(),us).optional(),required:ct(ce()).optional()}).catchall(Bn()),outputSchema:mt({type:Mt("object"),properties:Pn(ce(),us).optional(),required:ct(ce()).optional()}).catchall(Bn()).optional(),annotations:lTr.optional(),execution:uTr.optional(),_meta:Pn(ce(),Bn()).optional()}),dTr=mS.extend({method:Mt("tools/list")}),Z0e=hS.extend({tools:ct(Y0e)}),F4=Ys.extend({content:ct(jB).default([]),structuredContent:Pn(ce(),Bn()).optional(),isError:Rn().optional()}),yLn=F4.or(Ys.extend({toolResult:Bn()})),pTr=uS.extend({name:ce(),arguments:Pn(ce(),Bn()).optional()}),mTr=Xs.extend({method:Mt("tools/call"),params:pTr}),Q0e=Ol.extend({method:Mt("notifications/tools/list_changed"),params:Pl.optional()}),hTr=mt({autoRefresh:Rn().default(!0),debounceMs:Yr().int().nonnegative().default(300)}),eye=_a(["debug","info","notice","warning","error","critical","alert","emergency"]),fTr=Bc.extend({level:eye}),gTr=Xs.extend({method:Mt("logging/setLevel"),params:fTr}),yTr=Pl.extend({level:eye,logger:ce().optional(),data:Bn()}),vTr=Ol.extend({method:Mt("notifications/message"),params:yTr}),_Tr=mt({name:ce().optional()}),wTr=mt({hints:ct(_Tr).optional(),costPriority:Yr().min(0).max(1).optional(),speedPriority:Yr().min(0).max(1).optional(),intelligencePriority:Yr().min(0).max(1).optional()}),bTr=mt({mode:_a(["auto","required","none"]).optional()}),TTr=mt({type:Mt("tool_result"),toolUseId:ce().describe("The unique identifier for the corresponding tool call."),content:ct(jB).default([]),structuredContent:mt({}).loose().optional(),isError:Rn().optional(),_meta:Pn(ce(),Bn()).optional()}),ETr=$D("type",[zB,qB,GB]),U4=$D("type",[zB,qB,GB,iTr,TTr]),STr=mt({role:yS,content:Mn([U4,ct(U4)]),_meta:Pn(ce(),Bn()).optional()}),kTr=uS.extend({messages:ct(STr),modelPreferences:wTr.optional(),systemPrompt:ce().optional(),includeContext:_a(["none","thisServer","allServers"]).optional(),temperature:Yr().optional(),maxTokens:Yr().int(),stopSequences:ct(ce()).optional(),metadata:us.optional(),tools:ct(Y0e).optional(),toolChoice:bTr.optional()}),tye=Xs.extend({method:Mt("sampling/createMessage"),params:kTr}),rye=Ys.extend({model:ce(),stopReason:zn(_a(["endTurn","stopSequence","maxTokens"]).or(ce())),role:yS,content:ETr}),nye=Ys.extend({model:ce(),stopReason:zn(_a(["endTurn","stopSequence","maxTokens","toolUse"]).or(ce())),role:yS,content:Mn([U4,ct(U4)])}),ATr=mt({type:Mt("boolean"),title:ce().optional(),description:ce().optional(),default:Rn().optional()}),CTr=mt({type:Mt("string"),title:ce().optional(),description:ce().optional(),minLength:Yr().optional(),maxLength:Yr().optional(),format:_a(["email","uri","date","date-time"]).optional(),default:ce().optional()}),xTr=mt({type:_a(["number","integer"]),title:ce().optional(),description:ce().optional(),minimum:Yr().optional(),maximum:Yr().optional(),default:Yr().optional()}),ITr=mt({type:Mt("string"),title:ce().optional(),description:ce().optional(),enum:ct(ce()),default:ce().optional()}),RTr=mt({type:Mt("string"),title:ce().optional(),description:ce().optional(),oneOf:ct(mt({const:ce(),title:ce()})),default:ce().optional()}),MTr=mt({type:Mt("string"),title:ce().optional(),description:ce().optional(),enum:ct(ce()),enumNames:ct(ce()).optional(),default:ce().optional()}),PTr=Mn([ITr,RTr]),OTr=mt({type:Mt("array"),title:ce().optional(),description:ce().optional(),minItems:Yr().optional(),maxItems:Yr().optional(),items:mt({type:Mt("string"),enum:ct(ce())}),default:ct(ce()).optional()}),DTr=mt({type:Mt("array"),title:ce().optional(),description:ce().optional(),minItems:Yr().optional(),maxItems:Yr().optional(),items:mt({anyOf:ct(mt({const:ce(),title:ce()}))}),default:ct(ce()).optional()}),NTr=Mn([OTr,DTr]),LTr=Mn([MTr,PTr,NTr]),$Tr=Mn([LTr,ATr,CTr,xTr]),FTr=uS.extend({mode:Mt("form").optional(),message:ce(),requestedSchema:mt({type:Mt("object"),properties:Pn(ce(),$Tr),required:ct(ce()).optional()})}),UTr=uS.extend({mode:Mt("url"),message:ce(),elicitationId:ce(),url:ce().url()}),BTr=Mn([FTr,UTr]),oye=Xs.extend({method:Mt("elicitation/create"),params:BTr}),zTr=Pl.extend({elicitationId:ce()}),qTr=Ol.extend({method:Mt("notifications/elicitation/complete"),params:zTr}),iye=Ys.extend({action:_a(["accept","decline","cancel"]),content:zD(e=>e===null?void 0:e,Pn(ce(),Mn([ce(),Yr(),Rn(),ct(ce())])).optional())}),GTr=mt({type:Mt("ref/resource"),uri:ce()}),jTr=mt({type:Mt("ref/prompt"),name:ce()}),VTr=Bc.extend({ref:Mn([jTr,GTr]),argument:mt({name:ce(),value:ce()}),context:mt({arguments:Pn(ce(),ce()).optional()}).optional()}),HTr=Xs.extend({method:Mt("completion/complete"),params:VTr}),sye=Ys.extend({completion:Ts({values:ct(ce()).max(100),total:zn(Yr().int()),hasMore:zn(Rn())})}),WTr=mt({uri:ce().startsWith("file://"),name:ce().optional(),_meta:Pn(ce(),Bn()).optional()}),KTr=Xs.extend({method:Mt("roots/list"),params:Bc.optional()}),JTr=Ys.extend({roots:ct(WTr)}),XTr=Ol.extend({method:Mt("notifications/roots/list_changed"),params:Pl.optional()}),vLn=Mn([MB,Dbr,HTr,gTr,oTr,rTr,jbr,Vbr,Wbr,Jbr,Ybr,mTr,dTr,OB,NB,LB,FB]),_Ln=Mn([RB,PB,U0e,XTr,$4]),wLn=Mn([o_,rye,nye,iye,JTr,DB,$B,gS]),bLn=Mn([MB,tye,oye,KTr,OB,NB,LB,FB]),TLn=Mn([RB,PB,vTr,Qbr,W0e,Q0e,X0e,$4,qTr]),ELn=Mn([o_,F0e,sye,J0e,K0e,j0e,V0e,H0e,F4,Z0e,DB,$B,gS]),Wt=class EQr extends Error{constructor(t,r,n){super(`MCP error ${t}: ${r}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,r,n){if(t===rr.UrlElicitationRequired&&n){const o=n;if(o.elicitations)return new YTr(o.elicitations,r)}return new EQr(t,r,n)}},YTr=class extends Wt{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(rr.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}}});function a_(e){return e==="completed"||e==="failed"||e==="cancelled"}var SLn=E({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js"(){}});function ZTr(e){const r=ybr(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=vbr(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function QTr(e,t){const r=Eg(e,t);if(!r.success)throw r.error;return r.data}var kLn=E({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js"(){P0e(),cX()}});function eEr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ALn(e,t){const r={...e};for(const n in t){const o=n,i=t[o];if(i===void 0)continue;const s=r[o];eEr(s)&&eEr(i)?r[o]={...s,...i}:r[o]=i}return r}var tEr,rEr,CLn=E({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js"(){P0e(),kg(),SLn(),kLn(),tEr=6e4,rEr=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(RB,t=>{this._oncancel(t)}),this.setNotificationHandler(PB,t=>{this._onprogress(t)}),this.setRequestHandler(MB,t=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(OB,async(t,r)=>{const n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new Wt(rr.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(NB,async(t,r)=>{const n=async()=>{const o=t.params.taskId;if(!await this._taskStore.getTask(o,r.sessionId))throw new Wt(rr.InvalidParams,`Task not found: ${o}`);if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(o,r.sessionId);){if(s.type==="response"||s.type==="error"){const a=s.message,c=a.id,l=this._requestResolvers.get(c);if(l)if(this._requestResolvers.delete(c),s.type==="response")l(a);else{const u=a,d=new Wt(u.error.code,u.error.message,u.error.data);l(d)}else{const u=s.type==="response"?"Response":"Error";this._onerror(new Error(`${u} handler missing for request ${c}`))}continue}await this._transport?.send(s.message,{relatedRequestId:r.requestId})}}const i=await this._taskStore.getTask(o,r.sessionId);if(!i)throw new Wt(rr.InvalidParams,`Task not found: ${o}`);if(!a_(i.status))return await this._waitForTaskUpdate(o,r.signal,r.sessionId),await n();if(a_(i.status)){const s=await this._taskStore.getTaskResult(o,r.sessionId);return this._clearTaskQueue(o,r.sessionId),{...s,_meta:{...s._meta,[Sg]:{taskId:o}}}}return await n()};return await n()}),this.setRequestHandler(LB,async(t,r)=>{try{const{tasks:n,nextCursor:o}=await this._taskStore.listTasks(t.params?.cursor,r.sessionId);return{tasks:n,nextCursor:o,_meta:{}}}catch(n){throw new Wt(rr.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(FB,async(t,r)=>{try{const n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new Wt(rr.InvalidParams,`Task not found: ${t.params.taskId}`);if(a_(n.status))throw new Wt(rr.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(t.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(t.params.taskId,r.sessionId);const o=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!o)throw new Wt(rr.InvalidParams,`Task not found after cancellation: ${t.params.taskId}`);return{_meta:{},...o}}catch(n){throw n instanceof Wt?n:new Wt(rr.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,t,r,n,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:o,onTimeout:n})}_resetTimeout(e){const t=this._timeoutInfo.get(e);if(!t)return!1;const r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),Wt.fromError(rr.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){const t=this._timeoutInfo.get(e);t&&(clearTimeout(t.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;const t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};const r=this.transport?.onerror;this._transport.onerror=o=>{r?.(o),this._onerror(o)};const n=this._transport?.onmessage;this._transport.onmessage=(o,i)=>{n?.(o,i),dS(o)||kbr(o)?this._onresponse(o):CB(o)?this._onrequest(o,i):Sbr(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){const e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();for(const r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();const t=Wt.fromError(rr.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const r of e.values())r(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){const t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(r=>this._onerror(new Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,t){const r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,n=this._transport,o=e.params?._meta?.[Sg]?.taskId,i=n?.sessionId,s=this._taskStore;let a=!0,c;if(o&&s&&this._taskMessageQueue&&i!==void 0&&(a=!1,c=(async()=>{if(!await s.getTask(o,i))throw new Wt(rr.InvalidParams,`Task not found: ${o}`);a=!0})()),r===void 0){const m={jsonrpc:"2.0",id:e.id,error:{code:rr.MethodNotFound,message:"Method not found"}};if(o&&c){const h={type:"error",message:m,timestamp:Date.now()};c.then(()=>this._enqueueTaskMessage(o,h,i),()=>n?.send(m)).catch(f=>this._onerror(new Error(`Failed to send an error response: ${f}`)))}else o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:m,timestamp:Date.now()},n?.sessionId).catch(h=>this._onerror(new Error(`Failed to enqueue error response: ${h}`))):n?.send(m).catch(h=>this._onerror(new Error(`Failed to send an error response: ${h}`)));return}const l=new AbortController;this._requestHandlerAbortControllers.set(e.id,l);const u=Ebr(e.params)?e.params.task:void 0,d=this._taskStore?this.requestTaskStore(e,n?.sessionId):void 0,p={signal:l.signal,sessionId:n?.sessionId,_meta:e.params?._meta,sendNotification:async m=>{if(l.signal.aborted)return;const h={relatedRequestId:e.id};o&&(h.relatedTask={taskId:o}),await this.notification(m,h)},sendRequest:async(m,h,f)=>{if(l.signal.aborted)throw new Wt(rr.ConnectionClosed,"Request was cancelled");const y={...f,relatedRequestId:e.id};o&&!y.relatedTask&&(y.relatedTask={taskId:o});const v=y.relatedTask?.taskId??o;return v&&d&&await d.updateTaskStatus(v,"input_required"),await this.request(m,h,y)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:o,taskStore:d,taskRequestedTtl:u?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};(c??Promise.resolve()).then(()=>{if(c&&l.signal.aborted)throw new Wt(rr.ConnectionClosed,"Request was cancelled");u&&this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,p)).then(async m=>{if(l.signal.aborted)return;const h={result:m,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:h,timestamp:Date.now()},n?.sessionId):await n?.send(h)},async m=>{if(l.signal.aborted)return;const h={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(m.code)?m.code:rr.InternalError,message:m.message??"Internal error",...m.data!==void 0&&{data:m.data}}};o&&this._taskMessageQueue&&a?await this._enqueueTaskMessage(o,{type:"error",message:h,timestamp:Date.now()},n?.sessionId):await n?.send(h)}).catch(m=>this._onerror(new Error(`Failed to send response: ${m}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===l&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:t,...r}=e.params,n=Number(t),o=this._progressHandlers.get(n);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}const i=this._responseHandlers.get(n),s=this._timeoutInfo.get(n);if(s&&i&&s.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(a){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),i(a);return}o(r)}_onresponse(e){const t=Number(e.id),r=this._requestResolvers.get(t);if(r){if(this._requestResolvers.delete(t),dS(e))r(e);else{const i=new Wt(e.error.code,e.error.message,e.error.data);r(i)}return}const n=this._responseHandlers.get(t);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let o=!1;if(dS(e)&&e.result&&typeof e.result=="object"){const i=e.result;if(i.task&&typeof i.task=="object"){const s=i.task;typeof s.taskId=="string"&&(o=!0,this._taskProgressTokens.set(s.taskId,t))}}if(o||this._progressHandlers.delete(t),dS(e))n(e);else{const i=Wt.fromError(e.error.code,e.error.message,e.error.data);n(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,r){const{task:n}=r??{};if(!n){try{yield{type:"result",result:await this.request(e,t,r)}}catch(i){yield{type:"error",error:i instanceof Wt?i:new Wt(rr.InternalError,String(i))}}return}let o;try{const i=await this.request(e,gS,r);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new Wt(rr.InternalError,"Task creation did not return a task");for(;;){const s=await this.getTask({taskId:o},r);if(yield{type:"taskStatus",task:s},a_(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},t,r)}:s.status==="failed"?yield{type:"error",error:new Wt(rr.InternalError,`Task ${o} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new Wt(rr.InternalError,`Task ${o} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},t,r)};return}const a=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(c=>setTimeout(c,a)),r?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof Wt?i:new Wt(rr.InternalError,String(i))}}}request(e,t,r){const{relatedRequestId:n,resumptionToken:o,onresumptiontoken:i,task:s,relatedTask:a}=r??{};return new Promise((c,l)=>{const u=v=>{l(v)};if(!this._transport){u(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),s&&this.assertTaskCapability(e.method)}catch(v){u(v);return}r?.signal?.throwIfAborted();const d=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:d};r?.onprogress&&(this._progressHandlers.set(d,r.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),s&&(p.params={...p.params,task:s}),a&&(p.params={...p.params,_meta:{...p.params?._meta||{},[Sg]:a}});const m=v=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:d,reason:String(v)}},{relatedRequestId:n,resumptionToken:o,onresumptiontoken:i}).catch(w=>this._onerror(new Error(`Failed to send cancellation: ${w}`)));const _=v instanceof Wt?v:new Wt(rr.RequestTimeout,String(v));l(_)};this._responseHandlers.set(d,v=>{if(!r?.signal?.aborted){if(v instanceof Error)return l(v);try{const _=Eg(t,v.result);_.success?c(_.data):l(_.error)}catch(_){l(_)}}}),r?.signal?.addEventListener("abort",()=>{m(r?.signal?.reason)});const h=r?.timeout??tEr,f=()=>m(Wt.fromError(rr.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(d,h,r?.maxTotalTimeout,f,r?.resetTimeoutOnProgress??!1);const y=a?.taskId;if(y){const v=_=>{const w=this._responseHandlers.get(d);w?w(_):this._onerror(new Error(`Response handler missing for side-channeled request ${d}`))};this._requestResolvers.set(d,v),this._enqueueTaskMessage(y,{type:"request",message:p,timestamp:Date.now()}).catch(_=>{this._cleanupTimeout(d),l(_)})}else this._transport.send(p,{relatedRequestId:n,resumptionToken:o,onresumptiontoken:i}).catch(v=>{this._cleanupTimeout(d),l(v)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},DB,t)}async getTaskResult(e,t,r){return this.request({method:"tasks/result",params:e},t,r)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},$B,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},qbr,t)}async notification(e,t){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);const r=t?.relatedTask?.taskId;if(r){const s={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Sg]:t.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:s,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let s={...e,jsonrpc:"2.0"};t?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Sg]:t.relatedTask}}}),this._transport?.send(s,t).catch(a=>this._onerror(a))});return}let i={...e,jsonrpc:"2.0"};t?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Sg]:t.relatedTask}}}),await this._transport.send(i,t)}setRequestHandler(e,t){const r=ZTr(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(n,o)=>{const i=QTr(e,n);return Promise.resolve(t(i,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,t){const r=ZTr(e);this._notificationHandlers.set(r,n=>{const o=QTr(e,n);return Promise.resolve(t(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){const t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,r){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,r??this._transport?.sessionId,n)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){const r=await this._taskMessageQueue.dequeueAll(e,t);for(const n of r)if(n.type==="request"&&CB(n.message)){const o=n.message.id,i=this._requestResolvers.get(o);i?(i(new Wt(rr.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,t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{const o=await this._taskStore?.getTask(e,r);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,i)=>{if(t.aborted){i(new Wt(rr.InvalidRequest,"Request cancelled"));return}const s=setTimeout(o,n);t.addEventListener("abort",()=>{clearTimeout(s),i(new Wt(rr.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){const r=this._taskStore;if(!r)throw new Error("No task store configured");return{createTask:async n=>{if(!e)throw new Error("No request provided");return await r.createTask(n,e.id,{method:e.method,params:e.params},t)},getTask:async n=>{const o=await r.getTask(n,t);if(!o)throw new Wt(rr.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(n,o,i)=>{await r.storeTaskResult(n,o,i,t);const s=await r.getTask(n,t);if(s){const a=$4.parse({method:"notifications/tasks/status",params:s});await this.notification(a),a_(s.status)&&this._cleanupTaskProgressHandler(n)}},getTaskResult:n=>r.getTaskResult(n,t),updateTaskStatus:async(n,o,i)=>{const s=await r.getTask(n,t);if(!s)throw new Wt(rr.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(a_(s.status))throw new Wt(rr.InvalidParams,`Cannot update task "${n}" from terminal status "${s.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(n,o,i,t);const a=await r.getTask(n,t);if(a){const c=$4.parse({method:"notifications/tasks/status",params:a});await this.notification(c),a_(a.status)&&this._cleanupTaskProgressHandler(n)}},listTasks:n=>r.listTasks(n,t)}}}}}),c_,Ds,nEr,xLn,ILn,RLn,MLn,PLn,OLn,DLn,NLn,LLn,$Ln,FLn,ULn,BLn,zLn,qLn,GLn,jLn,VLn,HLn,WLn,KLn,JLn,XLn,YLn,ZLn,QLn,e6n,t6n,r6n,n6n,o6n,i6n,s6n,a6n,c6n,l6n,u6n,d6n,p6n,m6n,h6n,f6n,g6n,y6n,v6n,_6n,w6n=E({"npm-stub:ajv"(){c_={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:c_.get}):new Proxy(function(...r){return new Proxy({},{get:c_.get})},{get:c_.get,apply(r,n,o){return new Proxy({},{get:c_.get})},construct(r,n){return new Proxy({},{get:c_.get})}})}},Ds=new Proxy({},c_),nEr=Ds,{BedrockClient:xLn,ListFoundationModelsCommand:ILn,BedrockRuntimeClient:RLn,ConverseCommand:MLn,ConverseStreamCommand:PLn,ImageFormat:OLn,InvokeModelCommand:DLn}=Ds,{SageMakerRuntimeClient:NLn,InvokeEndpointCommand:LLn,InvokeEndpointWithResponseStreamCommand:$Ln}=Ds,{GoogleAuth:FLn,VertexAI:ULn,TextToSpeechClient:BLn}=Ds,{Webhook:zLn}=Ds,{Hippocampus:qLn,HippocampusConfig:GLn}=Ds,{createClient:jLn}=Ds,{Queue:VLn,Worker:HLn,Job:WLn,QueueScheduler:KLn,FlowProducer:JLn}=Ds,{Cron:XLn}=Ds,{parseBuffer:YLn,selectCover:ZLn}=Ds,{extractRawText:QLn,convertToHtml:e6n}=Ds,{Hono:t6n}=Ds,{cors:r6n,HTTPException:n6n,logger:o6n,secureHeaders:i6n,streamSSE:s6n,timeout:a6n}=Ds,c6n=globalThis.fetch,l6n=globalThis.Request,u6n=globalThis.Response,d6n=globalThis.Headers,p6n=globalThis.FormData,m6n=globalThis.File,h6n=globalThis.Blob,f6n=Ds.Agent,g6n=Ds.Pool,y6n=Ds.Client,v6n=Ds.Dispatcher,_6n=Ds.MockAgent}}),l_,Ns,oEr,b6n,T6n,E6n,S6n,k6n,A6n,C6n,x6n,I6n,R6n,M6n,P6n,O6n,D6n,N6n,L6n,$6n,F6n,U6n,B6n,z6n,q6n,G6n,j6n,V6n,H6n,W6n,K6n,J6n,X6n,Y6n,Z6n,Q6n,e$n,t$n,r$n,n$n,o$n,i$n,s$n,a$n,c$n,l$n,u$n,d$n,p$n,m$n=E({"npm-stub:ajv-formats"(){l_={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:l_.get}):new Proxy(function(...r){return new Proxy({},{get:l_.get})},{get:l_.get,apply(r,n,o){return new Proxy({},{get:l_.get})},construct(r,n){return new Proxy({},{get:l_.get})}})}},Ns=new Proxy({},l_),oEr=Ns,{BedrockClient:b6n,ListFoundationModelsCommand:T6n,BedrockRuntimeClient:E6n,ConverseCommand:S6n,ConverseStreamCommand:k6n,ImageFormat:A6n,InvokeModelCommand:C6n}=Ns,{SageMakerRuntimeClient:x6n,InvokeEndpointCommand:I6n,InvokeEndpointWithResponseStreamCommand:R6n}=Ns,{GoogleAuth:M6n,VertexAI:P6n,TextToSpeechClient:O6n}=Ns,{Webhook:D6n}=Ns,{Hippocampus:N6n,HippocampusConfig:L6n}=Ns,{createClient:$6n}=Ns,{Queue:F6n,Worker:U6n,Job:B6n,QueueScheduler:z6n,FlowProducer:q6n}=Ns,{Cron:G6n}=Ns,{parseBuffer:j6n,selectCover:V6n}=Ns,{extractRawText:H6n,convertToHtml:W6n}=Ns,{Hono:K6n}=Ns,{cors:J6n,HTTPException:X6n,logger:Y6n,secureHeaders:Z6n,streamSSE:Q6n,timeout:e$n}=Ns,t$n=globalThis.fetch,r$n=globalThis.Request,n$n=globalThis.Response,o$n=globalThis.Headers,i$n=globalThis.FormData,s$n=globalThis.File,a$n=globalThis.Blob,c$n=Ns.Agent,l$n=Ns.Pool,u$n=Ns.Client,d$n=Ns.Dispatcher,p$n=Ns.MockAgent}});function h$n(){const e=new nEr({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return oEr(e),e}var iEr,f$n=E({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js"(){w6n(),m$n(),iEr=class{constructor(e){this._ajv=e??h$n()}getValidator(e){const t="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return r=>t(r)?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}}}}),sEr,g$n=E({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js"(){kg(),sEr=class{constructor(e){this._client=e}async*callToolStream(e,t=F4,r){const n=this._client,o={...r,task:r?.task??(n.isToolTask(e.name)?{}:void 0)},i=n.requestStream({method:"tools/call",params:e},t,o),s=n.getToolOutputValidator(e.name);for await(const a of i){if(a.type==="result"&&s){const c=a.result;if(!c.structuredContent&&!c.isError){yield{type:"error",error:new Wt(rr.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(c.structuredContent)try{const l=s(c.structuredContent);if(!l.valid){yield{type:"error",error:new Wt(rr.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)};return}}catch(l){if(l instanceof Wt){yield{type:"error",error:l};return}yield{type:"error",error:new Wt(rr.InvalidParams,`Failed to validate structured content: ${l instanceof Error?l.message:String(l)}`)};return}}yield a}}async getTask(e,t){return this._client.getTask({taskId:e},t)}async getTaskResult(e,t,r){return this._client.getTaskResult({taskId:e},t,r)}async listTasks(e,t){return this._client.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._client.cancelTask({taskId:e},t)}requestStream(e,t,r){return this._client.requestStream(e,t,r)}}}});function y$n(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function v$n(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var _$n=E({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js"(){}}),aEr={};ae(aEr,{Client:()=>lEr,getSupportedElicitationModes:()=>cEr});function VB(e,t){if(!(!e||t===null||typeof t!="object")){if(e.type==="object"&&e.properties&&typeof e.properties=="object"){const r=t,n=e.properties;for(const o of Object.keys(n)){const i=n[o];r[o]===void 0&&Object.prototype.hasOwnProperty.call(i,"default")&&(r[o]=i.default),r[o]!==void 0&&VB(i,r[o])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)typeof r!="boolean"&&VB(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)typeof r!="boolean"&&VB(r,t)}}function cEr(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};const t=e.form!==void 0,r=e.url!==void 0;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}var lEr,w$n=E({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js"(){CLn(),kg(),f$n(),P0e(),g$n(),_$n(),lEr=class extends rEr{constructor(e,t){super(t),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=t?.capabilities??{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new iEr,t?.listChanged&&(this._pendingListChangedConfig=t.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Q0e,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",X0e,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",W0e,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new sEr(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=ALn(this._capabilities,e)}setRequestHandler(e,t){const n=ybr(e)?.method;if(!n)throw new Error("Schema is missing a method literal");const o=vbr(n);if(typeof o!="string")throw new Error("Schema method literal must be a string");const i=o;if(i==="elicitation/create"){const s=async(a,c)=>{const l=Eg(oye,a);if(!l.success){const v=l.error instanceof Error?l.error.message:String(l.error);throw new Wt(rr.InvalidParams,`Invalid elicitation request: ${v}`)}const{params:u}=l.data;u.mode=u.mode??"form";const{supportsFormMode:d,supportsUrlMode:p}=cEr(this._capabilities.elicitation);if(u.mode==="form"&&!d)throw new Wt(rr.InvalidParams,"Client does not support form-mode elicitation requests");if(u.mode==="url"&&!p)throw new Wt(rr.InvalidParams,"Client does not support URL-mode elicitation requests");const m=await Promise.resolve(t(a,c));if(u.task){const v=Eg(gS,m);if(!v.success){const _=v.error instanceof Error?v.error.message:String(v.error);throw new Wt(rr.InvalidParams,`Invalid task creation result: ${_}`)}return v.data}const h=Eg(iye,m);if(!h.success){const v=h.error instanceof Error?h.error.message:String(h.error);throw new Wt(rr.InvalidParams,`Invalid elicitation result: ${v}`)}const f=h.data,y=u.mode==="form"?u.requestedSchema:void 0;if(u.mode==="form"&&f.action==="accept"&&f.content&&y&&this._capabilities.elicitation?.form?.applyDefaults)try{VB(y,f.content)}catch{}return f};return super.setRequestHandler(e,s)}if(i==="sampling/createMessage"){const s=async(a,c)=>{const l=Eg(tye,a);if(!l.success){const f=l.error instanceof Error?l.error.message:String(l.error);throw new Wt(rr.InvalidParams,`Invalid sampling request: ${f}`)}const{params:u}=l.data,d=await Promise.resolve(t(a,c));if(u.task){const f=Eg(gS,d);if(!f.success){const y=f.error instanceof Error?f.error.message:String(f.error);throw new Wt(rr.InvalidParams,`Invalid task creation result: ${y}`)}return f.data}const m=u.tools||u.toolChoice?nye:rye,h=Eg(m,d);if(!h.success){const f=h.error instanceof Error?h.error.message:String(h.error);throw new Wt(rr.InvalidParams,`Invalid sampling result: ${f}`)}return h.data};return super.setRequestHandler(e,s)}return super.setRequestHandler(e,t)}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await super.connect(e),e.sessionId===void 0)try{const r=await this.request({method:"initialize",params:{protocolVersion:D4,capabilities:this._capabilities,clientInfo:this._clientInfo}},F0e,t);if(r===void 0)throw new Error(`Server sent invalid initialize result: ${r}`);if(!wbr.includes(r.protocolVersion))throw new Error(`Server's protocol version is not supported: ${r.protocolVersion}`);this._serverCapabilities=r.capabilities,this._serverVersion=r.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(r.protocolVersion),this._instructions=r.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(r){throw this.close(),r}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${e})`);break;case"ping":break}}assertTaskCapability(e){y$n(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&v$n(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},o_,e)}async complete(e,t){return this.request({method:"completion/complete",params:e},sye,t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},o_,t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},J0e,t)}async listPrompts(e,t){return this.request({method:"prompts/list",params:e},K0e,t)}async listResources(e,t){return this.request({method:"resources/list",params:e},j0e,t)}async listResourceTemplates(e,t){return this.request({method:"resources/templates/list",params:e},V0e,t)}async readResource(e,t){return this.request({method:"resources/read",params:e},H0e,t)}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},o_,t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},o_,t)}async callTool(e,t=F4,r){if(this.isToolTaskRequired(e.name))throw new Wt(rr.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);const n=await this.request({method:"tools/call",params:e},t,r),o=this.getToolOutputValidator(e.name);if(o){if(!n.structuredContent&&!n.isError)throw new Wt(rr.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(n.structuredContent)try{const i=o(n.structuredContent);if(!i.valid)throw new Wt(rr.InvalidParams,`Structured content does not match the tool's output schema: ${i.errorMessage}`)}catch(i){throw i instanceof Wt?i:new Wt(rr.InvalidParams,`Failed to validate structured content: ${i instanceof Error?i.message:String(i)}`)}}return n}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const t of e){if(t.outputSchema){const n=this._jsonSchemaValidator.getValidator(t.outputSchema);this._cachedToolOutputValidators.set(t.name,n)}const r=t.execution?.taskSupport;(r==="required"||r==="optional")&&this._cachedKnownTaskTools.add(t.name),r==="required"&&this._cachedRequiredTaskTools.add(t.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){const r=await this.request({method:"tools/list",params:e},Z0e,t);return this.cacheToolMetadata(r.tools),r}_setupListChangedHandler(e,t,r,n){const o=hTr.safeParse(r);if(!o.success)throw new Error(`Invalid ${e} listChanged options: ${o.error.message}`);if(typeof r.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);const{autoRefresh:i,debounceMs:s}=o.data,{onChanged:a}=r,c=async()=>{if(!i){a(null,null);return}try{const u=await n();a(null,u)}catch(u){const d=u instanceof Error?u:new Error(String(u));a(d,null)}},l=()=>{if(s){const u=this._listChangedDebounceTimers.get(e);u&&clearTimeout(u);const d=setTimeout(c,s);this._listChangedDebounceTimers.set(e,d)}else c()};this.setNotificationHandler(t,l)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}}}),uEr={};ae(uEr,{Agent:()=>QEr,BedrockClient:()=>pEr,BedrockRuntimeClient:()=>hEr,Blob:()=>ZEr,Client:()=>tSr,ConverseCommand:()=>fEr,ConverseStreamCommand:()=>gEr,Cron:()=>DEr,Dispatcher:()=>rSr,File:()=>YEr,FlowProducer:()=>OEr,FormData:()=>XEr,GoogleAuth:()=>TEr,HTTPException:()=>zEr,Headers:()=>JEr,Hippocampus:()=>AEr,HippocampusConfig:()=>CEr,Hono:()=>UEr,ImageFormat:()=>yEr,InvokeEndpointCommand:()=>wEr,InvokeEndpointWithResponseStreamCommand:()=>bEr,InvokeModelCommand:()=>vEr,Job:()=>MEr,ListFoundationModelsCommand:()=>mEr,MockAgent:()=>iSr,Pool:()=>eSr,Queue:()=>IEr,QueueScheduler:()=>PEr,Request:()=>WEr,Response:()=>KEr,SageMakerRuntimeClient:()=>_Er,TextToSpeechClient:()=>SEr,VertexAI:()=>EEr,Webhook:()=>kEr,Worker:()=>REr,convertToHtml:()=>FEr,cors:()=>BEr,createClient:()=>xEr,default:()=>dEr,extractRawText:()=>$Er,fetch:()=>HEr,getGlobalDispatcher:()=>oSr,interceptors:()=>sSr,logger:()=>qEr,parseBuffer:()=>NEr,request:()=>aSr,secureHeaders:()=>GEr,selectCover:()=>LEr,setGlobalDispatcher:()=>nSr,streamSSE:()=>jEr,timeout:()=>VEr});var u_,ds,dEr,pEr,mEr,hEr,fEr,gEr,yEr,vEr,_Er,wEr,bEr,TEr,EEr,SEr,kEr,AEr,CEr,xEr,IEr,REr,MEr,PEr,OEr,DEr,NEr,LEr,$Er,FEr,UEr,BEr,zEr,qEr,GEr,jEr,VEr,HEr,WEr,KEr,JEr,XEr,YEr,ZEr,QEr,eSr,tSr,rSr,nSr,oSr,iSr,sSr,aSr,b$n=E({"npm-stub:which"(){u_={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:u_.get}):new Proxy(function(...r){return new Proxy({},{get:u_.get})},{get:u_.get,apply(r,n,o){return new Proxy({},{get:u_.get})},construct(r,n){return new Proxy({},{get:u_.get})}})}},ds=new Proxy({},u_),dEr=ds,{BedrockClient:pEr,ListFoundationModelsCommand:mEr,BedrockRuntimeClient:hEr,ConverseCommand:fEr,ConverseStreamCommand:gEr,ImageFormat:yEr,InvokeModelCommand:vEr}=ds,{SageMakerRuntimeClient:_Er,InvokeEndpointCommand:wEr,InvokeEndpointWithResponseStreamCommand:bEr}=ds,{GoogleAuth:TEr,VertexAI:EEr,TextToSpeechClient:SEr}=ds,{Webhook:kEr}=ds,{Hippocampus:AEr,HippocampusConfig:CEr}=ds,{createClient:xEr}=ds,{Queue:IEr,Worker:REr,Job:MEr,QueueScheduler:PEr,FlowProducer:OEr}=ds,{Cron:DEr}=ds,{parseBuffer:NEr,selectCover:LEr}=ds,{extractRawText:$Er,convertToHtml:FEr}=ds,{Hono:UEr}=ds,{cors:BEr,HTTPException:zEr,logger:qEr,secureHeaders:GEr,streamSSE:jEr,timeout:VEr}=ds,HEr=globalThis.fetch,WEr=globalThis.Request,KEr=globalThis.Response,JEr=globalThis.Headers,XEr=globalThis.FormData,YEr=globalThis.File,ZEr=globalThis.Blob,QEr=ds.Agent,eSr=ds.Pool,tSr=ds.Client,rSr=ds.Dispatcher,nSr=()=>{},oSr=()=>ds,iSr=ds.MockAgent,sSr={redirect:()=>e=>e,retry:()=>e=>e},aSr=async(e,t)=>{const r=await globalThis.fetch(e,t);return{statusCode:r.status,headers:Object.fromEntries(r.headers.entries()),body:{text:()=>r.text(),json:()=>r.json(),arrayBuffer:()=>r.arrayBuffer()}}}}}),T$n=Sn({"node_modules/.pnpm/path-key@3.1.1/node_modules/path-key/index.js"(e,t){"use strict";var r=(n={})=>{const o=n.env||process.env;return(n.platform||process.platform)!=="win32"?"PATH":Object.keys(o).reverse().find(s=>s.toUpperCase()==="PATH")||"Path"};t.exports=r,t.exports.default=r}}),E$n=Sn({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js"(e,t){"use strict";var r=(Nr(),In(qh)),n=(b$n(),In(uEr)),o=T$n();function i(a,c){const l=a.options.env||process.env,u=process.cwd(),d=a.options.cwd!=null,p=d&&process.chdir!==void 0&&!process.chdir.disabled;if(p)try{process.chdir(a.options.cwd)}catch{}let m;try{m=n.sync(a.command,{path:l[o({env:l})],pathExt:c?r.delimiter:void 0})}catch{}finally{p&&process.chdir(u)}return m&&(m=r.resolve(d?a.options.cwd:"",m)),m}function s(a){return i(a)||i(a,!0)}t.exports=s}}),S$n=Sn({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/escape.js"(e,t){"use strict";var r=/([()\][%!^"`<>&|;, *?])/g;function n(i){return i=i.replace(r,"^$1"),i}function o(i,s){return i=`${i}`,i=i.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),i=i.replace(/(?=(\\+?)?)\1$/,"$1$1"),i=`"${i}"`,i=i.replace(r,"^$1"),s&&(i=i.replace(r,"^$1")),i}t.exports.command=n,t.exports.argument=o}}),k$n=Sn({"node_modules/.pnpm/shebang-regex@3.0.0/node_modules/shebang-regex/index.js"(e,t){"use strict";t.exports=/^#!(.*)/}}),A$n=Sn({"node_modules/.pnpm/shebang-command@2.0.0/node_modules/shebang-command/index.js"(e,t){"use strict";var r=k$n();t.exports=(n="")=>{const o=n.match(r);if(!o)return null;const[i,s]=o[0].replace(/#! ?/,"").split(" "),a=i.split("/").pop();return a==="env"?s:s?`${a} ${s}`:a}}}),C$n=Sn({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js"(e,t){"use strict";var r=(yo(),In(up)),n=A$n();function o(i){const a=Buffer.alloc(150);let c;try{c=r.openSync(i,"r"),r.readSync(c,a,0,150,0),r.closeSync(c)}catch{}return n(a.toString())}t.exports=o}}),x$n=Sn({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js"(e,t){"use strict";var r=(Nr(),In(qh)),n=E$n(),o=S$n(),i=C$n(),s=process.platform==="win32",a=/\.(?:com|exe)$/i,c=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function l(p){p.file=n(p);const m=p.file&&i(p.file);return m?(p.args.unshift(p.file),p.command=m,n(p)):p.file}function u(p){if(!s)return p;const m=l(p),h=!a.test(m);if(p.options.forceShell||h){const f=c.test(m);p.command=r.normalize(p.command),p.command=o.command(p.command),p.args=p.args.map(v=>o.argument(v,f));const y=[p.command].concat(p.args).join(" ");p.args=["/d","/s","/c",`"${y}"`],p.command=process.env.comspec||"cmd.exe",p.options.windowsVerbatimArguments=!0}return p}function d(p,m,h){m&&!Array.isArray(m)&&(h=m,m=null),m=m?m.slice(0):[],h=Object.assign({},h);const f={command:p,args:m,options:h,file:void 0,original:{command:p,args:m}};return h.shell?f:u(f)}t.exports=d}}),I$n=Sn({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/enoent.js"(e,t){"use strict";var r=process.platform==="win32";function n(a,c){return Object.assign(new Error(`${c} ${a.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${c} ${a.command}`,path:a.command,spawnargs:a.args})}function o(a,c){if(!r)return;const l=a.emit;a.emit=function(u,d){if(u==="exit"){const p=i(d,c);if(p)return l.call(a,"error",p)}return l.apply(a,arguments)}}function i(a,c){return r&&a===1&&!c.file?n(c.original,"spawn"):null}function s(a,c){return r&&a===1&&!c.file?n(c.original,"spawnSync"):null}t.exports={hookChildProcess:o,verifyENOENT:i,verifyENOENTSync:s,notFoundError:n}}}),R$n=Sn({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/index.js"(e,t){"use strict";var r=(Pje(),In(Xqe)),n=x$n(),o=I$n();function i(a,c,l){const u=n(a,c,l),d=r.spawn(u.command,u.args,u.options);return o.hookChildProcess(d,u),d}function s(a,c,l){const u=n(a,c,l),d=r.spawnSync(u.command,u.args,u.options);return d.error=d.error||o.verifyENOENTSync(d.status,u),d}t.exports=i,t.exports.spawn=i,t.exports.sync=s,t.exports._parse=n,t.exports._enoent=o}}),HB,M$n,P$n,O$n,D$n,WB,cSr,aye,N$n,L$n,$$n,F$n,U$n=E({"node-stub:node:process"(){HB={},M$n=globalThis.crypto,P$n=globalThis.ReadableStream||class{},O$n=globalThis.URL,D$n=globalThis.URLSearchParams,WB=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},WB.custom=Symbol.for("nodejs.util.inspect.custom"),WB.colors={},WB.styles={},cSr=globalThis.TextDecoder,aye=globalThis.TextEncoder,N$n=globalThis.performance||{now:()=>Date.now()},L$n=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),i=new Uint8Array(o.length);for(let s=0;s<o.length;s++)i[s]=o.charCodeAt(s);return i}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let i=0;i<t.length;i+=2)o[i/2]=parseInt(t.substr(i,2),16);return o}return new aye().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((i,s)=>i+s.length,0),n=new Uint8Array(r);let o=0;for(const i of t)n.set(i,o),o+=i.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new aye().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new cSr().decode(this)}},$$n=globalThis.clearTimeout,F$n=globalThis.clearInterval}});function B$n(e){return n_.parse(JSON.parse(e))}function z$n(e){return JSON.stringify(e)+`
1242
+ For video extraction, the result includes images (frames) that will be visible to you. Always call list_attached_files first to discover file IDs.`,inputSchema:R.object({file_id:R.string().describe("File ID (UUID) or exact filename from list_attached_files"),start_time:R.number().optional().describe("Start timestamp in seconds (video only)"),end_time:R.number().optional().describe("End timestamp in seconds (video only)"),frame_count:R.number().int().min(1).max(20).optional().describe("Number of frames to extract in time range (video only, default: 5, max: 20)"),pages:R.array(R.number().int().min(1)).optional().describe("Specific page/slide numbers to extract (1-indexed)"),page_range:R.object({start:R.number().int().min(1),end:R.number().int().min(1)}).optional().describe("Page/slide range to extract (1-indexed, inclusive)"),sheet:R.string().optional().describe("Sheet name or 0-based index as string e.g. '0', '1' (spreadsheet only, default: first sheet)"),row_range:R.object({start:R.number().int().min(1),end:R.number().int().min(1)}).optional().describe("Row range (1-indexed, spreadsheet only)"),columns:R.array(R.string()).optional().describe("Specific column letters to include (e.g., ['A', 'B', 'D'], spreadsheet only)"),entry_path:R.string().optional().describe("File path within archive to extract (archive only)"),format:R.enum(["text","detailed","summary"]).optional().describe("Output format hint (default: text)")}),execute:async t=>{try{const r={...t,sheet:t.sheet!==void 0?/^\d+$/.test(t.sheet)?parseInt(t.sheet,10):t.sheet:void 0},n=await e.extractContent(r);return n.success?{success:!0,text:n.text,metadata:n.metadata,imageCount:n.images?.length??0,_images:n.images,error:void 0}:{success:!1,error:n.error,text:void 0,metadata:void 0,imageCount:0,_images:void 0}}catch(r){return{success:!1,error:r instanceof Error?r.message:String(r),text:void 0,metadata:void 0,imageCount:0,_images:void 0}}},toModelOutput:({output:t})=>{const r=[];if(t.text?r.push({type:"text",text:t.text}):t.error&&r.push({type:"text",text:`Error: ${t.error}`}),t._images&&t._images.length>0)for(const n of t._images)r.push({type:"image-data",data:n.toString("base64"),mediaType:"image/jpeg"});return r.length===0&&r.push({type:"text",text:"(No content extracted)"}),{type:"content",value:r}}}}function Pwr(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${(e/(1024*1024*1024)).toFixed(2)} GB`}var Y3n=E({"src/lib/files/fileTools.ts"(){"use strict";An(),su()}}),Owr={};ae(Owr,{AuthError:()=>Nt,AuthErrorCodes:()=>hB});var hB,Nt,Oa=E({"src/lib/auth/errors.ts"(){"use strict";m1(),hB={INVALID_TOKEN:"AUTH-001",EXPIRED_TOKEN:"AUTH-002",MISSING_TOKEN:"AUTH-003",TOKEN_DECODE_FAILED:"AUTH-004",INVALID_SIGNATURE:"AUTH-005",SESSION_NOT_FOUND:"AUTH-010",SESSION_EXPIRED:"AUTH-011",SESSION_REVOKED:"AUTH-012",INSUFFICIENT_PERMISSIONS:"AUTH-020",INSUFFICIENT_ROLES:"AUTH-021",ACCESS_DENIED:"AUTH-022",USER_NOT_FOUND:"AUTH-030",USER_DISABLED:"AUTH-031",EMAIL_NOT_VERIFIED:"AUTH-032",MFA_REQUIRED:"AUTH-033",PROVIDER_ERROR:"AUTH-040",PROVIDER_NOT_FOUND:"AUTH-041",PROVIDER_INIT_FAILED:"AUTH-042",CONFIGURATION_ERROR:"AUTH-043",CREATION_FAILED:"AUTH-050",REGISTRATION_FAILED:"AUTH-051",DUPLICATE_REGISTRATION:"AUTH-052",MIDDLEWARE_ERROR:"AUTH-060",RATE_LIMITED:"AUTH-061",JWKS_FETCH_FAILED:"AUTH-070",JWKS_KEY_NOT_FOUND:"AUTH-071"},Nt=Py("Auth",hB)}}),fB={};ae(fB,{AuthContextHolder:()=>yB,createAuthenticatedContext:()=>qwr,getAuthContext:()=>aS,getCurrentSession:()=>Nwr,getCurrentUser:()=>R4,globalAuthContext:()=>e_,hasAllPermissions:()=>Uwr,hasAnyRole:()=>Fwr,hasPermission:()=>gB,hasRole:()=>h0e,isAuthenticated:()=>Lwr,requireAuth:()=>m0e,requirePermission:()=>Bwr,requireRole:()=>zwr,requireUser:()=>$wr,runWithAuthContext:()=>Dwr});function Dwr(e,t){return cS.run(e,t)}function aS(){return cS.getStore()??e_.get()}function R4(){return(cS.getStore()??e_.get())?.user}function Nwr(){return(cS.getStore()??e_.get())?.session}function Lwr(){return cS.getStore()!==void 0||e_.isAuthenticated()}function m0e(){const e=aS();if(!e)throw Nt.create("MISSING_TOKEN","Authentication required");return e}function $wr(e){const t=m0e();if(t.user.id!==e)throw Nt.create("ACCESS_DENIED","User mismatch");return t}function gB(e){const t=R4();if(!t)return!1;if(t.permissions.includes(e)||t.permissions.includes("*"))return!0;const r=e.split(":");for(let n=r.length-1;n>0;n--){const o=[...r.slice(0,n),"*"].join(":");if(t.permissions.includes(o))return!0}return!1}function h0e(e){return R4()?.roles.includes(e)??!1}function Fwr(e){const t=R4();return t?e.some(r=>t.roles.includes(r)):!1}function Uwr(e){return e.every(t=>gB(t))}function Bwr(e){if(!gB(e))throw Nt.create("INSUFFICIENT_PERMISSIONS",`Permission denied: ${e}`)}function zwr(e){if(!h0e(e))throw Nt.create("INSUFFICIENT_ROLES",`Role required: ${e}`)}function qwr(e,t,r,n){return{...r,user:e,session:t,request:r,authenticatedAt:new Date,provider:n}}var cS,yB,e_,lS=E({"src/lib/auth/authContext.ts"(){"use strict";eB(),Oa(),cS=new tS,yB=class{context;set(e){this.context=e}get(){return this.context}clear(){this.context=void 0}getUser(){return this.context?.user}getSession(){return this.context?.session}isAuthenticated(){return this.context!==void 0}hasPermission(e){const t=this.context?.user;if(!t)return!1;if(t.permissions.includes(e)||t.permissions.includes("*"))return!0;const r=e.split(":");for(let n=r.length-1;n>0;n--){const o=[...r.slice(0,n),"*"].join(":");if(t.permissions.includes(o))return!0}return!1}hasRole(e){return this.context?.user.roles.includes(e)??!1}},e_=new yB}}),vB,Gwr,f0e,_B,jwr,Z3n=E({"src/lib/mcp/batching/requestBatcher.ts"(){"use strict";To(),G(),st(),qr(),gr(),vB=class extends On{config;pending=new Map;serverQueues=new Map;flushTimer;executor;activeBatches=0;batchCounter=0;requestCounter=0;isDestroyed=!1;constructor(e){super(),this.config={maxBatchSize:e.maxBatchSize,maxWaitMs:e.maxWaitMs,enableParallel:e.enableParallel??!0,maxConcurrentBatches:e.maxConcurrentBatches??5,groupByServer:e.groupByServer??!0}}setExecutor(e){this.executor=e}async add(e,t,r){if(this.isDestroyed)throw Te.invalidConfiguration("batcher","Batcher has been destroyed");if(!this.executor)throw Te.missingConfiguration("batchExecutor",{hint:"Call setExecutor() before adding requests"});const n=this.generateRequestId();return new Promise((o,i)=>{const s={id:n,tool:e,args:t,serverId:r,resolve:o,reject:i,addedAt:Date.now()};if(this.pending.set(n,s),this.config.groupByServer&&r){this.serverQueues.has(r)||this.serverQueues.set(r,new Set);const a=this.serverQueues.get(r);a&&a.add(n)}this.emit("requestQueued",{requestId:n,queueSize:this.pending.size}),this.pending.size>=this.config.maxBatchSize?this.scheduleFlush("size"):this.flushTimer||(this.flushTimer=setTimeout(()=>{this.scheduleFlush("timeout")},this.config.maxWaitMs))})}async flush(){this.clearFlushTimer(),this.pending.size!==0&&(this.emit("flushTriggered",{reason:"manual",queueSize:this.pending.size}),await this.executeBatch())}get queueSize(){return this.pending.size}get activeBatchCount(){return this.activeBatches}get isIdle(){return this.pending.size===0&&this.activeBatches===0}async drain(){await this.flush();const e=3e4,t=Date.now()+e;for(;!this.isIdle;){if(Date.now()>=t)throw Te.toolTimeout("batchDrain",e);await new Promise(r=>setTimeout(r,10))}}destroy(){this.isDestroyed=!0,this.clearFlushTimer();for(const e of this.pending.values())e.reject(Te.invalidConfiguration("batcher","Batcher was destroyed before request could complete"));this.pending.clear(),this.serverQueues.clear()}generateRequestId(){return`req-${Date.now()}-${++this.requestCounter}`}generateBatchId(){return`batch-${Date.now()}-${++this.batchCounter}`}scheduleFlush(e){this.clearFlushTimer(),this.emit("flushTriggered",{reason:e,queueSize:this.pending.size}),setImmediate(()=>{this.executeBatch().catch(t=>{g.error("Batch execution failed:",t)})})}clearFlushTimer(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0)}async executeBatch(){if(this.pending.size===0)return;if(this.activeBatches>=this.config.maxConcurrentBatches){this.clearFlushTimer(),this.flushTimer=setTimeout(()=>{this.executeBatch().catch(n=>{g.error("Rescheduled batch execution failed:",n)})},10);return}const e=this.selectBatchRequests();if(e.length===0)return;const t=this.generateBatchId(),r=Date.now();this.activeBatches++,this.emit("batchStarted",{batchId:t,size:e.length}),await wt({name:"mcp.batch.execute",tracer:We.mcp,attributes:{"mcp.batch.id":t,"mcp.batch.size":e.length,"mcp.batch.active_batches":this.activeBatches}},async n=>{let o=0,i=0;try{if(!this.executor)throw Te.missingConfiguration("batchExecutor",{hint:"Call setExecutor() before executing batches"});const s=this.executor(e.map(p=>({tool:p.tool,args:p.args,serverId:p.serverId}))),a=Math.max(5e3,Number(process.env.MCP_TOOL_TIMEOUT)||6e4);let c;const l=new Promise((p,m)=>{c=setTimeout(()=>m(Te.toolTimeout("batchExecution",a)),a)});s.catch(p=>{});const u=await Promise.race([s,l]).finally(()=>{c&&clearTimeout(c)}),d=[];for(let p=0;p<e.length;p++){const m=e[p],h=u[p],f=Date.now()-r;if(!h){const y=Te.toolExecutionFailed(m.tool,new Error(`Batch executor returned no result for request ${p}`));m.reject(y),d.push({id:m.id,success:!1,error:y,executionTime:f}),i++;continue}if(h.success)m.resolve(h.result),d.push({id:m.id,success:!0,result:h.result,executionTime:f}),o++;else{const y=h.error??Te.toolExecutionFailed(m.tool,new Error("Unknown batch execution error"));m.reject(y),d.push({id:m.id,success:!1,error:y,executionTime:f}),i++}}n.setAttribute("mcp.batch.success_count",o),n.setAttribute("mcp.batch.error_count",i),this.emit("batchCompleted",{batchId:t,results:d})}catch(s){const a=s instanceof Error?s:Te.toolExecutionFailed("batch",new Error(String(s)));for(const c of e)c.reject(a);throw this.emit("batchFailed",{batchId:t,error:a}),a}finally{this.activeBatches--}}).catch(n=>{g.error("Batch span execution failed:",n)}),this.pending.size>0&&(this.clearFlushTimer(),this.flushTimer=setTimeout(()=>{this.executeBatch().catch(n=>{g.error("Follow-up batch execution failed:",n)})},0))}selectBatchRequests(){const e=[];if(this.config.groupByServer&&this.serverQueues.size>0){const[t,r]=this.serverQueues.entries().next().value;for(const n of r){if(e.length>=this.config.maxBatchSize)break;const o=this.pending.get(n);o&&(e.push(o),this.pending.delete(n),r.delete(n))}r.size===0&&this.serverQueues.delete(t)}else{const t=Array.from(this.pending.values()).sort((r,n)=>r.addedAt-n.addedAt);for(const r of t){if(e.length>=this.config.maxBatchSize)break;e.push(r),this.pending.delete(r.id)}}return e}},Gwr=e=>new vB(e),f0e={maxBatchSize:10,maxWaitMs:100,enableParallel:!0,maxConcurrentBatches:5,groupByServer:!0},_B=class{batcher;toolExecutor;constructor(e){this.batcher=new vB({...f0e,...e}),this.batcher.setExecutor(async t=>{if(!this.toolExecutor)throw Te.missingConfiguration("toolExecutor",{hint:"Call setToolExecutor() before executing tool calls"});const r=this.toolExecutor;return await Promise.all(t.map(async o=>{try{return{success:!0,result:await r(o.tool,o.args,o.serverId)}}catch(i){return{success:!1,error:i instanceof Error?i:Te.toolExecutionFailed(o.tool,new Error(String(i)))}}}))})}setToolExecutor(e){this.toolExecutor=e}async execute(e,t,r){return this.batcher.add(e,t,r)}async flush(){return this.batcher.flush()}async drain(){return this.batcher.drain()}get queueSize(){return this.batcher.queueSize}get isIdle(){return this.batcher.isIdle}destroy(){this.batcher.destroy()}},jwr=e=>new _B(e)}}),Vwr=E({"src/lib/mcp/batching/index.ts"(){"use strict";Z3n()}}),t_,Hwr,g0e,wB,Wwr,Q3n=E({"src/lib/mcp/caching/toolCache.ts"(){"use strict";tr(),To(),on(),t_=class extends On{cache=new Map;config;stats;cleanupTimer;constructor(e){super(),this.config={ttl:e.ttl,maxSize:e.maxSize,strategy:e.strategy,enableAutoCleanup:e.enableAutoCleanup??!0,cleanupInterval:e.cleanupInterval??6e4,namespace:e.namespace??""},this.stats={hits:0,misses:0,evictions:0,size:0,maxSize:this.config.maxSize,hitRate:0},this.config.enableAutoCleanup&&this.startAutoCleanup()}get(e){const t=this.getFullKey(e),r=this.cache.get(t);if(!r){this.stats.misses++,this.updateHitRate(),this.emit("miss",{key:t});return}if(this.isExpired(r)){this.deleteWithReason(t,"expired"),this.stats.misses++,this.updateHitRate(),this.emit("miss",{key:t});return}r.accessedAt=Date.now(),r.accessCount++,this.stats.hits++,this.updateHitRate();const n=this.cloneCachedValue(r.value);return this.listenerCount("hit")>0&&this.emit("hit",{key:t,value:this.cloneCachedValue(r.value)}),n}set(e,t,r){const n=this.getFullKey(e),o=r??this.config.ttl,i=Date.now();this.cache.size>=this.config.maxSize&&!this.cache.has(n)&&this.evictOne();const s={value:this.cloneCachedValue(t),expires:i+o,createdAt:i,accessedAt:i,accessCount:1,key:n};this.cache.set(n,s),this.stats.size=this.cache.size,this.emit("set",{key:n,value:t,ttl:o})}has(e){const t=this.getFullKey(e),r=this.cache.get(t);return r?this.isExpired(r)?(this.deleteWithReason(t,"expired"),!1):!0:!1}delete(e){const t=this.getFullKey(e),r=this.cache.delete(t);return r&&(this.stats.size=this.cache.size,this.emit("evict",{key:t,reason:"manual"})),r}invalidate(e){const t=this.getFullKey(e),r=this.patternToRegex(t);let n=0;for(const o of this.cache.keys())r.test(o)&&(this.cache.delete(o),n++,this.emit("evict",{key:o,reason:"manual"}));return this.stats.size=this.cache.size,n}clear(){const e=this.cache.size;this.cache.clear(),this.stats.size=0,this.emit("clear",{entriesRemoved:e})}async getOrSet(e,t,r){const n=this.get(e);if(n!==void 0)return n;const o=3e4,i=await Dt(Promise.resolve(t()),o,`ToolCache getOrSet factory timed out after ${o}ms for key "${e}"`);return i===void 0||this.set(e,i,r),i}getStats(){return{...this.stats}}resetStats(){this.stats.hits=0,this.stats.misses=0,this.stats.evictions=0,this.updateHitRate()}keys(){return Array.from(this.cache.keys())}get size(){return this.cache.size}static generateKey(e,t){const r=(o,i=new WeakSet)=>{if(o===null||typeof o!="object")return JSON.stringify(o);if(o instanceof Date)return`{"$date":${JSON.stringify(o.toISOString())}}`;if(i.has(o))throw new TypeError("Circular structures are not supported in cache keys");if(i.add(o),Array.isArray(o)){const c="["+o.map(l=>r(l,i)).join(",")+"]";return i.delete(o),c}const a=Object.keys(o).sort().map(c=>JSON.stringify(c)+":"+r(o[c],i));return i.delete(o),"{"+a.join(",")+"}"},n=Bu("sha256").update(r(t)).digest("hex").substring(0,16);return`${e}:${n}`}destroy(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.clear()}cloneCachedValue(e){if(e===null||typeof e!="object")return e;try{return structuredClone(e)}catch{return JSON.parse(JSON.stringify(e))}}getFullKey(e){return this.config.namespace?`${this.config.namespace}:${e}`:e}isExpired(e){return Date.now()>e.expires}deleteWithReason(e,t){const r=this.cache.delete(e);return r&&(this.stats.evictions++,this.stats.size=this.cache.size,this.emit("evict",{key:e,reason:t})),r}evictOne(){const e=this.selectEvictionCandidate();e&&(this.cache.delete(e.key),this.stats.evictions++,this.stats.size=this.cache.size,this.emit("evict",{key:e.key,reason:"capacity"}))}selectEvictionCandidate(){if(this.cache.size!==0)switch(this.config.strategy){case"lru":return this.findLRU();case"fifo":return this.findFIFO();case"lfu":return this.findLFU();default:return this.findLRU()}}findLRU(){let e,t=1/0;for(const r of this.cache.values())r.accessedAt<t&&(t=r.accessedAt,e=r);return e}findFIFO(){let e,t=1/0;for(const r of this.cache.values())r.createdAt<t&&(t=r.createdAt,e=r);return e}findLFU(){let e,t=1/0;for(const r of this.cache.values())r.accessCount<t&&(t=r.accessCount,e=r);return e}patternToRegex(e){const r=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^:]*");return new RegExp(`^${r}$`)}updateHitRate(){const e=this.stats.hits+this.stats.misses;this.stats.hitRate=e>0?this.stats.hits/e:0}startAutoCleanup(){this.cleanupTimer=setInterval(()=>{this.cleanupExpired()},this.config.cleanupInterval),this.cleanupTimer.unref&&this.cleanupTimer.unref()}cleanupExpired(){const e=Date.now();for(const[t,r]of this.cache.entries())e>r.expires&&(this.cache.delete(t),this.stats.evictions++,this.emit("evict",{key:t,reason:"expired"}));this.stats.size=this.cache.size}},Hwr=e=>new t_(e),g0e={ttl:300*1e3,maxSize:500,strategy:"lru",enableAutoCleanup:!0,cleanupInterval:6e4},wB=class{cache;constructor(e){this.cache=new t_({...g0e,...e,namespace:e?.namespace??"tool-results"})}cacheResult(e,t,r,n){const o=t_.generateKey(e,t);this.cache.set(o,r,n)}getCachedResult(e,t){const r=t_.generateKey(e,t);return this.cache.get(r)}hasCachedResult(e,t){const r=t_.generateKey(e,t);return this.cache.has(r)}invalidateTool(e){return this.cache.invalidate(`${e}:*`)}getStats(){return this.cache.getStats()}clear(){this.cache.clear()}destroy(){this.cache.destroy()}},Wwr=e=>new wB(e)}}),Kwr=E({"src/lib/mcp/caching/index.ts"(){"use strict";Q3n()}}),Jwr={};ae(Jwr,{createAnnotatedTool:()=>Ywr,filterToolsByAnnotations:()=>ebr,getAnnotationSummary:()=>tbr,getToolSafetyLevel:()=>Qwr,inferAnnotations:()=>sh,isSafeToRetry:()=>v0e,mergeAnnotations:()=>y0e,requiresConfirmation:()=>Zwr,validateAnnotations:()=>Xwr});function sh(e){const t=e.name,r=e.description.toLowerCase(),n={},o=(l,u)=>new RegExp(`\\b${u}\\b`,"i").test(l)?!0:l.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase().split(/[_-]/).some(p=>p===u.toLowerCase());return["get","list","read","fetch","query","search","find","show","display","view","retrieve","check","inspect","look"].some(l=>o(r,l)||o(t,l))&&(n.readOnlyHint=!0),["delete","remove","drop","destroy","clear","purge","erase","wipe","truncate","reset"].some(l=>o(r,l)||o(t,l))&&(n.destructiveHint=!0,n.requiresConfirmation=!0),["set","update","put","upsert","replace"].some(l=>o(r,l)||o(t,l))&&!n.destructiveHint&&(n.idempotentHint=!0),["complex","analyze","process","generate","transform","compute","calculate"].some(l=>o(r,l)||o(t,l))?n.complexity="complex":r.length>100?n.complexity="medium":n.complexity="simple",n}function y0e(...e){const t={};for(const r of e)if(r){const n=t.tags?[...t.tags]:[];if(Object.assign(t,r),n.length>0||r.tags){const o=r.tags??[];t.tags=[...new Set([...n,...o])]}}return t}function Xwr(e){const t=[];if(e.readOnlyHint&&e.destructiveHint&&t.push("Tool cannot be both readOnly and destructive - these are conflicting hints"),e.rateLimitHint!==void 0&&(e.rateLimitHint<0||!Number.isFinite(e.rateLimitHint))&&t.push("rateLimitHint must be a non-negative number"),e.estimatedDuration!==void 0&&(e.estimatedDuration<0||!Number.isFinite(e.estimatedDuration))&&t.push("estimatedDuration must be a non-negative number"),e.costHint!==void 0&&(e.costHint<0||!Number.isFinite(e.costHint))&&t.push("costHint must be a non-negative number"),e.tags){for(const r of e.tags)if(typeof r!="string"||r.length===0){t.push("All tags must be non-empty strings");break}}return t}function Ywr(e){const t=sh(e),r=y0e(t,e.annotations);return{...e,annotations:r}}function Zwr(e){return!!(e.annotations?.requiresConfirmation||e.annotations?.destructiveHint)}function v0e(e){return!!(e.annotations?.idempotentHint||e.annotations?.readOnlyHint)}function Qwr(e){return e.annotations?.destructiveHint?"dangerous":e.annotations?.readOnlyHint?"safe":(e.annotations?.idempotentHint,"moderate")}function ebr(e,t){return e.filter(r=>{const n=r.annotations??{};return t(n)})}function tbr(e){const t=[];return e.title&&t.push(e.title),e.readOnlyHint&&t.push("read-only"),e.destructiveHint&&t.push("DESTRUCTIVE"),e.idempotentHint&&t.push("idempotent"),e.requiresConfirmation&&t.push("requires confirmation"),e.complexity&&t.push(`${e.complexity} complexity`),e.estimatedDuration!==void 0&&t.push(`~${e.estimatedDuration}ms`),e.tags?.length&&t.push(`tags: ${e.tags.join(", ")}`),t.length>0?`[${t.join(" | ")}]`:"[no annotations]"}var M4=E({"src/lib/mcp/toolAnnotations.ts"(){"use strict"}}),rbr={};ae(rbr,{MultiServerManager:()=>P4,globalMultiServerManager:()=>_0e});var P4,_0e,w0e=E({"src/lib/mcp/multiServerManager.ts"(){"use strict";To(),G(),st(),P4=class extends On{config;servers=new Map;groups=new Map;metrics=new Map;roundRobinCounters=new Map;toolPreferences=new Map;constructor(e={}){super(),this.config={defaultStrategy:e.defaultStrategy??"round-robin",healthAwareRouting:e.healthAwareRouting??!0,healthCheckInterval:e.healthCheckInterval??3e4,maxFailoverRetries:e.maxFailoverRetries??3,namespaceSeparator:e.namespaceSeparator??".",autoNamespace:e.autoNamespace??!1,conflictResolution:e.conflictResolution??"first-wins"}}addServer(e){this.servers.set(e.id,e),this.metrics.set(e.id,{activeRequests:0,totalRequests:0,completedRequests:0,averageResponseTime:0,errorRate:0,isHealthy:e.status==="connected"}),this.emit("serverAdded",{serverId:e.id,server:e}),g.debug(`[MultiServerManager] Added server: ${e.id} (${e.name})`)}removeServer(e){if(!this.servers.get(e))return!1;for(const[r,n]of this.groups){const o=n.servers.indexOf(e);o!==-1&&(n.servers.splice(o,1),n.servers.length===0&&(this.groups.delete(r),this.roundRobinCounters.delete(r)))}this.servers.delete(e),this.metrics.delete(e);for(const[r,n]of this.toolPreferences)n===e&&this.toolPreferences.delete(r);return this.emit("serverRemoved",{serverId:e}),g.debug(`[MultiServerManager] Removed server: ${e}`),!0}updateServer(e,t){const r=this.servers.get(e);if(!r)throw Te.invalidConfiguration("serverId",`Server '${e}' not found`,{serverId:e});const n={...r,...t,id:e};this.servers.set(e,n);const o=this.metrics.get(e);o&&t.status!==void 0&&(o.isHealthy=t.status==="connected"),this.emit("serverUpdated",{serverId:e,server:n})}createGroup(e){for(const t of e.servers)if(!this.servers.has(t))throw Te.invalidConfiguration("serverGroup.servers",`Server '${t}' not found when creating group '${e.id}'`,{serverId:t,groupId:e.id});this.groups.set(e.id,e),this.roundRobinCounters.set(e.id,0),this.emit("groupCreated",{group:e}),g.debug(`[MultiServerManager] Created group: ${e.id} with ${e.servers.length} servers`)}removeGroup(e){const t=this.groups.delete(e);return t&&(this.roundRobinCounters.delete(e),this.emit("groupRemoved",{groupId:e})),t}addServerToGroup(e,t){const r=this.groups.get(t);if(!r)throw Te.invalidConfiguration("groupId",`Group '${t}' not found`,{groupId:t});if(!this.servers.has(e))throw Te.invalidConfiguration("serverId",`Server '${e}' not found`,{serverId:e,groupId:t});r.servers.includes(e)||(r.servers.push(e),this.emit("serverAddedToGroup",{serverId:e,groupId:t}))}removeServerFromGroup(e,t){const r=this.groups.get(t);if(!r)return!1;const n=r.servers.indexOf(e);return n!==-1?(r.servers.splice(n,1),this.emit("serverRemovedFromGroup",{serverId:e,groupId:t}),!0):!1}getUnifiedTools(){const e=new Map;for(const[t,r]of this.servers){const o=this.metrics.get(t)?.isHealthy??!0;if(!(this.config.healthAwareRouting&&!o))for(const i of r.tools||[]){const s=e.get(i.name);s?(s.hasConflict=!0,s.servers.push({serverId:t,serverName:r.name,inputSchema:i.inputSchema,priority:this.getServerPriority(t)})):e.set(i.name,{name:i.name,description:i.description,servers:[{serverId:t,serverName:r.name,inputSchema:i.inputSchema,priority:this.getServerPriority(t)}],hasConflict:!1,preferredServerId:this.toolPreferences.get(i.name)})}}for(const t of e.values())t.servers.sort((r,n)=>r.priority-n.priority),!t.preferredServerId&&t.servers.length>0&&(t.preferredServerId=t.servers[0].serverId);return Array.from(e.values())}getNamespacedTools(){const e=[];for(const[t,r]of this.servers)if(!(this.config.healthAwareRouting&&!(this.metrics.get(t)?.isHealthy??!0)))for(const n of r.tools||[])e.push({fullName:`${t}${this.config.namespaceSeparator}${n.name}`,toolName:n.name,serverId:t,serverName:r.name,description:n.description,inputSchema:n.inputSchema});return e}setToolPreference(e,t){if(!this.servers.has(t))throw Te.invalidConfiguration("serverId",`Server '${t}' not found`,{serverId:t,toolName:e});this.toolPreferences.set(e,t),this.emit("toolPreferenceSet",{toolName:e,serverId:t})}clearToolPreference(e){this.toolPreferences.delete(e)}selectServer(e,t){const r=this.toolPreferences.get(e);if(r){const c=this.servers.get(r),l=this.metrics.get(r);if(c&&(!this.config.healthAwareRouting||l?.isHealthy)&&c.tools?.some(u=>u.name===e))return{serverId:r,server:c}}let n;if(t){const c=this.groups.get(t);if(!c)return g.warn(`[MultiServerManager] Group '${t}' not found`),null;n=c.servers.filter(l=>this.servers.get(l)?.tools?.some(d=>d.name===e))}else{n=[];for(const[c,l]of this.servers)l.tools?.some(u=>u.name===e)&&n.push(c)}if(n.length===0)return null;if((t?this.groups.get(t)?.healthAware??this.config.healthAwareRouting:this.config.healthAwareRouting)&&(n=n.filter(c=>this.metrics.get(c)?.isHealthy??!0),n.length===0))return g.warn(`[MultiServerManager] No healthy servers available for tool '${e}'`),null;const i=t?this.groups.get(t)?.strategy??this.config.defaultStrategy:this.config.defaultStrategy,s=this.applyStrategy(i,n,t);if(!s)return null;const a=this.servers.get(s);return a?{serverId:s,server:a}:null}applyStrategy(e,t,r){if(t.length===0)return null;if(t.length===1)return t[0];switch(e){case"round-robin":{const n=r??"default",o=this.roundRobinCounters.get(n)??0,i=t[o%t.length];return this.roundRobinCounters.set(n,o+1),i}case"least-loaded":{let n=1/0,o=t[0];for(const i of t){const a=this.metrics.get(i)?.activeRequests??0;a<n&&(n=a,o=i)}return o}case"random":{const n=Math.floor(Math.random()*t.length);return t[n]}case"weighted":{if(!r){const c=Math.floor(Math.random()*t.length);return t[c]}const n=this.groups.get(r);if(!n?.weights){const c=Math.floor(Math.random()*t.length);return t[c]}const o=1,i=t.map(c=>{const u=(n.weights??[]).find(d=>d.serverId===c);return{serverId:c,weight:u?.weight??o}}),s=i.reduce((c,l)=>c+l.weight,0);if(s===0){const c=Math.floor(Math.random()*t.length);return t[c]}let a=Math.random()*s;for(const c of i)if(a-=c.weight,a<=0)return c.serverId;return t[0]}case"failover-only":return t.map(o=>({id:o,priority:this.getServerPriority(o,r)})).sort((o,i)=>o.priority-i.priority)[0]?.id??null;default:return t[0]}}getServerPriority(e,t){if(t){const n=this.groups.get(t);if(n?.weights){const o=n.weights.find(i=>i.serverId===e);if(o)return o.priority}}for(const n of this.groups.values())if(n.weights){const o=n.weights.find(i=>i.serverId===e);if(o)return o.priority}return Array.from(this.servers.keys()).indexOf(e)}updateMetrics(e,t){const r=this.metrics.get(e);r&&(Object.assign(r,t),this.emit("metricsUpdated",{serverId:e,metrics:{...r}}))}requestStarted(e){const t=this.metrics.get(e);t&&(t.activeRequests++,t.totalRequests++)}requestCompleted(e,t,r){const n=this.metrics.get(e);if(n){n.activeRequests=Math.max(0,n.activeRequests-1),n.completedRequests++;const o=n.averageResponseTime*(n.completedRequests-1)+t;n.averageResponseTime=o/n.completedRequests;const i=.1;n.errorRate=n.errorRate*(1-i)+(r?0:1)*i}}getServers(){return Array.from(this.servers.values())}getServer(e){return this.servers.get(e)}getGroups(){return Array.from(this.groups.values())}getGroup(e){return this.groups.get(e)}getServerMetrics(e){return this.metrics.get(e)}getAllMetrics(){return new Map(this.metrics)}getStatistics(){let e=0,t=0,r=0;for(const i of this.metrics.values())i.isHealthy&&e++,t+=i.totalRequests,r+=i.activeRequests;const n=this.getUnifiedTools(),o=n.filter(i=>i.hasConflict).length;return{totalServers:this.servers.size,healthyServers:e,totalGroups:this.groups.size,totalTools:n.length,conflictingTools:o,totalRequests:t,activeRequests:r}}},_0e=new P4}}),nbr={};ae(nbr,{EnhancedToolDiscovery:()=>bB});var bB,b0e=E({"src/lib/mcp/enhancedToolDiscovery.ts"(){"use strict";To(),G(),on(),st(),M4(),w0e(),bB=class extends On{toolRegistry=new Map;serverToolsMap=new Map;multiServerManager;discoveryInProgress=new Set;constructor(e){super(),this.multiServerManager=e??new P4}async discoverToolsWithAnnotations(e,t,r=1e4){const n=Date.now();if(this.discoveryInProgress.has(e))return{success:!1,error:`Discovery already in progress for server: ${e}`,toolCount:0,tools:[],duration:Date.now()-n,serverId:e};this.discoveryInProgress.add(e);try{g.info(`[EnhancedToolDiscovery] Starting discovery with annotations for: ${e}`);const o=await Dt(t.listTools(),r,"Discovery timeout");if(!o?.tools)throw Te.toolExecutionFailed("discoverTools",new Error("No tools returned from server"),e);this.clearServerTools(e);const i=[];for(const s of o.tools){const a=this.createEnhancedToolInfo(e,s),c=this.createToolKey(e,s.name);this.toolRegistry.set(c,a);let l=this.serverToolsMap.get(e);l||(l=new Set,this.serverToolsMap.set(e,l)),l.add(s.name),i.push(a),this.emit("toolDiscovered",{serverId:e,toolName:s.name,annotations:a.annotations,timestamp:new Date})}return g.info(`[EnhancedToolDiscovery] Discovered ${i.length} tools with annotations from ${e}`),{success:!0,toolCount:i.length,tools:i,duration:Date.now()-n,serverId:e}}catch(o){const i=o instanceof Error?o.message:String(o);return g.error(`[EnhancedToolDiscovery] Discovery failed for ${e}:`,o),{success:!1,error:i,toolCount:0,tools:[],duration:Date.now()-n,serverId:e}}finally{this.discoveryInProgress.delete(e)}}createEnhancedToolInfo(e,t){const r=sh({name:t.name,description:t.description??""});return{name:t.name,description:t.description??"No description provided",serverId:e,inputSchema:t.inputSchema,isAvailable:!0,annotations:r,version:"1.0.0",stats:{totalCalls:0,successfulCalls:0,failedCalls:0,averageExecutionTime:0,lastExecutionTime:0},metadata:{category:this.inferCategory(t),deprecated:!1}}}inferCategory(e){const t=e.name.toLowerCase(),r=(e.description??"").toLowerCase();return t.includes("git")||r.includes("git")?"version-control":t.includes("file")||t.includes("read")||t.includes("write")?"file-system":t.includes("api")||t.includes("http")?"api":t.includes("data")||t.includes("query")?"data":t.includes("auth")||t.includes("login")?"authentication":t.includes("deploy")||t.includes("build")?"deployment":"general"}searchTools(e){const t=Date.now();let r=Array.from(this.toolRegistry.values());if(e.name){const o=e.name.toLowerCase();r=r.filter(i=>i.name.toLowerCase().includes(o))}if(e.description){const o=e.description.toLowerCase().split(/\s+/);r=r.filter(i=>{const s=i.description.toLowerCase();return o.some(a=>s.includes(a))})}if(e.serverIds?.length){const o=e.serverIds;r=r.filter(i=>o.includes(i.serverId))}if(e.category&&(r=r.filter(o=>o.metadata?.category===e.category)),e.tags?.length){const o=e.tags;r=r.filter(i=>{const s=i.annotations?.tags??[];return o.some(a=>s.includes(a))})}if(e.annotations){const o=e.annotations;r=r.filter(i=>{if(!i.annotations)return!1;for(const[s,a]of Object.entries(o)){const c=s;if(i.annotations[c]!==a)return!1}return!0})}if(e.includeUnavailable||(r=r.filter(o=>o.isAvailable)),e.sortBy){const o=e.sortDirection==="desc"?-1:1;r.sort((i,s)=>{let a=0;switch(e.sortBy){case"name":a=i.name.localeCompare(s.name);break;case"calls":a=i.stats.totalCalls-s.stats.totalCalls;break;case"successRate":{const c=i.stats.totalCalls>0?i.stats.successfulCalls/i.stats.totalCalls:0,l=s.stats.totalCalls>0?s.stats.successfulCalls/s.stats.totalCalls:0;a=c-l;break}case"avgExecutionTime":a=i.stats.averageExecutionTime-s.stats.averageExecutionTime;break}return a*o})}const n=r.length;return e.limit&&e.limit>0&&(r=r.slice(0,e.limit)),{tools:r,totalCount:n,criteria:e,executionTime:Date.now()-t}}getToolsBySafetyLevel(e){return Array.from(this.toolRegistry.values()).filter(t=>{const r=t.annotations??{};switch(e){case"dangerous":return r.destructiveHint===!0;case"safe":return r.readOnlyHint===!0;case"moderate":return!r.destructiveHint&&!r.readOnlyHint;default:return!1}})}getToolsRequiringConfirmation(){return Array.from(this.toolRegistry.values()).filter(e=>e.annotations?.requiresConfirmation===!0||e.annotations?.destructiveHint===!0)}getReadOnlyTools(){return Array.from(this.toolRegistry.values()).filter(e=>e.annotations?.readOnlyHint===!0)}getUnifiedTools(){return this.multiServerManager.getUnifiedTools()}registerServer(e){this.multiServerManager.addServer(e)}updateToolAnnotations(e,t,r){const n=this.createToolKey(e,t),o=this.toolRegistry.get(n);return o?(o.annotations={...o.annotations,...r},this.emit("annotationsUpdated",{serverId:e,toolName:t,annotations:o.annotations,timestamp:new Date}),!0):!1}checkCompatibility(e,t,r){const n=this.createToolKey(t,e),o=this.toolRegistry.get(n),i=[],s=[],a=[];if(!o)return{compatible:!1,issues:[`Tool '${e}' not found on server '${t}'`],warnings:[],recommendations:[]};if(r&&o.version){const c=o.version.split(".").map(Number),l=r.split(".").map(Number);c.some(isNaN)||l.some(isNaN)?s.push(`Non-standard version format: tool=${o.version}, target=${r}`):c[0]!==l[0]?i.push(`Major version mismatch: tool is v${o.version}, target is v${r}`):c[1]<l[1]&&s.push(`Minor version mismatch: tool is v${o.version}, target is v${r}`)}return o.metadata?.deprecated&&(s.push("This tool is marked as deprecated"),a.push("Consider using an alternative tool if available")),o.annotations?.securityLevel==="restricted"&&a.push("This tool requires elevated permissions"),{compatible:i.length===0,issues:i,warnings:s,recommendations:a}}getTool(e,t){return this.toolRegistry.get(this.createToolKey(e,t))}getAllTools(){return Array.from(this.toolRegistry.values())}getServerTools(e){const t=this.serverToolsMap.get(e);return t?Array.from(t).map(r=>this.getTool(e,r)).filter(r=>r!==void 0):[]}clearServerTools(e){const t=this.serverToolsMap.get(e);if(t){for(const r of t)this.toolRegistry.delete(this.createToolKey(e,r));this.serverToolsMap.delete(e)}}createToolKey(e,t){return`${e}:${t}`}getStatistics(){const e={},t={},r={safe:0,moderate:0,dangerous:0};let n=0,o=0;for(const i of this.toolRegistry.values()){e[i.serverId]=(e[i.serverId]??0)+1;const s=i.metadata?.category??"general";t[s]=(t[s]??0)+1,i.annotations?.destructiveHint?r.dangerous++:i.annotations?.readOnlyHint?r.safe++:r.moderate++,i.annotations&&Object.keys(i.annotations).length>0&&n++,i.metadata?.deprecated&&o++}return{totalTools:this.toolRegistry.size,toolsByServer:e,toolsByCategory:t,toolsBySafetyLevel:r,toolsWithAnnotations:n,deprecatedTools:o}}}}}),obr,T0e,E0e,O4,S0e=E({"src/lib/mcp/mcpCircuitBreaker.ts"(){"use strict";To(),Gt(),G(),ft(),ft(),obr=Math.max(1e4,Number(process.env.MCP_OPERATION_TIMEOUT)||6e4),T0e=class extends On{constructor(e,t={}){super(),this.name=e,this.config={failureThreshold:t.failureThreshold??5,resetTimeout:t.resetTimeout??6e4,halfOpenMaxCalls:t.halfOpenMaxCalls??3,operationTimeout:t.operationTimeout??obr,minimumCallsBeforeCalculation:t.minimumCallsBeforeCalculation??10,statisticsWindowSize:t.statisticsWindowSize??3e5},this.cleanupTimer=setInterval(()=>this.cleanupCallHistory(),6e4),this.cleanupTimer.unref&&this.cleanupTimer.unref()}name;state="closed";config;callHistory=[];lastFailureTime=0;halfOpenCalls=0;lastStateChange=new Date;cleanupTimer;async execute(e,t){const r=Date.now();try{if(this.state==="open"){const s=this.config.resetTimeout-(Date.now()-this.lastFailureTime);if(s>0)throw new ef({breakerName:this.name,retryAfter:new Date(this.lastFailureTime+this.config.resetTimeout),retryAfterMs:s,breakerState:"open",failureCount:this.getStats().failedCalls});this.changeState("half-open","Reset timeout reached")}if(this.state==="half-open"&&this.halfOpenCalls>=this.config.halfOpenMaxCalls)throw this.lastFailureTime=Date.now(),this.changeState("open","Half-open call limit reached, reverting to open"),new ef({breakerName:this.name,retryAfter:new Date(this.lastFailureTime+this.config.resetTimeout),retryAfterMs:this.config.resetTimeout,breakerState:"open",failureCount:this.getStats().failedCalls});if(this.state==="half-open"){const s=Xt.getActiveSpan();s&&s.addEvent("circuit.half_open_test",{"circuit.name":this.name,"circuit.half_open_call":this.halfOpenCalls+1,"circuit.half_open_max_calls":this.config.halfOpenMaxCalls})}let n;const o=s=>{n=s||"Operation resolved a failure result"},i=await this.raceWithTimeout(e(o),this.config.operationTimeout);return n!==void 0?(this.recordFailureOutcome(n,Date.now()-r),i):(this.recordCall(!0,Date.now()-r),this.state==="half-open"&&(this.halfOpenCalls++,this.halfOpenCalls>=this.config.halfOpenMaxCalls&&this.changeState("closed","Half-open test successful")),i)}catch(n){if(t?.isCancelled?.())throw n;const o=Date.now()-r,i=n instanceof Error?n.message:String(n);throw this.recordFailureOutcome(i,o),n}}recordFailureOutcome(e,t){this.recordCall(!1,t),this.emit("callFailure",{error:e,duration:t,timestamp:new Date}),this.state==="half-open"?this.changeState("open",`Half-open test failed: ${e}`):this.state==="closed"&&this.checkFailureThreshold()}recordCall(e,t){const r=Date.now();this.callHistory.push({timestamp:r,success:e,duration:t}),e&&this.emit("callSuccess",{duration:t,timestamp:new Date}),e||(this.lastFailureTime=r)}checkFailureThreshold(){const e=Date.now()-this.config.statisticsWindowSize,t=this.callHistory.filter(o=>o.timestamp>=e);if(t.length<this.config.minimumCallsBeforeCalculation)return;const r=t.filter(o=>!o.success).length,n=r/t.length;le.debug(`[CircuitBreaker:${this.name}] Failure rate: ${(n*100).toFixed(1)}% (${r}/${t.length})`),r>=this.config.failureThreshold&&(this.changeState("open",`Failure threshold exceeded: ${r} failures`),this.emit("circuitOpen",{failureRate:n,totalCalls:t.length,timestamp:new Date}))}changeState(e,t){const r=this.state;this.state=e,this.lastStateChange=new Date;const n=Xt.getActiveSpan();n&&n.addEvent("circuit.state_change",{"circuit.name":this.name,"circuit.from_state":r,"circuit.to_state":e,"circuit.reason":t.slice(0,128),"circuit.failure_count":this.callHistory.filter(o=>!o.success).length}),e==="half-open"?(this.halfOpenCalls=0,this.emit("circuitHalfOpen",{timestamp:new Date})):e==="closed"&&(this.halfOpenCalls=0,this.emit("circuitClosed",{timestamp:new Date})),le.info(`[CircuitBreaker:${this.name}] State changed: ${r} -> ${e} (${t})`),this.emit("stateChange",{oldState:r,newState:e,reason:t,timestamp:new Date})}async raceWithTimeout(e,t){let r;const n=new Promise((o,i)=>{r=setTimeout(()=>{i(new Error(`Operation timed out after ${t}ms`))},t)});try{return await Promise.race([e,n])}finally{clearTimeout(r)}}cleanupCallHistory(){const e=Date.now()-this.config.statisticsWindowSize,t=this.callHistory.length;this.callHistory=this.callHistory.filter(n=>n.timestamp>=e);const r=t-this.callHistory.length;r>0&&le.debug(`[CircuitBreaker:${this.name}] Cleaned up ${r} old call records`)}getStats(){const e=Date.now()-this.config.statisticsWindowSize,t=this.callHistory.filter(i=>i.timestamp>=e),r=t.filter(i=>i.success).length,n=t.length-r,o=t.length>0?n/t.length:0;return{state:this.state,totalCalls:this.callHistory.length,successfulCalls:this.callHistory.filter(i=>i.success).length,failedCalls:this.callHistory.filter(i=>!i.success).length,failureRate:o,windowCalls:t.length,lastStateChange:this.lastStateChange,nextRetryTime:this.state==="open"?new Date(this.lastFailureTime+this.config.resetTimeout):void 0,halfOpenCalls:this.halfOpenCalls}}reset(){this.changeState("closed","Manual reset"),this.callHistory=[],this.lastFailureTime=0,this.halfOpenCalls=0}forceOpen(e="Manual force open"){this.changeState("open",e),this.lastFailureTime=Date.now()}getName(){return this.name}isOpen(){return this.state==="open"}isClosed(){return this.state==="closed"}isHalfOpen(){return this.state==="half-open"}destroy(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0,le.debug(`[CircuitBreaker:${this.name}] Cleanup timer cleared`)),this.removeAllListeners(),this.callHistory=[],le.debug(`[CircuitBreaker:${this.name}] Destroyed and cleaned up`)}},E0e=class{breakers=new Map;getBreaker(e,t){if(!this.breakers.has(e)){const n=new T0e(e,t);this.breakers.set(e,n),le.debug(`[CircuitBreakerManager] Created circuit breaker: ${e}`)}const r=this.breakers.get(e);if(!r)throw new Error(`Circuit breaker ${e} not found after creation`);return r}removeBreaker(e){const t=this.breakers.get(e);return t?(t.destroy(),this.breakers.delete(e),le.debug(`[CircuitBreakerManager] Removed and cleaned up circuit breaker: ${e}`),!0):!1}getBreakerNames(){return Array.from(this.breakers.keys())}getAllStats(){const e={};for(const[t,r]of this.breakers)e[t]=r.getStats();return e}resetAll(){for(const e of this.breakers.values())e.reset();le.info("[CircuitBreakerManager] Reset all circuit breakers")}getHealthSummary(){let e=0,t=0,r=0;const n=[];for(const[o,i]of this.breakers)switch(i.getStats().state){case"closed":e++;break;case"open":t++,n.push(o);break;case"half-open":r++;break}return{totalBreakers:this.breakers.size,closedBreakers:e,openBreakers:t,halfOpenBreakers:r,unhealthyBreakers:n}}destroyAll(){for(const e of this.breakers.values())e.destroy();this.breakers.clear(),le.info("[CircuitBreakerManager] Destroyed all circuit breakers")}},O4=new E0e}});function eLn(e){return new Promise(t=>setTimeout(t,e))}function TB(e,t=Jp){return t.retryableStatusCodes.includes(e)}function ibr(e,t=Jp){if(!e||typeof e!="object")return!1;const r=e;if(cr(e))return!1;if(r.name==="TimeoutError"||r.code==="TIMEOUT"||r.code==="ETIMEDOUT"||r.code==="ECONNRESET"||r.code==="ENOTFOUND"||r.code==="ECONNREFUSED"||r.code==="ECONNABORTED"||r.code==="EPIPE"||r.code==="ENETUNREACH"||r.code==="EHOSTUNREACH")return!0;if(r.name==="TypeError"&&typeof r.message=="string"){const n=r.message.toLowerCase();if(n.includes("fetch")||n.includes("network")||n.includes("connection"))return!0}return typeof r.status=="number"?TB(r.status,t):r.response&&typeof r.response=="object"&&typeof r.response.status=="number"?TB(r.response.status,t):typeof r.statusCode=="number"?TB(r.statusCode,t):!1}async function sbr(e,t={}){const r={...Jp,...t},{traceId:n,parentSpanId:o}=Cy(),i=Oe.createSpan("mcp.transport","mcp.retry",{"mcp.transport":"http","mcp.operation":"retry","mcp.maxAttempts":r.maxAttempts},o,n),s=Date.now();let a,c=0;for(let u=1;u<=r.maxAttempts;u++){c=u;try{const d=await e();i.durationMs=Date.now()-s,i.attributes["mcp.retryAttempt"]=u;const p=Oe.endSpan(i,1);return pt().recordSpan(p),d}catch(d){if(a=d,u===r.maxAttempts){g.debug(`HTTP retry: All ${r.maxAttempts} attempts exhausted`);break}if(!ibr(d,r)){g.debug("HTTP retry: Non-retryable error encountered",d instanceof Error?d.message:String(d));break}const p=x2t(u,r.initialDelay,r.backoffMultiplier,r.maxDelay,!0),m=d instanceof Error?d.message:String(d);g.warn(`HTTP retry: Attempt ${u}/${r.maxAttempts} failed: ${m}. Retrying in ${Math.round(p)}ms...`),await eLn(p)}}i.durationMs=Date.now()-s,i.attributes["mcp.retryAttempt"]=c;const l=Oe.endSpan(i,2);throw l.statusMessage=a instanceof Error?a.message:String(a),pt().recordSpan(l),a}var Jp,abr=E({"src/lib/mcp/httpRetryHandler.ts"(){"use strict";st(),O2t(),G(),wo(),xy(),Jp={maxAttempts:3,initialDelay:1e3,maxDelay:3e4,backoffMultiplier:2,retryableStatusCodes:[408,429,500,502,503,504]}}}),k0e,A0e,C0e,x0e,cbr=E({"src/lib/mcp/httpRateLimiter.ts"(){"use strict";G(),HC(),wo(),xy(),k0e={requestsPerWindow:60,windowMs:6e4,useTokenBucket:!0,refillRate:1,maxBurst:10},A0e=class{tokens;lastRefill;config;waitQueue=[];processingQueue=!1;constructor(e={}){this.config={...k0e,...e},this.tokens=this.config.maxBurst,this.lastRefill=Date.now(),le.debug("[HTTPRateLimiter] Initialized with config:",{requestsPerWindow:this.config.requestsPerWindow,windowMs:this.config.windowMs,useTokenBucket:this.config.useTokenBucket,refillRate:this.config.refillRate,maxBurst:this.config.maxBurst})}refillTokens(){const e=Date.now(),n=(e-this.lastRefill)/1e3*this.config.refillRate;if(n>=1){const o=this.tokens;this.tokens=Math.min(this.config.maxBurst,this.tokens+n),this.lastRefill=e,this.tokens>o&&le.debug(`[HTTPRateLimiter] Refilled tokens: ${o.toFixed(2)} -> ${this.tokens.toFixed(2)} (+${n.toFixed(2)})`)}}async acquire(){const{traceId:e,parentSpanId:t}=Cy(),r=Oe.createSpan("mcp.transport","mcp.rateLimit",{"mcp.transport":"http","mcp.operation":"rateLimit","mcp.rateLimit.tokensAvailable":this.tokens,"mcp.rateLimit.maxBurst":this.config.maxBurst},t,e),n=Date.now();try{if(this.tryAcquire()){r.durationMs=Date.now()-n,r.attributes["mcp.rateLimit.waited"]=!1;const i=Oe.endSpan(r,1);pt().recordSpan(i);return}await new Promise((i,s)=>{this.waitQueue.push({resolve:i,reject:s}),le.debug(`[HTTPRateLimiter] Request queued, queue length: ${this.waitQueue.length}`),this.processingQueue||this.processQueue()}),r.durationMs=Date.now()-n,r.attributes["mcp.rateLimit.waited"]=!0;const o=Oe.endSpan(r,1);pt().recordSpan(o)}catch(o){r.durationMs=Date.now()-n;const i=Oe.endSpan(r,2);throw i.statusMessage=o instanceof Error?o.message:String(o),pt().recordSpan(i),o}}async processQueue(){if(!this.processingQueue){for(this.processingQueue=!0;this.waitQueue.length>0;)if(this.refillTokens(),this.tokens>=1){const e=this.waitQueue.shift();e&&(this.tokens-=1,le.debug(`[HTTPRateLimiter] Token granted from queue, remaining: ${this.tokens.toFixed(2)}, queue: ${this.waitQueue.length}`),e.resolve())}else{const t=(1-this.tokens)/this.config.refillRate*1e3,r=Math.max(10,Math.ceil(t));le.debug(`[HTTPRateLimiter] Waiting ${r}ms for token refill`),await this.sleep(r)}this.processingQueue=!1}}sleep(e){return new Promise(t=>setTimeout(t,e))}tryAcquire(){return this.refillTokens(),this.tokens>=1?(this.tokens-=1,le.debug(`[HTTPRateLimiter] Token acquired, remaining: ${this.tokens.toFixed(2)}`),!0):(le.debug(`[HTTPRateLimiter] No tokens available, current: ${this.tokens.toFixed(2)}`),!1)}handleRateLimitResponse(e){const t=Sb(e),r=e.get("Retry-After");if(r&&t!==void 0){const i=parseInt(r,10);if(isNaN(i)){const s=new Date(r);if(!isNaN(s.getTime()))return le.info(`[HTTPRateLimiter] Server requested retry at ${s.toISOString()} (${t}ms)`),t}else return le.info(`[HTTPRateLimiter] Server requested retry after ${i} seconds`),t}const n=e.get("X-RateLimit-Reset");if(n&&t!==void 0){const i=parseInt(n,10);if(!isNaN(i)){const s=i>1e12?i:i*1e3;return le.info(`[HTTPRateLimiter] Rate limit resets at ${new Date(s).toISOString()} (${t}ms)`),t}}return e.get("X-RateLimit-Remaining")==="0"&&t!==void 0?(le.info(`[HTTPRateLimiter] Rate limit exhausted, using default backoff: ${t}ms`),t):t??0}getRemainingTokens(){return this.refillTokens(),this.tokens}reset(){for(this.tokens=this.config.maxBurst,this.lastRefill=Date.now();this.waitQueue.length>0;){const e=this.waitQueue.shift();e&&e.reject(new Error("Rate limiter was reset"))}le.info(`[HTTPRateLimiter] Reset to initial state, tokens: ${this.tokens}`)}getStats(){return this.refillTokens(),{tokens:this.tokens,maxBurst:this.config.maxBurst,refillRate:this.config.refillRate,queueLength:this.waitQueue.length,lastRefill:new Date(this.lastRefill)}}updateConfig(e){Object.assign(this.config,e),le.info("[HTTPRateLimiter] Configuration updated:",e)}getConfig(){return{...this.config}}},C0e=class{limiters=new Map;getLimiter(e,t){let r=this.limiters.get(e);return r?t&&r.updateConfig(t):(r=new A0e(t),this.limiters.set(e,r),le.debug(`[RateLimiterManager] Created rate limiter for server: ${e}`)),r}hasLimiter(e){return this.limiters.has(e)}removeLimiter(e){const t=this.limiters.get(e);t&&(t.reset(),this.limiters.delete(e),le.debug(`[RateLimiterManager] Removed rate limiter for server: ${e}`))}getServerIds(){return Array.from(this.limiters.keys())}getAllStats(){const e={};for(const[t,r]of this.limiters)e[t]=r.getStats();return e}resetAll(){for(const e of this.limiters.values())e.reset();le.info("[RateLimiterManager] Reset all rate limiters")}destroyAll(){for(const e of this.limiters.values())e.reset();this.limiters.clear(),le.info("[RateLimiterManager] Destroyed all rate limiters")}getHealthSummary(){const e=[];let t=0,r=0;for(const[o,i]of this.limiters){const s=i.getStats();s.queueLength>0&&(e.push(o),t+=s.queueLength),r+=s.tokens}const n=this.limiters.size>0?r/this.limiters.size:0;return{totalLimiters:this.limiters.size,serversWithQueuedRequests:e,totalQueuedRequests:t,averageTokensAvailable:n}}},x0e=new C0e}});function lbr(e,t=60){if(!e.expiresAt)return!1;const r=t*1e3,n=Date.now();return e.expiresAt-r<=n}function I0e(e){return Date.now()+e*1e3}var EB,ubr,dbr=E({"src/lib/mcp/auth/tokenStorage.ts"(){"use strict";G(),EB=class{tokens=new Map;async getTokens(e){return this.tokens.get(e)??null}async saveTokens(e,t){this.tokens.set(e,t)}async deleteTokens(e){this.tokens.delete(e)}async hasTokens(e){return this.tokens.has(e)}async clearAll(){this.tokens.clear()}get size(){return this.tokens.size}getServerIds(){return Array.from(this.tokens.keys())}},ubr=class{filePath;tokens=new Map;loaded=!1;constructor(e){this.filePath=e}async loadTokens(){if(!this.loaded)try{const t=await(await Promise.resolve().then(()=>(Fi(),Xy))).readFile(this.filePath,"utf-8"),r=JSON.parse(t);this.tokens=new Map(Object.entries(r)),this.loaded=!0}catch(e){e instanceof Error&&"code"in e&&e.code!=="ENOENT"&&g.warn(`[FileTokenStorage] Error loading tokens: ${e.message}`),this.tokens=new Map,this.loaded=!0}}async saveToFile(){try{const e=await Promise.resolve().then(()=>(Fi(),Xy)),t=await Promise.resolve().then(()=>(Nr(),qh)),{randomBytes:r}=await Promise.resolve().then(()=>(tr(),Ew)),n=t.dirname(this.filePath);await e.mkdir(n,{recursive:!0,mode:448});const o=Object.fromEntries(this.tokens.entries()),i=`${this.filePath}.${process.pid}.${r(6).toString("hex")}.tmp`;try{await e.writeFile(i,JSON.stringify(o,null,2),{encoding:"utf-8",mode:384,flag:"wx"}),await e.rename(i,this.filePath),await e.chmod(this.filePath,384)}catch(s){throw await e.rm(i,{force:!0}),s}}catch(e){throw g.error(`[FileTokenStorage] Error saving tokens: ${e instanceof Error?e.message:String(e)}`),e}}async getTokens(e){return await this.loadTokens(),this.tokens.get(e)??null}async saveTokens(e,t){await this.loadTokens(),this.tokens.set(e,t),await this.saveToFile()}async deleteTokens(e){await this.loadTokens(),this.tokens.delete(e),await this.saveToFile()}async hasTokens(e){return await this.loadTokens(),this.tokens.has(e)}async clearAll(){this.tokens.clear(),await this.saveToFile()}}}});function tLn(e,t){return new SB({clientId:e.clientId,clientSecret:e.clientSecret,authorizationUrl:e.authorizationUrl,tokenUrl:e.tokenUrl,redirectUrl:e.redirectUrl,scope:e.scope,usePKCE:e.usePKCE??!0},t)}var r_,SB,rLn=E({"src/lib/mcp/auth/oauthClientProvider.ts"(){"use strict";tr(),dbr(),G(),st(),r_=3e4,SB=class{config;storage;pendingChallenges=new Map;pendingStates=new Set;constructor(e,t){this.config={...e,usePKCE:e.usePKCE??!0},this.storage=t??new EB}async tokens(e){const t=await this.storage.getTokens(e);if(!t)return null;if(lbr(t)){if(t.refreshToken)try{return await this.refreshTokens(e,t.refreshToken)}catch(r){return g.warn(`[NeuroLinkOAuthProvider] Token refresh failed: ${r instanceof Error?r.message:String(r)}`),await this.storage.deleteTokens(e),null}return await this.storage.deleteTokens(e),null}return t}async saveTokens(e,t){await this.storage.saveTokens(e,t)}async deleteTokens(e){await this.storage.deleteTokens(e)}clientInformation(){return{clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:this.config.redirectUrl}}redirectToAuthorization(e){const t=this.generateState();this.pendingStates.add(t);const r=new URL(this.config.authorizationUrl);r.searchParams.set("response_type","code"),r.searchParams.set("client_id",this.config.clientId),r.searchParams.set("redirect_uri",this.config.redirectUrl),r.searchParams.set("state",t),this.config.scope&&r.searchParams.set("scope",this.config.scope);let n;if(this.config.usePKCE){const o=this.generatePKCE();n=o.codeVerifier,this.pendingChallenges.set(t,o),r.searchParams.set("code_challenge",o.codeChallenge),r.searchParams.set("code_challenge_method",o.codeChallengeMethod)}if(this.config.additionalParams)for(const[o,i]of Object.entries(this.config.additionalParams))r.searchParams.set(o,i);return{url:r.toString(),state:t,codeVerifier:n}}async exchangeCode(e,t){if(!this.pendingStates.has(t.state))throw new Error("Invalid or expired state parameter");this.pendingStates.delete(t.state);let r=t.codeVerifier;if(this.config.usePKCE&&!r){const a=this.pendingChallenges.get(t.state);a&&(r=a.codeVerifier,this.pendingChallenges.delete(t.state))}const n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",t.code),n.set("redirect_uri",this.config.redirectUrl),n.set("client_id",this.config.clientId),this.config.clientSecret&&n.set("client_secret",this.config.clientSecret),r&&n.set("code_verifier",r);const o=await Je(fetch(this.config.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:n.toString()}),r_,new Error(`OAuth token exchange timed out after ${r_}ms`));if(!o.ok){const a=await o.text();throw new Error(`Token exchange failed: ${o.status} ${o.statusText} - ${a}`)}const i=await o.json(),s={accessToken:i.access_token,refreshToken:i.refresh_token,expiresAt:i.expires_in?I0e(i.expires_in):void 0,tokenType:i.token_type??"Bearer",scope:i.scope};return await this.saveTokens(e,s),s}async refreshTokens(e,t){const r=new URLSearchParams;r.set("grant_type","refresh_token"),r.set("refresh_token",t),r.set("client_id",this.config.clientId),this.config.clientSecret&&r.set("client_secret",this.config.clientSecret);const n=await Je(fetch(this.config.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:r.toString()}),r_,new Error(`OAuth token refresh timed out after ${r_}ms`));if(!n.ok){const s=await n.text();throw new Error(`Token refresh failed: ${n.status} ${n.statusText} - ${s}`)}const o=await n.json(),i={accessToken:o.access_token,refreshToken:o.refresh_token??t,expiresAt:o.expires_in?I0e(o.expires_in):void 0,tokenType:o.token_type??"Bearer",scope:o.scope};return await this.saveTokens(e,i),i}async revokeTokens(e,t){const r=await this.storage.getTokens(e);if(!r)return;const n=new URLSearchParams;n.set("token",r.accessToken),n.set("client_id",this.config.clientId),this.config.clientSecret&&n.set("client_secret",this.config.clientSecret);try{await Je(fetch(t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()}),r_,new Error(`OAuth token revocation timed out after ${r_}ms`))}catch(o){g.warn(`[NeuroLinkOAuthProvider] Token revocation failed: ${o instanceof Error?o.message:String(o)}`)}await this.storage.deleteTokens(e)}async getAuthorizationHeader(e){const t=await this.tokens(e);return t?`${t.tokenType} ${t.accessToken}`:null}async hasValidTokens(e){return await this.tokens(e)!==null}generateState(){return f0(32).toString("base64url")}generatePKCE(){const e=f0(32).toString("base64url"),t=Bu("sha256").update(e).digest("base64url");return{codeVerifier:e,codeChallenge:t,codeChallengeMethod:"S256"}}getConfig(){return{...this.config}}getStorage(){return this.storage}cleanupPendingRequests(){this.pendingStates.size>100&&this.pendingStates.clear(),this.pendingChallenges.size>100&&this.pendingChallenges.clear()}}}}),pbr=E({"src/lib/mcp/auth/index.ts"(){"use strict";dbr(),rLn()}});function nLn(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function oLn(e){const t=e.endsWith(".")?e.slice(0,-1):e;return t==="localhost"||t.endsWith(".localhost")}function R0e(e){const t=CT(e);if(t===0)throw new Error(`"${e}" is not an IP address`);const r=t===4?"ipv4":"ipv6";return kB.check(e,r)?"loopback":nc.check(e,r)?"private":"public"}function gd(e){return e.serverId?`MCP server "${e.serverId}" (${e.transport})`:`MCP ${e.transport} transport`}async function iLn(e){return(await u$(e,{all:!0,verbatim:!0})).map(r=>r.address)}async function mbr(e,t){let r;try{r=new URL(e)}catch{throw new Error(`${gd(t)}: "${e}" is not a valid URL`)}const n=r.protocol,o=fbr.has(n);if(!o&&!hbr.has(n))throw new Error(`${gd(t)}: scheme "${n}" is not allowed (use https:, wss:, or http:/ws: for a loopback host)`);const i=nLn(r.hostname).toLowerCase();if(i.length===0)throw new Error(`${gd(t)}: "${e}" has no host`);if(t.hostOwnedEgress===!0)return;const s=t.allowPrivateNetwork===!0,a=oLn(i)?"loopback":CT(i)!==0?R0e(i):void 0;if(a!==void 0){if(a==="loopback")return;if(!s){if(a==="private")throw new Error(`${gd(t)}: "${e}" points at a private, link-local or metadata address; set "allowPrivateNetwork": true on this server if that is intended`);if(!o)throw new Error(`${gd(t)}: "${e}" uses plaintext ${n} to a non-loopback host; use ${n==="ws:"?"wss:":"https:"}`);return}if(a==="public"&&!o)throw new Error(`${gd(t)}: "${e}" uses plaintext ${n} to a public host; allowPrivateNetwork only permits plaintext to private addresses`);return}if(!o&&!s)throw new Error(`${gd(t)}: "${e}" uses plaintext ${n} to a non-loopback host; use ${n==="ws:"?"wss:":"https:"}, or set "allowPrivateNetwork": true for a server on your own network`);let c;try{c=await iLn(i)}catch(u){throw new Error(`${gd(t)}: host "${i}" could not be resolved (${u instanceof Error?u.message:String(u)})`,{cause:u})}if(c.length===0)throw new Error(`${gd(t)}: host "${i}" resolved to no addresses`);const l=c.map(u=>({address:u,cls:R0e(u)}));if(!s){const u=l.find(d=>d.cls!=="public");if(u)throw new Error(`${gd(t)}: host "${i}" resolves to ${u.address}, a ${u.cls} address; set "allowPrivateNetwork": true on this server if that is intended`);return}if(!o&&l.some(u=>u.cls==="public"))throw new Error(`${gd(t)}: "${e}" uses plaintext ${n} to a host that resolves to a public address; allowPrivateNetwork only permits plaintext to private addresses`)}var hbr,fbr,kB,nc,gbr=E({"src/lib/mcp/transportUrlPolicy.ts"(){"use strict";rPt(),_se(),hbr=new Set(["http:","ws:"]),fbr=new Set(["https:","wss:"]),kB=new yse,kB.addSubnet("127.0.0.0",8,"ipv4"),kB.addAddress("::1","ipv6"),nc=new yse,nc.addSubnet("0.0.0.0",8,"ipv4"),nc.addSubnet("10.0.0.0",8,"ipv4"),nc.addSubnet("100.64.0.0",10,"ipv4"),nc.addSubnet("169.254.0.0",16,"ipv4"),nc.addSubnet("172.16.0.0",12,"ipv4"),nc.addSubnet("192.0.0.0",24,"ipv4"),nc.addSubnet("192.168.0.0",16,"ipv4"),nc.addSubnet("198.18.0.0",15,"ipv4"),nc.addSubnet("224.0.0.0",4,"ipv4"),nc.addSubnet("240.0.0.0",4,"ipv4"),nc.addAddress("::","ipv6"),nc.addSubnet("fc00::",7,"ipv6"),nc.addSubnet("fe80::",10,"ipv6")}}),sLn=E({"node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/mini/parse.js"(){dc()}}),aLn=E({"node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/mini/schemas.js"(){}}),cLn=E({"node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/mini/checks.js"(){}}),lLn=E({"node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/mini/iso.js"(){}}),uLn=E({"node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/mini/coerce.js"(){}}),dLn=E({"node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/mini/external.js"(){dc(),sLn(),aLn(),cLn(),XH(),lLn(),uLn()}}),pLn=E({"node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4-mini/index.js"(){dLn()}});function M0e(e){return!!e._zod}function Eg(e,t){return M0e(e)?yj(e,t):e.safeParse(t)}function ybr(e){if(!e)return;let t;if(M0e(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function vbr(e){if(M0e(e)){const i=e._zod?.def;if(i){if(i.value!==void 0)return i.value;if(Array.isArray(i.values)&&i.values.length>0)return i.values[0]}}const r=e._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}const n=e.value;if(n!==void 0)return n}var P0e=E({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js"(){pLn()}}),mLn=E({"node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/index.js"(){_J()}}),_br=E({"node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/index.js"(){mLn()}}),D4,wbr,Sg,N4,us,O0e,D0e,hLn,bbr,Tbr,AB,Bc,uS,Ebr,Xs,Pl,Ol,Ys,L4,N0e,CB,L0e,Sbr,xB,dS,rr,IB,kbr,n_,fLn,o_,Abr,RB,Cbr,pS,i_,$0e,xbr,Ibr,Rbr,Mbr,Pbr,Obr,Dbr,Nbr,F0e,U0e,Lbr,MB,$br,Fbr,PB,Ubr,mS,hS,Bbr,fS,gS,zbr,$4,OB,DB,NB,gLn,LB,$B,FB,qbr,B0e,z0e,UB,q0e,yS,s_,G0e,Gbr,jbr,j0e,Vbr,V0e,BB,Hbr,Wbr,H0e,W0e,Kbr,Jbr,Xbr,Ybr,Zbr,Qbr,eTr,tTr,rTr,K0e,nTr,oTr,zB,qB,GB,iTr,sTr,aTr,jB,cTr,J0e,X0e,lTr,uTr,Y0e,dTr,Z0e,F4,yLn,pTr,mTr,Q0e,hTr,eye,fTr,gTr,yTr,vTr,_Tr,wTr,bTr,TTr,ETr,U4,STr,kTr,tye,rye,nye,ATr,CTr,xTr,ITr,RTr,MTr,PTr,OTr,DTr,NTr,LTr,$Tr,FTr,UTr,BTr,oye,zTr,qTr,iye,GTr,jTr,VTr,HTr,sye,WTr,KTr,JTr,XTr,vLn,_Ln,wLn,bLn,TLn,ELn,Wt,YTr,kg=E({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js"(){_br(),D4="2025-11-25",wbr=[D4,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Sg="io.modelcontextprotocol/related-task",N4="2.0",us=sJ(e=>e!==null&&(typeof e=="object"||typeof e=="function")),O0e=Mn([ce(),Yr().int()]),D0e=ce(),hLn=Ts({ttl:Yr().optional(),pollInterval:Yr().optional()}),bbr=mt({ttl:Yr().optional()}),Tbr=mt({taskId:ce()}),AB=Ts({progressToken:O0e.optional(),[Sg]:Tbr.optional()}),Bc=mt({_meta:AB.optional()}),uS=Bc.extend({task:bbr.optional()}),Ebr=e=>uS.safeParse(e).success,Xs=mt({method:ce(),params:Bc.loose().optional()}),Pl=mt({_meta:AB.optional()}),Ol=mt({method:ce(),params:Pl.loose().optional()}),Ys=Ts({_meta:AB.optional()}),L4=Mn([ce(),Yr().int()]),N0e=mt({jsonrpc:Mt(N4),id:L4,...Xs.shape}).strict(),CB=e=>N0e.safeParse(e).success,L0e=mt({jsonrpc:Mt(N4),...Ol.shape}).strict(),Sbr=e=>L0e.safeParse(e).success,xB=mt({jsonrpc:Mt(N4),id:L4,result:Ys}).strict(),dS=e=>xB.safeParse(e).success,(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(rr||(rr={})),IB=mt({jsonrpc:Mt(N4),id:L4.optional(),error:mt({code:Yr().int(),message:ce(),data:Bn().optional()})}).strict(),kbr=e=>IB.safeParse(e).success,n_=Mn([N0e,L0e,xB,IB]),fLn=Mn([xB,IB]),o_=Ys.strict(),Abr=Pl.extend({requestId:L4.optional(),reason:ce().optional()}),RB=Ol.extend({method:Mt("notifications/cancelled"),params:Abr}),Cbr=mt({src:ce(),mimeType:ce().optional(),sizes:ct(ce()).optional(),theme:_a(["light","dark"]).optional()}),pS=mt({icons:ct(Cbr).optional()}),i_=mt({name:ce(),title:ce().optional()}),$0e=i_.extend({...i_.shape,...pS.shape,version:ce(),websiteUrl:ce().optional(),description:ce().optional()}),xbr=tC(mt({applyDefaults:Rn().optional()}),Pn(ce(),Bn())),Ibr=zD(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,tC(mt({form:xbr.optional(),url:us.optional()}),Pn(ce(),Bn()).optional())),Rbr=Ts({list:us.optional(),cancel:us.optional(),requests:Ts({sampling:Ts({createMessage:us.optional()}).optional(),elicitation:Ts({create:us.optional()}).optional()}).optional()}),Mbr=Ts({list:us.optional(),cancel:us.optional(),requests:Ts({tools:Ts({call:us.optional()}).optional()}).optional()}),Pbr=mt({experimental:Pn(ce(),us).optional(),sampling:mt({context:us.optional(),tools:us.optional()}).optional(),elicitation:Ibr.optional(),roots:mt({listChanged:Rn().optional()}).optional(),tasks:Rbr.optional(),extensions:Pn(ce(),us).optional()}),Obr=Bc.extend({protocolVersion:ce(),capabilities:Pbr,clientInfo:$0e}),Dbr=Xs.extend({method:Mt("initialize"),params:Obr}),Nbr=mt({experimental:Pn(ce(),us).optional(),logging:us.optional(),completions:us.optional(),prompts:mt({listChanged:Rn().optional()}).optional(),resources:mt({subscribe:Rn().optional(),listChanged:Rn().optional()}).optional(),tools:mt({listChanged:Rn().optional()}).optional(),tasks:Mbr.optional(),extensions:Pn(ce(),us).optional()}),F0e=Ys.extend({protocolVersion:ce(),capabilities:Nbr,serverInfo:$0e,instructions:ce().optional()}),U0e=Ol.extend({method:Mt("notifications/initialized"),params:Pl.optional()}),Lbr=e=>U0e.safeParse(e).success,MB=Xs.extend({method:Mt("ping"),params:Bc.optional()}),$br=mt({progress:Yr(),total:zn(Yr()),message:zn(ce())}),Fbr=mt({...Pl.shape,...$br.shape,progressToken:O0e}),PB=Ol.extend({method:Mt("notifications/progress"),params:Fbr}),Ubr=Bc.extend({cursor:D0e.optional()}),mS=Xs.extend({params:Ubr.optional()}),hS=Ys.extend({nextCursor:D0e.optional()}),Bbr=_a(["working","input_required","completed","failed","cancelled"]),fS=mt({taskId:ce(),status:Bbr,ttl:Mn([Yr(),ND()]),createdAt:ce(),lastUpdatedAt:ce(),pollInterval:zn(Yr()),statusMessage:zn(ce())}),gS=Ys.extend({task:fS}),zbr=Pl.merge(fS),$4=Ol.extend({method:Mt("notifications/tasks/status"),params:zbr}),OB=Xs.extend({method:Mt("tasks/get"),params:Bc.extend({taskId:ce()})}),DB=Ys.merge(fS),NB=Xs.extend({method:Mt("tasks/result"),params:Bc.extend({taskId:ce()})}),gLn=Ys.loose(),LB=mS.extend({method:Mt("tasks/list")}),$B=hS.extend({tasks:ct(fS)}),FB=Xs.extend({method:Mt("tasks/cancel"),params:Bc.extend({taskId:ce()})}),qbr=Ys.merge(fS),B0e=mt({uri:ce(),mimeType:zn(ce()),_meta:Pn(ce(),Bn()).optional()}),z0e=B0e.extend({text:ce()}),UB=ce().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),q0e=B0e.extend({blob:UB}),yS=_a(["user","assistant"]),s_=mt({audience:ct(yS).optional(),priority:Yr().min(0).max(1).optional(),lastModified:bN.datetime({offset:!0}).optional()}),G0e=mt({...i_.shape,...pS.shape,uri:ce(),description:zn(ce()),mimeType:zn(ce()),size:zn(Yr()),annotations:s_.optional(),_meta:zn(Ts({}))}),Gbr=mt({...i_.shape,...pS.shape,uriTemplate:ce(),description:zn(ce()),mimeType:zn(ce()),annotations:s_.optional(),_meta:zn(Ts({}))}),jbr=mS.extend({method:Mt("resources/list")}),j0e=hS.extend({resources:ct(G0e)}),Vbr=mS.extend({method:Mt("resources/templates/list")}),V0e=hS.extend({resourceTemplates:ct(Gbr)}),BB=Bc.extend({uri:ce()}),Hbr=BB,Wbr=Xs.extend({method:Mt("resources/read"),params:Hbr}),H0e=Ys.extend({contents:ct(Mn([z0e,q0e]))}),W0e=Ol.extend({method:Mt("notifications/resources/list_changed"),params:Pl.optional()}),Kbr=BB,Jbr=Xs.extend({method:Mt("resources/subscribe"),params:Kbr}),Xbr=BB,Ybr=Xs.extend({method:Mt("resources/unsubscribe"),params:Xbr}),Zbr=Pl.extend({uri:ce()}),Qbr=Ol.extend({method:Mt("notifications/resources/updated"),params:Zbr}),eTr=mt({name:ce(),description:zn(ce()),required:zn(Rn())}),tTr=mt({...i_.shape,...pS.shape,description:zn(ce()),arguments:zn(ct(eTr)),_meta:zn(Ts({}))}),rTr=mS.extend({method:Mt("prompts/list")}),K0e=hS.extend({prompts:ct(tTr)}),nTr=Bc.extend({name:ce(),arguments:Pn(ce(),ce()).optional()}),oTr=Xs.extend({method:Mt("prompts/get"),params:nTr}),zB=mt({type:Mt("text"),text:ce(),annotations:s_.optional(),_meta:Pn(ce(),Bn()).optional()}),qB=mt({type:Mt("image"),data:UB,mimeType:ce(),annotations:s_.optional(),_meta:Pn(ce(),Bn()).optional()}),GB=mt({type:Mt("audio"),data:UB,mimeType:ce(),annotations:s_.optional(),_meta:Pn(ce(),Bn()).optional()}),iTr=mt({type:Mt("tool_use"),name:ce(),id:ce(),input:Pn(ce(),Bn()),_meta:Pn(ce(),Bn()).optional()}),sTr=mt({type:Mt("resource"),resource:Mn([z0e,q0e]),annotations:s_.optional(),_meta:Pn(ce(),Bn()).optional()}),aTr=G0e.extend({type:Mt("resource_link")}),jB=Mn([zB,qB,GB,aTr,sTr]),cTr=mt({role:yS,content:jB}),J0e=Ys.extend({description:ce().optional(),messages:ct(cTr)}),X0e=Ol.extend({method:Mt("notifications/prompts/list_changed"),params:Pl.optional()}),lTr=mt({title:ce().optional(),readOnlyHint:Rn().optional(),destructiveHint:Rn().optional(),idempotentHint:Rn().optional(),openWorldHint:Rn().optional()}),uTr=mt({taskSupport:_a(["required","optional","forbidden"]).optional()}),Y0e=mt({...i_.shape,...pS.shape,description:ce().optional(),inputSchema:mt({type:Mt("object"),properties:Pn(ce(),us).optional(),required:ct(ce()).optional()}).catchall(Bn()),outputSchema:mt({type:Mt("object"),properties:Pn(ce(),us).optional(),required:ct(ce()).optional()}).catchall(Bn()).optional(),annotations:lTr.optional(),execution:uTr.optional(),_meta:Pn(ce(),Bn()).optional()}),dTr=mS.extend({method:Mt("tools/list")}),Z0e=hS.extend({tools:ct(Y0e)}),F4=Ys.extend({content:ct(jB).default([]),structuredContent:Pn(ce(),Bn()).optional(),isError:Rn().optional()}),yLn=F4.or(Ys.extend({toolResult:Bn()})),pTr=uS.extend({name:ce(),arguments:Pn(ce(),Bn()).optional()}),mTr=Xs.extend({method:Mt("tools/call"),params:pTr}),Q0e=Ol.extend({method:Mt("notifications/tools/list_changed"),params:Pl.optional()}),hTr=mt({autoRefresh:Rn().default(!0),debounceMs:Yr().int().nonnegative().default(300)}),eye=_a(["debug","info","notice","warning","error","critical","alert","emergency"]),fTr=Bc.extend({level:eye}),gTr=Xs.extend({method:Mt("logging/setLevel"),params:fTr}),yTr=Pl.extend({level:eye,logger:ce().optional(),data:Bn()}),vTr=Ol.extend({method:Mt("notifications/message"),params:yTr}),_Tr=mt({name:ce().optional()}),wTr=mt({hints:ct(_Tr).optional(),costPriority:Yr().min(0).max(1).optional(),speedPriority:Yr().min(0).max(1).optional(),intelligencePriority:Yr().min(0).max(1).optional()}),bTr=mt({mode:_a(["auto","required","none"]).optional()}),TTr=mt({type:Mt("tool_result"),toolUseId:ce().describe("The unique identifier for the corresponding tool call."),content:ct(jB).default([]),structuredContent:mt({}).loose().optional(),isError:Rn().optional(),_meta:Pn(ce(),Bn()).optional()}),ETr=$D("type",[zB,qB,GB]),U4=$D("type",[zB,qB,GB,iTr,TTr]),STr=mt({role:yS,content:Mn([U4,ct(U4)]),_meta:Pn(ce(),Bn()).optional()}),kTr=uS.extend({messages:ct(STr),modelPreferences:wTr.optional(),systemPrompt:ce().optional(),includeContext:_a(["none","thisServer","allServers"]).optional(),temperature:Yr().optional(),maxTokens:Yr().int(),stopSequences:ct(ce()).optional(),metadata:us.optional(),tools:ct(Y0e).optional(),toolChoice:bTr.optional()}),tye=Xs.extend({method:Mt("sampling/createMessage"),params:kTr}),rye=Ys.extend({model:ce(),stopReason:zn(_a(["endTurn","stopSequence","maxTokens"]).or(ce())),role:yS,content:ETr}),nye=Ys.extend({model:ce(),stopReason:zn(_a(["endTurn","stopSequence","maxTokens","toolUse"]).or(ce())),role:yS,content:Mn([U4,ct(U4)])}),ATr=mt({type:Mt("boolean"),title:ce().optional(),description:ce().optional(),default:Rn().optional()}),CTr=mt({type:Mt("string"),title:ce().optional(),description:ce().optional(),minLength:Yr().optional(),maxLength:Yr().optional(),format:_a(["email","uri","date","date-time"]).optional(),default:ce().optional()}),xTr=mt({type:_a(["number","integer"]),title:ce().optional(),description:ce().optional(),minimum:Yr().optional(),maximum:Yr().optional(),default:Yr().optional()}),ITr=mt({type:Mt("string"),title:ce().optional(),description:ce().optional(),enum:ct(ce()),default:ce().optional()}),RTr=mt({type:Mt("string"),title:ce().optional(),description:ce().optional(),oneOf:ct(mt({const:ce(),title:ce()})),default:ce().optional()}),MTr=mt({type:Mt("string"),title:ce().optional(),description:ce().optional(),enum:ct(ce()),enumNames:ct(ce()).optional(),default:ce().optional()}),PTr=Mn([ITr,RTr]),OTr=mt({type:Mt("array"),title:ce().optional(),description:ce().optional(),minItems:Yr().optional(),maxItems:Yr().optional(),items:mt({type:Mt("string"),enum:ct(ce())}),default:ct(ce()).optional()}),DTr=mt({type:Mt("array"),title:ce().optional(),description:ce().optional(),minItems:Yr().optional(),maxItems:Yr().optional(),items:mt({anyOf:ct(mt({const:ce(),title:ce()}))}),default:ct(ce()).optional()}),NTr=Mn([OTr,DTr]),LTr=Mn([MTr,PTr,NTr]),$Tr=Mn([LTr,ATr,CTr,xTr]),FTr=uS.extend({mode:Mt("form").optional(),message:ce(),requestedSchema:mt({type:Mt("object"),properties:Pn(ce(),$Tr),required:ct(ce()).optional()})}),UTr=uS.extend({mode:Mt("url"),message:ce(),elicitationId:ce(),url:ce().url()}),BTr=Mn([FTr,UTr]),oye=Xs.extend({method:Mt("elicitation/create"),params:BTr}),zTr=Pl.extend({elicitationId:ce()}),qTr=Ol.extend({method:Mt("notifications/elicitation/complete"),params:zTr}),iye=Ys.extend({action:_a(["accept","decline","cancel"]),content:zD(e=>e===null?void 0:e,Pn(ce(),Mn([ce(),Yr(),Rn(),ct(ce())])).optional())}),GTr=mt({type:Mt("ref/resource"),uri:ce()}),jTr=mt({type:Mt("ref/prompt"),name:ce()}),VTr=Bc.extend({ref:Mn([jTr,GTr]),argument:mt({name:ce(),value:ce()}),context:mt({arguments:Pn(ce(),ce()).optional()}).optional()}),HTr=Xs.extend({method:Mt("completion/complete"),params:VTr}),sye=Ys.extend({completion:Ts({values:ct(ce()).max(100),total:zn(Yr().int()),hasMore:zn(Rn())})}),WTr=mt({uri:ce().startsWith("file://"),name:ce().optional(),_meta:Pn(ce(),Bn()).optional()}),KTr=Xs.extend({method:Mt("roots/list"),params:Bc.optional()}),JTr=Ys.extend({roots:ct(WTr)}),XTr=Ol.extend({method:Mt("notifications/roots/list_changed"),params:Pl.optional()}),vLn=Mn([MB,Dbr,HTr,gTr,oTr,rTr,jbr,Vbr,Wbr,Jbr,Ybr,mTr,dTr,OB,NB,LB,FB]),_Ln=Mn([RB,PB,U0e,XTr,$4]),wLn=Mn([o_,rye,nye,iye,JTr,DB,$B,gS]),bLn=Mn([MB,tye,oye,KTr,OB,NB,LB,FB]),TLn=Mn([RB,PB,vTr,Qbr,W0e,Q0e,X0e,$4,qTr]),ELn=Mn([o_,F0e,sye,J0e,K0e,j0e,V0e,H0e,F4,Z0e,DB,$B,gS]),Wt=class EQr extends Error{constructor(t,r,n){super(`MCP error ${t}: ${r}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,r,n){if(t===rr.UrlElicitationRequired&&n){const o=n;if(o.elicitations)return new YTr(o.elicitations,r)}return new EQr(t,r,n)}},YTr=class extends Wt{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(rr.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}}});function a_(e){return e==="completed"||e==="failed"||e==="cancelled"}var SLn=E({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js"(){}});function ZTr(e){const r=ybr(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=vbr(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function QTr(e,t){const r=Eg(e,t);if(!r.success)throw r.error;return r.data}var kLn=E({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js"(){P0e(),cX()}});function eEr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ALn(e,t){const r={...e};for(const n in t){const o=n,i=t[o];if(i===void 0)continue;const s=r[o];eEr(s)&&eEr(i)?r[o]={...s,...i}:r[o]=i}return r}var tEr,rEr,CLn=E({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js"(){P0e(),kg(),SLn(),kLn(),tEr=6e4,rEr=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(RB,t=>{this._oncancel(t)}),this.setNotificationHandler(PB,t=>{this._onprogress(t)}),this.setRequestHandler(MB,t=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(OB,async(t,r)=>{const n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new Wt(rr.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(NB,async(t,r)=>{const n=async()=>{const o=t.params.taskId;if(!await this._taskStore.getTask(o,r.sessionId))throw new Wt(rr.InvalidParams,`Task not found: ${o}`);if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(o,r.sessionId);){if(s.type==="response"||s.type==="error"){const a=s.message,c=a.id,l=this._requestResolvers.get(c);if(l)if(this._requestResolvers.delete(c),s.type==="response")l(a);else{const u=a,d=new Wt(u.error.code,u.error.message,u.error.data);l(d)}else{const u=s.type==="response"?"Response":"Error";this._onerror(new Error(`${u} handler missing for request ${c}`))}continue}await this._transport?.send(s.message,{relatedRequestId:r.requestId})}}const i=await this._taskStore.getTask(o,r.sessionId);if(!i)throw new Wt(rr.InvalidParams,`Task not found: ${o}`);if(!a_(i.status))return await this._waitForTaskUpdate(o,r.signal,r.sessionId),await n();if(a_(i.status)){const s=await this._taskStore.getTaskResult(o,r.sessionId);return this._clearTaskQueue(o,r.sessionId),{...s,_meta:{...s._meta,[Sg]:{taskId:o}}}}return await n()};return await n()}),this.setRequestHandler(LB,async(t,r)=>{try{const{tasks:n,nextCursor:o}=await this._taskStore.listTasks(t.params?.cursor,r.sessionId);return{tasks:n,nextCursor:o,_meta:{}}}catch(n){throw new Wt(rr.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(FB,async(t,r)=>{try{const n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new Wt(rr.InvalidParams,`Task not found: ${t.params.taskId}`);if(a_(n.status))throw new Wt(rr.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(t.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(t.params.taskId,r.sessionId);const o=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!o)throw new Wt(rr.InvalidParams,`Task not found after cancellation: ${t.params.taskId}`);return{_meta:{},...o}}catch(n){throw n instanceof Wt?n:new Wt(rr.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,t,r,n,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:o,onTimeout:n})}_resetTimeout(e){const t=this._timeoutInfo.get(e);if(!t)return!1;const r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),Wt.fromError(rr.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){const t=this._timeoutInfo.get(e);t&&(clearTimeout(t.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;const t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};const r=this.transport?.onerror;this._transport.onerror=o=>{r?.(o),this._onerror(o)};const n=this._transport?.onmessage;this._transport.onmessage=(o,i)=>{n?.(o,i),dS(o)||kbr(o)?this._onresponse(o):CB(o)?this._onrequest(o,i):Sbr(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){const e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();for(const r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();const t=Wt.fromError(rr.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const r of e.values())r(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){const t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(r=>this._onerror(new Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,t){const r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,n=this._transport,o=e.params?._meta?.[Sg]?.taskId,i=n?.sessionId,s=this._taskStore;let a=!0,c;if(o&&s&&this._taskMessageQueue&&i!==void 0&&(a=!1,c=(async()=>{if(!await s.getTask(o,i))throw new Wt(rr.InvalidParams,`Task not found: ${o}`);a=!0})()),r===void 0){const m={jsonrpc:"2.0",id:e.id,error:{code:rr.MethodNotFound,message:"Method not found"}};if(o&&c){const h={type:"error",message:m,timestamp:Date.now()};c.then(()=>this._enqueueTaskMessage(o,h,i),()=>n?.send(m)).catch(f=>this._onerror(new Error(`Failed to send an error response: ${f}`)))}else o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:m,timestamp:Date.now()},n?.sessionId).catch(h=>this._onerror(new Error(`Failed to enqueue error response: ${h}`))):n?.send(m).catch(h=>this._onerror(new Error(`Failed to send an error response: ${h}`)));return}const l=new AbortController;this._requestHandlerAbortControllers.set(e.id,l);const u=Ebr(e.params)?e.params.task:void 0,d=this._taskStore?this.requestTaskStore(e,n?.sessionId):void 0,p={signal:l.signal,sessionId:n?.sessionId,_meta:e.params?._meta,sendNotification:async m=>{if(l.signal.aborted)return;const h={relatedRequestId:e.id};o&&(h.relatedTask={taskId:o}),await this.notification(m,h)},sendRequest:async(m,h,f)=>{if(l.signal.aborted)throw new Wt(rr.ConnectionClosed,"Request was cancelled");const y={...f,relatedRequestId:e.id};o&&!y.relatedTask&&(y.relatedTask={taskId:o});const v=y.relatedTask?.taskId??o;return v&&d&&await d.updateTaskStatus(v,"input_required"),await this.request(m,h,y)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:o,taskStore:d,taskRequestedTtl:u?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};(c??Promise.resolve()).then(()=>{if(c&&l.signal.aborted)throw new Wt(rr.ConnectionClosed,"Request was cancelled");u&&this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,p)).then(async m=>{if(l.signal.aborted)return;const h={result:m,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:h,timestamp:Date.now()},n?.sessionId):await n?.send(h)},async m=>{if(l.signal.aborted)return;const h={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(m.code)?m.code:rr.InternalError,message:m.message??"Internal error",...m.data!==void 0&&{data:m.data}}};o&&this._taskMessageQueue&&a?await this._enqueueTaskMessage(o,{type:"error",message:h,timestamp:Date.now()},n?.sessionId):await n?.send(h)}).catch(m=>this._onerror(new Error(`Failed to send response: ${m}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===l&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:t,...r}=e.params,n=Number(t),o=this._progressHandlers.get(n);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}const i=this._responseHandlers.get(n),s=this._timeoutInfo.get(n);if(s&&i&&s.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(a){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),i(a);return}o(r)}_onresponse(e){const t=Number(e.id),r=this._requestResolvers.get(t);if(r){if(this._requestResolvers.delete(t),dS(e))r(e);else{const i=new Wt(e.error.code,e.error.message,e.error.data);r(i)}return}const n=this._responseHandlers.get(t);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let o=!1;if(dS(e)&&e.result&&typeof e.result=="object"){const i=e.result;if(i.task&&typeof i.task=="object"){const s=i.task;typeof s.taskId=="string"&&(o=!0,this._taskProgressTokens.set(s.taskId,t))}}if(o||this._progressHandlers.delete(t),dS(e))n(e);else{const i=Wt.fromError(e.error.code,e.error.message,e.error.data);n(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,r){const{task:n}=r??{};if(!n){try{yield{type:"result",result:await this.request(e,t,r)}}catch(i){yield{type:"error",error:i instanceof Wt?i:new Wt(rr.InternalError,String(i))}}return}let o;try{const i=await this.request(e,gS,r);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new Wt(rr.InternalError,"Task creation did not return a task");for(;;){const s=await this.getTask({taskId:o},r);if(yield{type:"taskStatus",task:s},a_(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},t,r)}:s.status==="failed"?yield{type:"error",error:new Wt(rr.InternalError,`Task ${o} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new Wt(rr.InternalError,`Task ${o} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},t,r)};return}const a=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(c=>setTimeout(c,a)),r?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof Wt?i:new Wt(rr.InternalError,String(i))}}}request(e,t,r){const{relatedRequestId:n,resumptionToken:o,onresumptiontoken:i,task:s,relatedTask:a}=r??{};return new Promise((c,l)=>{const u=v=>{l(v)};if(!this._transport){u(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),s&&this.assertTaskCapability(e.method)}catch(v){u(v);return}r?.signal?.throwIfAborted();const d=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:d};r?.onprogress&&(this._progressHandlers.set(d,r.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),s&&(p.params={...p.params,task:s}),a&&(p.params={...p.params,_meta:{...p.params?._meta||{},[Sg]:a}});const m=v=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:d,reason:String(v)}},{relatedRequestId:n,resumptionToken:o,onresumptiontoken:i}).catch(w=>this._onerror(new Error(`Failed to send cancellation: ${w}`)));const _=v instanceof Wt?v:new Wt(rr.RequestTimeout,String(v));l(_)};this._responseHandlers.set(d,v=>{if(!r?.signal?.aborted){if(v instanceof Error)return l(v);try{const _=Eg(t,v.result);_.success?c(_.data):l(_.error)}catch(_){l(_)}}}),r?.signal?.addEventListener("abort",()=>{m(r?.signal?.reason)});const h=r?.timeout??tEr,f=()=>m(Wt.fromError(rr.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(d,h,r?.maxTotalTimeout,f,r?.resetTimeoutOnProgress??!1);const y=a?.taskId;if(y){const v=_=>{const w=this._responseHandlers.get(d);w?w(_):this._onerror(new Error(`Response handler missing for side-channeled request ${d}`))};this._requestResolvers.set(d,v),this._enqueueTaskMessage(y,{type:"request",message:p,timestamp:Date.now()}).catch(_=>{this._cleanupTimeout(d),l(_)})}else this._transport.send(p,{relatedRequestId:n,resumptionToken:o,onresumptiontoken:i}).catch(v=>{this._cleanupTimeout(d),l(v)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},DB,t)}async getTaskResult(e,t,r){return this.request({method:"tasks/result",params:e},t,r)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},$B,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},qbr,t)}async notification(e,t){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);const r=t?.relatedTask?.taskId;if(r){const s={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Sg]:t.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:s,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let s={...e,jsonrpc:"2.0"};t?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Sg]:t.relatedTask}}}),this._transport?.send(s,t).catch(a=>this._onerror(a))});return}let i={...e,jsonrpc:"2.0"};t?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Sg]:t.relatedTask}}}),await this._transport.send(i,t)}setRequestHandler(e,t){const r=ZTr(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(n,o)=>{const i=QTr(e,n);return Promise.resolve(t(i,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,t){const r=ZTr(e);this._notificationHandlers.set(r,n=>{const o=QTr(e,n);return Promise.resolve(t(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){const t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,r){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,r??this._transport?.sessionId,n)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){const r=await this._taskMessageQueue.dequeueAll(e,t);for(const n of r)if(n.type==="request"&&CB(n.message)){const o=n.message.id,i=this._requestResolvers.get(o);i?(i(new Wt(rr.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,t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{const o=await this._taskStore?.getTask(e,r);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,i)=>{if(t.aborted){i(new Wt(rr.InvalidRequest,"Request cancelled"));return}const s=setTimeout(o,n);t.addEventListener("abort",()=>{clearTimeout(s),i(new Wt(rr.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){const r=this._taskStore;if(!r)throw new Error("No task store configured");return{createTask:async n=>{if(!e)throw new Error("No request provided");return await r.createTask(n,e.id,{method:e.method,params:e.params},t)},getTask:async n=>{const o=await r.getTask(n,t);if(!o)throw new Wt(rr.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(n,o,i)=>{await r.storeTaskResult(n,o,i,t);const s=await r.getTask(n,t);if(s){const a=$4.parse({method:"notifications/tasks/status",params:s});await this.notification(a),a_(s.status)&&this._cleanupTaskProgressHandler(n)}},getTaskResult:n=>r.getTaskResult(n,t),updateTaskStatus:async(n,o,i)=>{const s=await r.getTask(n,t);if(!s)throw new Wt(rr.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(a_(s.status))throw new Wt(rr.InvalidParams,`Cannot update task "${n}" from terminal status "${s.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(n,o,i,t);const a=await r.getTask(n,t);if(a){const c=$4.parse({method:"notifications/tasks/status",params:a});await this.notification(c),a_(a.status)&&this._cleanupTaskProgressHandler(n)}},listTasks:n=>r.listTasks(n,t)}}}}}),c_,Ds,nEr,xLn,ILn,RLn,MLn,PLn,OLn,DLn,NLn,LLn,$Ln,FLn,ULn,BLn,zLn,qLn,GLn,jLn,VLn,HLn,WLn,KLn,JLn,XLn,YLn,ZLn,QLn,e6n,t6n,r6n,n6n,o6n,i6n,s6n,a6n,c6n,l6n,u6n,d6n,p6n,m6n,h6n,f6n,g6n,y6n,v6n,_6n,w6n=E({"npm-stub:ajv"(){c_={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:c_.get}):new Proxy(function(...r){return new Proxy({},{get:c_.get})},{get:c_.get,apply(r,n,o){return new Proxy({},{get:c_.get})},construct(r,n){return new Proxy({},{get:c_.get})}})}},Ds=new Proxy({},c_),nEr=Ds,{BedrockClient:xLn,ListFoundationModelsCommand:ILn,BedrockRuntimeClient:RLn,ConverseCommand:MLn,ConverseStreamCommand:PLn,ImageFormat:OLn,InvokeModelCommand:DLn}=Ds,{SageMakerRuntimeClient:NLn,InvokeEndpointCommand:LLn,InvokeEndpointWithResponseStreamCommand:$Ln}=Ds,{GoogleAuth:FLn,VertexAI:ULn,TextToSpeechClient:BLn}=Ds,{Webhook:zLn}=Ds,{Hippocampus:qLn,HippocampusConfig:GLn}=Ds,{createClient:jLn}=Ds,{Queue:VLn,Worker:HLn,Job:WLn,QueueScheduler:KLn,FlowProducer:JLn}=Ds,{Cron:XLn}=Ds,{parseBuffer:YLn,selectCover:ZLn}=Ds,{extractRawText:QLn,convertToHtml:e6n}=Ds,{Hono:t6n}=Ds,{cors:r6n,HTTPException:n6n,logger:o6n,secureHeaders:i6n,streamSSE:s6n,timeout:a6n}=Ds,c6n=globalThis.fetch,l6n=globalThis.Request,u6n=globalThis.Response,d6n=globalThis.Headers,p6n=globalThis.FormData,m6n=globalThis.File,h6n=globalThis.Blob,f6n=Ds.Agent,g6n=Ds.Pool,y6n=Ds.Client,v6n=Ds.Dispatcher,_6n=Ds.MockAgent}}),l_,Ns,oEr,b6n,T6n,E6n,S6n,k6n,A6n,C6n,x6n,I6n,R6n,M6n,P6n,O6n,D6n,N6n,L6n,$6n,F6n,U6n,B6n,z6n,q6n,G6n,j6n,V6n,H6n,W6n,K6n,J6n,X6n,Y6n,Z6n,Q6n,e$n,t$n,r$n,n$n,o$n,i$n,s$n,a$n,c$n,l$n,u$n,d$n,p$n,m$n=E({"npm-stub:ajv-formats"(){l_={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:l_.get}):new Proxy(function(...r){return new Proxy({},{get:l_.get})},{get:l_.get,apply(r,n,o){return new Proxy({},{get:l_.get})},construct(r,n){return new Proxy({},{get:l_.get})}})}},Ns=new Proxy({},l_),oEr=Ns,{BedrockClient:b6n,ListFoundationModelsCommand:T6n,BedrockRuntimeClient:E6n,ConverseCommand:S6n,ConverseStreamCommand:k6n,ImageFormat:A6n,InvokeModelCommand:C6n}=Ns,{SageMakerRuntimeClient:x6n,InvokeEndpointCommand:I6n,InvokeEndpointWithResponseStreamCommand:R6n}=Ns,{GoogleAuth:M6n,VertexAI:P6n,TextToSpeechClient:O6n}=Ns,{Webhook:D6n}=Ns,{Hippocampus:N6n,HippocampusConfig:L6n}=Ns,{createClient:$6n}=Ns,{Queue:F6n,Worker:U6n,Job:B6n,QueueScheduler:z6n,FlowProducer:q6n}=Ns,{Cron:G6n}=Ns,{parseBuffer:j6n,selectCover:V6n}=Ns,{extractRawText:H6n,convertToHtml:W6n}=Ns,{Hono:K6n}=Ns,{cors:J6n,HTTPException:X6n,logger:Y6n,secureHeaders:Z6n,streamSSE:Q6n,timeout:e$n}=Ns,t$n=globalThis.fetch,r$n=globalThis.Request,n$n=globalThis.Response,o$n=globalThis.Headers,i$n=globalThis.FormData,s$n=globalThis.File,a$n=globalThis.Blob,c$n=Ns.Agent,l$n=Ns.Pool,u$n=Ns.Client,d$n=Ns.Dispatcher,p$n=Ns.MockAgent}});function h$n(){const e=new nEr({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return oEr(e),e}var iEr,f$n=E({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js"(){w6n(),m$n(),iEr=class{constructor(e){this._ajv=e??h$n()}getValidator(e){const t="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return r=>t(r)?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}}}}),sEr,g$n=E({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js"(){kg(),sEr=class{constructor(e){this._client=e}async*callToolStream(e,t=F4,r){const n=this._client,o={...r,task:r?.task??(n.isToolTask(e.name)?{}:void 0)},i=n.requestStream({method:"tools/call",params:e},t,o),s=n.getToolOutputValidator(e.name);for await(const a of i){if(a.type==="result"&&s){const c=a.result;if(!c.structuredContent&&!c.isError){yield{type:"error",error:new Wt(rr.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(c.structuredContent)try{const l=s(c.structuredContent);if(!l.valid){yield{type:"error",error:new Wt(rr.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)};return}}catch(l){if(l instanceof Wt){yield{type:"error",error:l};return}yield{type:"error",error:new Wt(rr.InvalidParams,`Failed to validate structured content: ${l instanceof Error?l.message:String(l)}`)};return}}yield a}}async getTask(e,t){return this._client.getTask({taskId:e},t)}async getTaskResult(e,t,r){return this._client.getTaskResult({taskId:e},t,r)}async listTasks(e,t){return this._client.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._client.cancelTask({taskId:e},t)}requestStream(e,t,r){return this._client.requestStream(e,t,r)}}}});function y$n(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function v$n(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var _$n=E({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js"(){}}),aEr={};ae(aEr,{Client:()=>lEr,getSupportedElicitationModes:()=>cEr});function VB(e,t){if(!(!e||t===null||typeof t!="object")){if(e.type==="object"&&e.properties&&typeof e.properties=="object"){const r=t,n=e.properties;for(const o of Object.keys(n)){const i=n[o];r[o]===void 0&&Object.prototype.hasOwnProperty.call(i,"default")&&(r[o]=i.default),r[o]!==void 0&&VB(i,r[o])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)typeof r!="boolean"&&VB(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)typeof r!="boolean"&&VB(r,t)}}function cEr(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};const t=e.form!==void 0,r=e.url!==void 0;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}var lEr,w$n=E({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js"(){CLn(),kg(),f$n(),P0e(),g$n(),_$n(),lEr=class extends rEr{constructor(e,t){super(t),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=t?.capabilities??{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new iEr,t?.listChanged&&(this._pendingListChangedConfig=t.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Q0e,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",X0e,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",W0e,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new sEr(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=ALn(this._capabilities,e)}setRequestHandler(e,t){const n=ybr(e)?.method;if(!n)throw new Error("Schema is missing a method literal");const o=vbr(n);if(typeof o!="string")throw new Error("Schema method literal must be a string");const i=o;if(i==="elicitation/create"){const s=async(a,c)=>{const l=Eg(oye,a);if(!l.success){const v=l.error instanceof Error?l.error.message:String(l.error);throw new Wt(rr.InvalidParams,`Invalid elicitation request: ${v}`)}const{params:u}=l.data;u.mode=u.mode??"form";const{supportsFormMode:d,supportsUrlMode:p}=cEr(this._capabilities.elicitation);if(u.mode==="form"&&!d)throw new Wt(rr.InvalidParams,"Client does not support form-mode elicitation requests");if(u.mode==="url"&&!p)throw new Wt(rr.InvalidParams,"Client does not support URL-mode elicitation requests");const m=await Promise.resolve(t(a,c));if(u.task){const v=Eg(gS,m);if(!v.success){const _=v.error instanceof Error?v.error.message:String(v.error);throw new Wt(rr.InvalidParams,`Invalid task creation result: ${_}`)}return v.data}const h=Eg(iye,m);if(!h.success){const v=h.error instanceof Error?h.error.message:String(h.error);throw new Wt(rr.InvalidParams,`Invalid elicitation result: ${v}`)}const f=h.data,y=u.mode==="form"?u.requestedSchema:void 0;if(u.mode==="form"&&f.action==="accept"&&f.content&&y&&this._capabilities.elicitation?.form?.applyDefaults)try{VB(y,f.content)}catch{}return f};return super.setRequestHandler(e,s)}if(i==="sampling/createMessage"){const s=async(a,c)=>{const l=Eg(tye,a);if(!l.success){const f=l.error instanceof Error?l.error.message:String(l.error);throw new Wt(rr.InvalidParams,`Invalid sampling request: ${f}`)}const{params:u}=l.data,d=await Promise.resolve(t(a,c));if(u.task){const f=Eg(gS,d);if(!f.success){const y=f.error instanceof Error?f.error.message:String(f.error);throw new Wt(rr.InvalidParams,`Invalid task creation result: ${y}`)}return f.data}const m=u.tools||u.toolChoice?nye:rye,h=Eg(m,d);if(!h.success){const f=h.error instanceof Error?h.error.message:String(h.error);throw new Wt(rr.InvalidParams,`Invalid sampling result: ${f}`)}return h.data};return super.setRequestHandler(e,s)}return super.setRequestHandler(e,t)}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await super.connect(e),e.sessionId===void 0)try{const r=await this.request({method:"initialize",params:{protocolVersion:D4,capabilities:this._capabilities,clientInfo:this._clientInfo}},F0e,t);if(r===void 0)throw new Error(`Server sent invalid initialize result: ${r}`);if(!wbr.includes(r.protocolVersion))throw new Error(`Server's protocol version is not supported: ${r.protocolVersion}`);this._serverCapabilities=r.capabilities,this._serverVersion=r.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(r.protocolVersion),this._instructions=r.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(r){throw this.close(),r}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${e})`);break;case"ping":break}}assertTaskCapability(e){y$n(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&v$n(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},o_,e)}async complete(e,t){return this.request({method:"completion/complete",params:e},sye,t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},o_,t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},J0e,t)}async listPrompts(e,t){return this.request({method:"prompts/list",params:e},K0e,t)}async listResources(e,t){return this.request({method:"resources/list",params:e},j0e,t)}async listResourceTemplates(e,t){return this.request({method:"resources/templates/list",params:e},V0e,t)}async readResource(e,t){return this.request({method:"resources/read",params:e},H0e,t)}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},o_,t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},o_,t)}async callTool(e,t=F4,r){if(this.isToolTaskRequired(e.name))throw new Wt(rr.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);const n=await this.request({method:"tools/call",params:e},t,r),o=this.getToolOutputValidator(e.name);if(o){if(!n.structuredContent&&!n.isError)throw new Wt(rr.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(n.structuredContent)try{const i=o(n.structuredContent);if(!i.valid)throw new Wt(rr.InvalidParams,`Structured content does not match the tool's output schema: ${i.errorMessage}`)}catch(i){throw i instanceof Wt?i:new Wt(rr.InvalidParams,`Failed to validate structured content: ${i instanceof Error?i.message:String(i)}`)}}return n}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const t of e){if(t.outputSchema){const n=this._jsonSchemaValidator.getValidator(t.outputSchema);this._cachedToolOutputValidators.set(t.name,n)}const r=t.execution?.taskSupport;(r==="required"||r==="optional")&&this._cachedKnownTaskTools.add(t.name),r==="required"&&this._cachedRequiredTaskTools.add(t.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){const r=await this.request({method:"tools/list",params:e},Z0e,t);return this.cacheToolMetadata(r.tools),r}_setupListChangedHandler(e,t,r,n){const o=hTr.safeParse(r);if(!o.success)throw new Error(`Invalid ${e} listChanged options: ${o.error.message}`);if(typeof r.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);const{autoRefresh:i,debounceMs:s}=o.data,{onChanged:a}=r,c=async()=>{if(!i){a(null,null);return}try{const u=await n();a(null,u)}catch(u){const d=u instanceof Error?u:new Error(String(u));a(d,null)}},l=()=>{if(s){const u=this._listChangedDebounceTimers.get(e);u&&clearTimeout(u);const d=setTimeout(c,s);this._listChangedDebounceTimers.set(e,d)}else c()};this.setNotificationHandler(t,l)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}}}),uEr={};ae(uEr,{Agent:()=>QEr,BedrockClient:()=>pEr,BedrockRuntimeClient:()=>hEr,Blob:()=>ZEr,Client:()=>tSr,ConverseCommand:()=>fEr,ConverseStreamCommand:()=>gEr,Cron:()=>DEr,Dispatcher:()=>rSr,File:()=>YEr,FlowProducer:()=>OEr,FormData:()=>XEr,GoogleAuth:()=>TEr,HTTPException:()=>zEr,Headers:()=>JEr,Hippocampus:()=>AEr,HippocampusConfig:()=>CEr,Hono:()=>UEr,ImageFormat:()=>yEr,InvokeEndpointCommand:()=>wEr,InvokeEndpointWithResponseStreamCommand:()=>bEr,InvokeModelCommand:()=>vEr,Job:()=>MEr,ListFoundationModelsCommand:()=>mEr,MockAgent:()=>iSr,Pool:()=>eSr,Queue:()=>IEr,QueueScheduler:()=>PEr,Request:()=>WEr,Response:()=>KEr,SageMakerRuntimeClient:()=>_Er,TextToSpeechClient:()=>SEr,VertexAI:()=>EEr,Webhook:()=>kEr,Worker:()=>REr,convertToHtml:()=>FEr,cors:()=>BEr,createClient:()=>xEr,default:()=>dEr,extractRawText:()=>$Er,fetch:()=>HEr,getGlobalDispatcher:()=>oSr,interceptors:()=>sSr,logger:()=>qEr,parseBuffer:()=>NEr,request:()=>aSr,secureHeaders:()=>GEr,selectCover:()=>LEr,setGlobalDispatcher:()=>nSr,streamSSE:()=>jEr,timeout:()=>VEr});var u_,ds,dEr,pEr,mEr,hEr,fEr,gEr,yEr,vEr,_Er,wEr,bEr,TEr,EEr,SEr,kEr,AEr,CEr,xEr,IEr,REr,MEr,PEr,OEr,DEr,NEr,LEr,$Er,FEr,UEr,BEr,zEr,qEr,GEr,jEr,VEr,HEr,WEr,KEr,JEr,XEr,YEr,ZEr,QEr,eSr,tSr,rSr,nSr,oSr,iSr,sSr,aSr,b$n=E({"npm-stub:which"(){u_={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:u_.get}):new Proxy(function(...r){return new Proxy({},{get:u_.get})},{get:u_.get,apply(r,n,o){return new Proxy({},{get:u_.get})},construct(r,n){return new Proxy({},{get:u_.get})}})}},ds=new Proxy({},u_),dEr=ds,{BedrockClient:pEr,ListFoundationModelsCommand:mEr,BedrockRuntimeClient:hEr,ConverseCommand:fEr,ConverseStreamCommand:gEr,ImageFormat:yEr,InvokeModelCommand:vEr}=ds,{SageMakerRuntimeClient:_Er,InvokeEndpointCommand:wEr,InvokeEndpointWithResponseStreamCommand:bEr}=ds,{GoogleAuth:TEr,VertexAI:EEr,TextToSpeechClient:SEr}=ds,{Webhook:kEr}=ds,{Hippocampus:AEr,HippocampusConfig:CEr}=ds,{createClient:xEr}=ds,{Queue:IEr,Worker:REr,Job:MEr,QueueScheduler:PEr,FlowProducer:OEr}=ds,{Cron:DEr}=ds,{parseBuffer:NEr,selectCover:LEr}=ds,{extractRawText:$Er,convertToHtml:FEr}=ds,{Hono:UEr}=ds,{cors:BEr,HTTPException:zEr,logger:qEr,secureHeaders:GEr,streamSSE:jEr,timeout:VEr}=ds,HEr=globalThis.fetch,WEr=globalThis.Request,KEr=globalThis.Response,JEr=globalThis.Headers,XEr=globalThis.FormData,YEr=globalThis.File,ZEr=globalThis.Blob,QEr=ds.Agent,eSr=ds.Pool,tSr=ds.Client,rSr=ds.Dispatcher,nSr=()=>{},oSr=()=>ds,iSr=ds.MockAgent,sSr={redirect:()=>e=>e,retry:()=>e=>e},aSr=async(e,t)=>{const r=await globalThis.fetch(e,t);return{statusCode:r.status,headers:Object.fromEntries(r.headers.entries()),body:{text:()=>r.text(),json:()=>r.json(),arrayBuffer:()=>r.arrayBuffer()}}}}}),T$n=Sn({"node_modules/.pnpm/path-key@3.1.1/node_modules/path-key/index.js"(e,t){"use strict";var r=(n={})=>{const o=n.env||process.env;return(n.platform||process.platform)!=="win32"?"PATH":Object.keys(o).reverse().find(s=>s.toUpperCase()==="PATH")||"Path"};t.exports=r,t.exports.default=r}}),E$n=Sn({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js"(e,t){"use strict";var r=(Nr(),In(qh)),n=(b$n(),In(uEr)),o=T$n();function i(a,c){const l=a.options.env||process.env,u=process.cwd(),d=a.options.cwd!=null,p=d&&process.chdir!==void 0&&!process.chdir.disabled;if(p)try{process.chdir(a.options.cwd)}catch{}let m;try{m=n.sync(a.command,{path:l[o({env:l})],pathExt:c?r.delimiter:void 0})}catch{}finally{p&&process.chdir(u)}return m&&(m=r.resolve(d?a.options.cwd:"",m)),m}function s(a){return i(a)||i(a,!0)}t.exports=s}}),S$n=Sn({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/escape.js"(e,t){"use strict";var r=/([()\][%!^"`<>&|;, *?])/g;function n(i){return i=i.replace(r,"^$1"),i}function o(i,s){return i=`${i}`,i=i.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),i=i.replace(/(?=(\\+?)?)\1$/,"$1$1"),i=`"${i}"`,i=i.replace(r,"^$1"),s&&(i=i.replace(r,"^$1")),i}t.exports.command=n,t.exports.argument=o}}),k$n=Sn({"node_modules/.pnpm/shebang-regex@3.0.0/node_modules/shebang-regex/index.js"(e,t){"use strict";t.exports=/^#!(.*)/}}),A$n=Sn({"node_modules/.pnpm/shebang-command@2.0.0/node_modules/shebang-command/index.js"(e,t){"use strict";var r=k$n();t.exports=(n="")=>{const o=n.match(r);if(!o)return null;const[i,s]=o[0].replace(/#! ?/,"").split(" "),a=i.split("/").pop();return a==="env"?s:s?`${a} ${s}`:a}}}),C$n=Sn({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js"(e,t){"use strict";var r=(yo(),In(up)),n=A$n();function o(i){const a=Buffer.alloc(150);let c;try{c=r.openSync(i,"r"),r.readSync(c,a,0,150,0),r.closeSync(c)}catch{}return n(a.toString())}t.exports=o}}),x$n=Sn({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js"(e,t){"use strict";var r=(Nr(),In(qh)),n=E$n(),o=S$n(),i=C$n(),s=process.platform==="win32",a=/\.(?:com|exe)$/i,c=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function l(p){p.file=n(p);const m=p.file&&i(p.file);return m?(p.args.unshift(p.file),p.command=m,n(p)):p.file}function u(p){if(!s)return p;const m=l(p),h=!a.test(m);if(p.options.forceShell||h){const f=c.test(m);p.command=r.normalize(p.command),p.command=o.command(p.command),p.args=p.args.map(v=>o.argument(v,f));const y=[p.command].concat(p.args).join(" ");p.args=["/d","/s","/c",`"${y}"`],p.command=process.env.comspec||"cmd.exe",p.options.windowsVerbatimArguments=!0}return p}function d(p,m,h){m&&!Array.isArray(m)&&(h=m,m=null),m=m?m.slice(0):[],h=Object.assign({},h);const f={command:p,args:m,options:h,file:void 0,original:{command:p,args:m}};return h.shell?f:u(f)}t.exports=d}}),I$n=Sn({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/enoent.js"(e,t){"use strict";var r=process.platform==="win32";function n(a,c){return Object.assign(new Error(`${c} ${a.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${c} ${a.command}`,path:a.command,spawnargs:a.args})}function o(a,c){if(!r)return;const l=a.emit;a.emit=function(u,d){if(u==="exit"){const p=i(d,c);if(p)return l.call(a,"error",p)}return l.apply(a,arguments)}}function i(a,c){return r&&a===1&&!c.file?n(c.original,"spawn"):null}function s(a,c){return r&&a===1&&!c.file?n(c.original,"spawnSync"):null}t.exports={hookChildProcess:o,verifyENOENT:i,verifyENOENTSync:s,notFoundError:n}}}),R$n=Sn({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/index.js"(e,t){"use strict";var r=(Pje(),In(Xqe)),n=x$n(),o=I$n();function i(a,c,l){const u=n(a,c,l),d=r.spawn(u.command,u.args,u.options);return o.hookChildProcess(d,u),d}function s(a,c,l){const u=n(a,c,l),d=r.spawnSync(u.command,u.args,u.options);return d.error=d.error||o.verifyENOENTSync(d.status,u),d}t.exports=i,t.exports.spawn=i,t.exports.sync=s,t.exports._parse=n,t.exports._enoent=o}}),HB,M$n,P$n,O$n,D$n,WB,cSr,aye,N$n,L$n,$$n,F$n,U$n=E({"node-stub:node:process"(){HB={},M$n=globalThis.crypto,P$n=globalThis.ReadableStream||class{},O$n=globalThis.URL,D$n=globalThis.URLSearchParams,WB=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},WB.custom=Symbol.for("nodejs.util.inspect.custom"),WB.colors={},WB.styles={},cSr=globalThis.TextDecoder,aye=globalThis.TextEncoder,N$n=globalThis.performance||{now:()=>Date.now()},L$n=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),i=new Uint8Array(o.length);for(let s=0;s<o.length;s++)i[s]=o.charCodeAt(s);return i}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let i=0;i<t.length;i+=2)o[i/2]=parseInt(t.substr(i,2),16);return o}return new aye().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((i,s)=>i+s.length,0),n=new Uint8Array(r);let o=0;for(const i of t)n.set(i,o),o+=i.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new aye().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new cSr().decode(this)}},$$n=globalThis.clearTimeout,F$n=globalThis.clearInterval}});function B$n(e){return n_.parse(JSON.parse(e))}function z$n(e){return JSON.stringify(e)+`
1243
1243
  `}var lSr,uSr,q$n=E({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js"(){kg(),lSr=10*1024*1024,uSr=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??lSr}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;const e=this._buffer.indexOf(`
1244
1244
  `);if(e===-1)return null;const t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),B$n(t)}clear(){this._buffer=void 0}}}}),cye={};ae(cye,{DEFAULT_INHERITED_ENV_VARS:()=>lye,StdioClientTransport:()=>mSr,getDefaultEnvironment:()=>dSr});function dSr(){const e={};for(const t of lye){const r=HB.env[t];r!==void 0&&(r.startsWith("()")||(e[t]=r))}return e}var pSr,lye,mSr,hSr=E({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js"(){pSr=Hl(R$n(),1),U$n(),rde(),q$n(),lye=HB.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"],mSr=class{constructor(e){this._stderrStream=null,this._serverParams=e,this._readBuffer=new uSr({maxBufferSize:e.maxBufferSize}),(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new Zue)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,t)=>{this._process=(0,pSr.default)(this._serverParams.command,this._serverParams.args??[],{env:{...dSr(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:HB.platform==="win32",cwd:this._serverParams.cwd}),this._process.on("error",r=>{t(r),this.onerror?.(r)}),this._process.on("spawn",()=>{e()}),this._process.on("close",r=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",r=>{this.onerror?.(r)}),this._process.stdout?.on("data",r=>{try{this._readBuffer.append(r),this.processReadBuffer()}catch(n){this.onerror?.(n),this.close().catch(()=>{})}}),this._process.stdout?.on("error",r=>{this.onerror?.(r)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{const e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._process){const e=this._process;this._process=void 0;const t=new Promise(r=>{e.once("close",()=>{r()})});try{e.stdin?.end()}catch{}if(await Promise.race([t,new Promise(r=>setTimeout(r,2e3).unref())]),e.exitCode===null){try{e.kill("SIGTERM")}catch{}await Promise.race([t,new Promise(r=>setTimeout(r,2e3).unref())])}if(e.exitCode===null)try{e.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(e){return new Promise(t=>{if(!this._process?.stdin)throw new Error("Not connected");const r=z$n(e);this._process.stdin.write(r)?t():this._process.stdin.once("drain",t)})}}}});function uye(e){}function dye(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=uye,onError:r=uye,onRetry:n=uye,onComment:o}=e,i=[];let s=!0,a,c="",l=0,u;function d(v){if(s&&(s=!1,v.charCodeAt(0)===239&&v.charCodeAt(1)===187&&v.charCodeAt(2)===191&&(v=v.slice(3))),i.length===0){const T=p(v);T!==""&&i.push(T);return}if(v.indexOf(`
1245
1245
  `)===-1&&v.indexOf("\r")===-1){i.push(v);return}i.push(v);const _=i.join("");i.length=0;const w=p(_);w!==""&&i.push(w)}function p(v){let _=0;if(v.indexOf("\r")===-1){let w=v.indexOf(`
@@ -1253,7 +1253,7 @@ ${D}`,l++;return}if(gSr(v,_,T)){u=v.slice(v.charCodeAt(_+6)===Ag?_+7:_+6,w)||voi
1253
1253
  ${_}`,l++;break;case"id":a=_.includes("\0")?void 0:_;break;case"retry":/^\d+$/.test(_)?n(parseInt(_,10)):r(new pye(`Invalid \`retry\` value: "${_}"`,{type:"invalid-retry",value:_,line:w}));break;default:r(new pye(`Unknown field "${v.length>20?`${v.slice(0,20)}\u2026`:v}"`,{type:"unknown-field",field:v,value:_,line:w}));break}}function f(){l>0&&t({id:a,event:u,data:c}),a=void 0,c="",l=0,u=void 0}function y(v={}){if(v.consume&&i.length>0){const _=i.join("");m(_,0,_.length)}s=!0,a=void 0,c="",l=0,u=void 0,i.length=0}return{feed:d,reset:y}}function fSr(e,t,r){return r===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function gSr(e,t,r){return r===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}var pye,mye,ySr,Ag,hye=E({"node_modules/.pnpm/eventsource-parser@3.0.8/node_modules/eventsource-parser/dist/index.js"(){pye=class extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}},mye=10,ySr=13,Ag=32}});function G$n(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function fye(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(fye).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${fye(e.cause)}`:e.message:`${e}`}function vSr(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}function j$n(){const e="document"in globalThis?globalThis.document:void 0;return e&&typeof e=="object"&&"baseURI"in e&&typeof e.baseURI=="string"?e.baseURI:void 0}var gye,yye,KB,Dr,ps,ni,Xp,zc,d_,vS,JB,XB,B4,_S,z4,Cg,wS,bS,TS,q4,yd,vye,_ye,wye,_Sr,bye,Tye,G4,Eye,Sye,j4,V$n=E({"node_modules/.pnpm/eventsource@3.0.7/node_modules/eventsource/dist/index.js"(){hye(),gye=class extends Event{constructor(e,t){var r,n;super(e),this.code=(r=t?.code)!=null?r:void 0,this.message=(n=t?.message)!=null?n:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,t,r){return r(vSr(this),t)}[Symbol.for("Deno.customInspect")](e,t){return e(vSr(this),t)}},yye=e=>{throw TypeError(e)},KB=(e,t,r)=>t.has(e)||yye("Cannot "+r),Dr=(e,t,r)=>(KB(e,t,"read from private field"),r?r.call(e):t.get(e)),ps=(e,t,r)=>t.has(e)?yye("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),ni=(e,t,r,n)=>(KB(e,t,"write to private field"),t.set(e,r),r),Xp=(e,t,r)=>(KB(e,t,"access private method"),r),j4=class extends EventTarget{constructor(e,t){var r,n;super(),ps(this,yd),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,ps(this,zc),ps(this,d_),ps(this,vS),ps(this,JB),ps(this,XB),ps(this,B4),ps(this,_S),ps(this,z4,null),ps(this,Cg),ps(this,wS),ps(this,bS,null),ps(this,TS,null),ps(this,q4,null),ps(this,_ye,async o=>{var i;Dr(this,wS).reset();const{body:s,redirected:a,status:c,headers:l}=o;if(c===204){Xp(this,yd,G4).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(a?ni(this,vS,new URL(o.url)):ni(this,vS,void 0),c!==200){Xp(this,yd,G4).call(this,`Non-200 status code (${c})`,c);return}if(!(l.get("content-type")||"").startsWith("text/event-stream")){Xp(this,yd,G4).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(Dr(this,zc)===this.CLOSED)return;ni(this,zc,this.OPEN);const u=new Event("open");if((i=Dr(this,q4))==null||i.call(this,u),this.dispatchEvent(u),typeof s!="object"||!s||!("getReader"in s)){Xp(this,yd,G4).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}const d=new TextDecoder,p=s.getReader();let m=!0;do{const{done:h,value:f}=await p.read();f&&Dr(this,wS).feed(d.decode(f,{stream:!h})),h&&(m=!1,Dr(this,wS).reset(),Xp(this,yd,Eye).call(this))}while(m)}),ps(this,wye,o=>{ni(this,Cg,void 0),!(o.name==="AbortError"||o.type==="aborted")&&Xp(this,yd,Eye).call(this,fye(o))}),ps(this,bye,o=>{typeof o.id=="string"&&ni(this,z4,o.id);const i=new MessageEvent(o.event||"message",{data:o.data,origin:Dr(this,vS)?Dr(this,vS).origin:Dr(this,d_).origin,lastEventId:o.id||""});Dr(this,TS)&&(!o.event||o.event==="message")&&Dr(this,TS).call(this,i),this.dispatchEvent(i)}),ps(this,Tye,o=>{ni(this,B4,o)}),ps(this,Sye,()=>{ni(this,_S,void 0),Dr(this,zc)===this.CONNECTING&&Xp(this,yd,vye).call(this)});try{if(e instanceof URL)ni(this,d_,e);else if(typeof e=="string")ni(this,d_,new URL(e,j$n()));else throw new Error("Invalid URL")}catch{throw G$n("An invalid or illegal string was specified")}ni(this,wS,dye({onEvent:Dr(this,bye),onRetry:Dr(this,Tye)})),ni(this,zc,this.CONNECTING),ni(this,B4,3e3),ni(this,XB,(r=t?.fetch)!=null?r:globalThis.fetch),ni(this,JB,(n=t?.withCredentials)!=null?n:!1),Xp(this,yd,vye).call(this)}get readyState(){return Dr(this,zc)}get url(){return Dr(this,d_).href}get withCredentials(){return Dr(this,JB)}get onerror(){return Dr(this,bS)}set onerror(e){ni(this,bS,e)}get onmessage(){return Dr(this,TS)}set onmessage(e){ni(this,TS,e)}get onopen(){return Dr(this,q4)}set onopen(e){ni(this,q4,e)}addEventListener(e,t,r){const n=t;super.addEventListener(e,n,r)}removeEventListener(e,t,r){const n=t;super.removeEventListener(e,n,r)}close(){Dr(this,_S)&&clearTimeout(Dr(this,_S)),Dr(this,zc)!==this.CLOSED&&(Dr(this,Cg)&&Dr(this,Cg).abort(),ni(this,zc,this.CLOSED),ni(this,Cg,void 0))}},zc=new WeakMap,d_=new WeakMap,vS=new WeakMap,JB=new WeakMap,XB=new WeakMap,B4=new WeakMap,_S=new WeakMap,z4=new WeakMap,Cg=new WeakMap,wS=new WeakMap,bS=new WeakMap,TS=new WeakMap,q4=new WeakMap,yd=new WeakSet,vye=function(){ni(this,zc,this.CONNECTING),ni(this,Cg,new AbortController),Dr(this,XB)(Dr(this,d_),Xp(this,yd,_Sr).call(this)).then(Dr(this,_ye)).catch(Dr(this,wye))},_ye=new WeakMap,wye=new WeakMap,_Sr=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Dr(this,z4)?{"Last-Event-ID":Dr(this,z4)}:void 0},cache:"no-store",signal:(e=Dr(this,Cg))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},bye=new WeakMap,Tye=new WeakMap,G4=function(e,t){var r;Dr(this,zc)!==this.CLOSED&&ni(this,zc,this.CLOSED);const n=new gye("error",{code:t,message:e});(r=Dr(this,bS))==null||r.call(this,n),this.dispatchEvent(n)},Eye=function(e,t){var r;if(Dr(this,zc)===this.CLOSED)return;ni(this,zc,this.CONNECTING);const n=new gye("error",{code:t,message:e});(r=Dr(this,bS))==null||r.call(this,n),this.dispatchEvent(n),ni(this,_S,setTimeout(Dr(this,Sye),Dr(this,B4)))},Sye=new WeakMap,j4.CONNECTING=0,j4.OPEN=1,j4.CLOSED=2}});function YB(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function wSr(e=fetch,t){return t?async(r,n)=>{const o={...t,...n,headers:n?.headers?{...YB(t.headers),...YB(n.headers)}:t.headers};return e(r,o)}:e}function H$n(e,t){return e.protocol===t.protocol&&e.hostname===t.hostname&&e.port===t.port?!0:e.hostname===t.hostname&&e.protocol==="http:"&&e.port===""&&t.protocol==="https:"&&t.port===""}function bSr(e,t){const r=ESr.includes(e.status)?e.headers.get("location"):null;try{return r?new URL(r,t):void 0}catch{return}}function kye(e,t,r,n,o=0){const i=bSr(n,t),s=n.status===307||n.status===308||(r?.method??"GET").toUpperCase()==="GET";if(!i||o===TSr||!s)return;const a=new URL(t);if(!((i.username||i.password)&&(i.username!==a.username||i.password!==a.password)||!H$n(a,i)))return Promise.resolve(n.body?.cancel()).then(()=>e(i,{...r,redirect:"manual"})).then(l=>kye(e,i,r,l,o+1)??l)}function ZB(e){const t=(r,n)=>(e??fetch)(r,n);return Cye.add(t),t}function p_(e=fetch){return Cye.has(e)?e:(t,r)=>r?.redirect==="error"||r?.redirect==="manual"?e(t,r):Promise.resolve(e(t,{...r,redirect:"manual"})).then(n=>kye(e,t,r,n)??n)}function Aye(e,t){if(e.type==="opaqueredirect")return"Redirect not followed: this runtime does not expose the redirect target";const r=e.url||t,n=bSr(e,r);if(n)return n.username=n.password=n.search=n.hash="",n.protocol==="http:"&&new URL(r).protocol==="https:"?(n.protocol="https:",`Redirect to plain http not followed; try ${n.href} instead`):`Redirect to ${n.href} not followed`}var TSr,ESr,Cye,xye=E({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js"(){TSr=5,ESr=[301,302,303,307,308],Cye=new WeakSet}}),m_,Ls,SSr,W$n,K$n,J$n,X$n,Y$n,Z$n,Q$n,eFn,tFn,rFn,nFn,oFn,iFn,sFn,aFn,cFn,lFn,uFn,dFn,pFn,mFn,hFn,fFn,gFn,yFn,vFn,_Fn,wFn,bFn,TFn,EFn,SFn,kFn,AFn,CFn,xFn,IFn,RFn,MFn,PFn,OFn,DFn,NFn,LFn,$Fn,FFn,UFn=E({"npm-stub:pkce-challenge"(){m_={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:m_.get}):new Proxy(function(...r){return new Proxy({},{get:m_.get})},{get:m_.get,apply(r,n,o){return new Proxy({},{get:m_.get})},construct(r,n){return new Proxy({},{get:m_.get})}})}},Ls=new Proxy({},m_),SSr=Ls,{BedrockClient:W$n,ListFoundationModelsCommand:K$n,BedrockRuntimeClient:J$n,ConverseCommand:X$n,ConverseStreamCommand:Y$n,ImageFormat:Z$n,InvokeModelCommand:Q$n}=Ls,{SageMakerRuntimeClient:eFn,InvokeEndpointCommand:tFn,InvokeEndpointWithResponseStreamCommand:rFn}=Ls,{GoogleAuth:nFn,VertexAI:oFn,TextToSpeechClient:iFn}=Ls,{Webhook:sFn}=Ls,{Hippocampus:aFn,HippocampusConfig:cFn}=Ls,{createClient:lFn}=Ls,{Queue:uFn,Worker:dFn,Job:pFn,QueueScheduler:mFn,FlowProducer:hFn}=Ls,{Cron:fFn}=Ls,{parseBuffer:gFn,selectCover:yFn}=Ls,{extractRawText:vFn,convertToHtml:_Fn}=Ls,{Hono:wFn}=Ls,{cors:bFn,HTTPException:TFn,logger:EFn,secureHeaders:SFn,streamSSE:kFn,timeout:AFn}=Ls,CFn=globalThis.fetch,xFn=globalThis.Request,IFn=globalThis.Response,RFn=globalThis.Headers,MFn=globalThis.FormData,PFn=globalThis.File,OFn=globalThis.Blob,DFn=Ls.Agent,NFn=Ls.Pool,LFn=Ls.Client,$Fn=Ls.Dispatcher,FFn=Ls.MockAgent}}),Zs,kSr,Iye,ASr,CSr,xSr,ISr,Rye,RSr,MSr,PSr,BFn,zFn,OSr=E({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js"(){_br(),Zs=XK().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:pJ.custom,message:"URL must be parseable",fatal:!0}),fO}).refine(e=>{const t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),kSr=Ts({resource:ce().url(),authorization_servers:ct(Zs).optional(),jwks_uri:ce().url().optional(),scopes_supported:ct(ce()).optional(),bearer_methods_supported:ct(ce()).optional(),resource_signing_alg_values_supported:ct(ce()).optional(),resource_name:ce().optional(),resource_documentation:ce().optional(),resource_policy_uri:ce().url().optional(),resource_tos_uri:ce().url().optional(),tls_client_certificate_bound_access_tokens:Rn().optional(),authorization_details_types_supported:ct(ce()).optional(),dpop_signing_alg_values_supported:ct(ce()).optional(),dpop_bound_access_tokens_required:Rn().optional()}),Iye=Ts({issuer:ce(),authorization_endpoint:Zs,token_endpoint:Zs,registration_endpoint:Zs.optional(),scopes_supported:ct(ce()).optional(),response_types_supported:ct(ce()),response_modes_supported:ct(ce()).optional(),grant_types_supported:ct(ce()).optional(),token_endpoint_auth_methods_supported:ct(ce()).optional(),token_endpoint_auth_signing_alg_values_supported:ct(ce()).optional(),service_documentation:Zs.optional(),revocation_endpoint:Zs.optional(),revocation_endpoint_auth_methods_supported:ct(ce()).optional(),revocation_endpoint_auth_signing_alg_values_supported:ct(ce()).optional(),introspection_endpoint:ce().optional(),introspection_endpoint_auth_methods_supported:ct(ce()).optional(),introspection_endpoint_auth_signing_alg_values_supported:ct(ce()).optional(),code_challenge_methods_supported:ct(ce()).optional(),client_id_metadata_document_supported:Rn().optional()}),ASr=Ts({issuer:ce(),authorization_endpoint:Zs,token_endpoint:Zs,userinfo_endpoint:Zs.optional(),jwks_uri:Zs,registration_endpoint:Zs.optional(),scopes_supported:ct(ce()).optional(),response_types_supported:ct(ce()),response_modes_supported:ct(ce()).optional(),grant_types_supported:ct(ce()).optional(),acr_values_supported:ct(ce()).optional(),subject_types_supported:ct(ce()),id_token_signing_alg_values_supported:ct(ce()),id_token_encryption_alg_values_supported:ct(ce()).optional(),id_token_encryption_enc_values_supported:ct(ce()).optional(),userinfo_signing_alg_values_supported:ct(ce()).optional(),userinfo_encryption_alg_values_supported:ct(ce()).optional(),userinfo_encryption_enc_values_supported:ct(ce()).optional(),request_object_signing_alg_values_supported:ct(ce()).optional(),request_object_encryption_alg_values_supported:ct(ce()).optional(),request_object_encryption_enc_values_supported:ct(ce()).optional(),token_endpoint_auth_methods_supported:ct(ce()).optional(),token_endpoint_auth_signing_alg_values_supported:ct(ce()).optional(),display_values_supported:ct(ce()).optional(),claim_types_supported:ct(ce()).optional(),claims_supported:ct(ce()).optional(),service_documentation:ce().optional(),claims_locales_supported:ct(ce()).optional(),ui_locales_supported:ct(ce()).optional(),claims_parameter_supported:Rn().optional(),request_parameter_supported:Rn().optional(),request_uri_parameter_supported:Rn().optional(),require_request_uri_registration:Rn().optional(),op_policy_uri:Zs.optional(),op_tos_uri:Zs.optional(),client_id_metadata_document_supported:Rn().optional()}),CSr=mt({...ASr.shape,...Iye.pick({code_challenge_methods_supported:!0}).shape}),xSr=mt({access_token:ce(),id_token:ce().optional(),token_type:ce(),expires_in:vJ.number().optional(),scope:ce().optional(),refresh_token:ce().optional(),issuer:ce().optional().catch(void 0)}).strip(),ISr=mt({error:ce(),error_description:ce().optional(),error_uri:ce().optional()}),Rye=Zs.optional().or(Mt("").transform(()=>{})),RSr=mt({redirect_uris:ct(Zs),token_endpoint_auth_method:ce().optional(),grant_types:ct(ce()).optional(),response_types:ct(ce()).optional(),client_name:ce().optional(),client_uri:Zs.optional(),logo_uri:Rye,scope:ce().optional(),contacts:ct(ce()).optional(),tos_uri:Rye,policy_uri:ce().optional(),jwks_uri:Zs.optional(),jwks:YK().optional(),software_id:ce().optional(),software_version:ce().optional(),software_statement:ce().optional()}).strip(),MSr=mt({client_id:ce(),client_secret:ce().optional(),client_id_issued_at:Yr().optional(),client_secret_expires_at:Yr().optional(),issuer:ce().optional().catch(void 0)}).strip(),PSr=RSr.merge(MSr),BFn=mt({error:ce(),error_description:ce().optional()}).strip(),zFn=mt({token:ce(),token_type_hint:ce().optional()}).strip()}});function qFn(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function GFn({requestedResource:e,configuredResource:t}){const r=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;const o=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",i=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return o.startsWith(i)}var jFn=E({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js"(){}}),$s,QB,V4,H4,W4,e9,t9,r9,h_,n9,o9,i9,s9,a9,c9,K4,l9,u9,DSr,VFn=E({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js"(){$s=class extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){const e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},QB=class extends $s{},QB.errorCode="invalid_request",V4=class extends $s{},V4.errorCode="invalid_client",H4=class extends $s{},H4.errorCode="invalid_grant",W4=class extends $s{},W4.errorCode="unauthorized_client",e9=class extends $s{},e9.errorCode="unsupported_grant_type",t9=class extends $s{},t9.errorCode="invalid_scope",r9=class extends $s{},r9.errorCode="access_denied",h_=class extends $s{},h_.errorCode="server_error",n9=class extends $s{},n9.errorCode="temporarily_unavailable",o9=class extends $s{},o9.errorCode="unsupported_response_type",i9=class extends $s{},i9.errorCode="unsupported_token_type",s9=class extends $s{},s9.errorCode="invalid_token",a9=class extends $s{},a9.errorCode="method_not_allowed",c9=class extends $s{},c9.errorCode="too_many_requests",K4=class extends $s{},K4.errorCode="invalid_client_metadata",l9=class extends $s{},l9.errorCode="insufficient_scope",u9=class extends $s{},u9.errorCode="invalid_target",DSr={[QB.errorCode]:QB,[V4.errorCode]:V4,[H4.errorCode]:H4,[W4.errorCode]:W4,[e9.errorCode]:e9,[t9.errorCode]:t9,[r9.errorCode]:r9,[h_.errorCode]:h_,[n9.errorCode]:n9,[o9.errorCode]:o9,[i9.errorCode]:i9,[s9.errorCode]:s9,[a9.errorCode]:a9,[c9.errorCode]:c9,[K4.errorCode]:K4,[l9.errorCode]:l9,[u9.errorCode]:u9}}});function HFn(e){return["client_secret_basic","client_secret_post","none"].includes(e)}function WFn(e,t){const r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&HFn(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?r?"client_secret_basic":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}function KFn(e,t,r,n){const{client_id:o,client_secret:i}=t;switch(e){case"client_secret_basic":JFn(o,i,r);return;case"client_secret_post":XFn(o,i,n);return;case"none":YFn(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function JFn(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}function XFn(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function YFn(e,t){t.set("client_id",e)}async function NSr(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=ISr.parse(JSON.parse(r)),{error:o,error_description:i,error_uri:s}=n,a=DSr[o]||h_;return new a(i||"",s)}catch(n){const o=e instanceof Response?Aye(e,e.url):void 0,i=`${t?`HTTP ${t}: `:""}${o??`Invalid OAuth error response: ${n}. Raw body: ${r}`}`;return new h_(i)}}function ZFn(e,t){let[r,n]=[e,t];try{[r,n]=[new URL(e).href,new URL(t).href]}catch{}return r===n||r.endsWith("/")&&r.slice(0,-1)===n||n.endsWith("/")&&n.slice(0,-1)===r}function Mye(e,t){if(e)return typeof e.issuer!="string"?e.issuer==null?e:{...e,issuer:void 0}:ZFn(e.issuer,t)?e:void 0}function LSr(e,t){return new Error(`OAuth client information is bound to authorization server ${e.issuer} and is not presented to ${t}. Clear the stored client information, or correct \`expectedIssuer\`, if the authorization server has moved.`)}async function f_(e,t){try{return await Pye(e,t)}catch(r){if(r instanceof V4||r instanceof W4)return await e.invalidateCredentials?.("all"),await Pye(e,t);if(r instanceof H4)return await e.invalidateCredentials?.("tokens"),await Pye(e,t);throw r}}async function Pye(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:i}){const s=await e.discoveryState?.();let a,c,l,u=o;if(!u&&s?.resourceMetadataUrl&&(u=new URL(s.resourceMetadataUrl)),s?.authorizationServerUrl){if(c=s.authorizationServerUrl,a=s.resourceMetadata,l=s.authorizationServerMetadata??await USr(c,{fetchFn:i}),!a)try{a=await $Sr(t,{resourceMetadataUrl:u},i)}catch{}(l!==s.authorizationServerMetadata||a!==s.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:u?.toString(),resourceMetadata:a,authorizationServerMetadata:l})}else{const x=await i5n(t,{resourceMetadataUrl:u,fetchFn:i});c=x.authorizationServerUrl,l=x.authorizationServerMetadata,a=x.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:u?.toString(),resourceMetadata:a,authorizationServerMetadata:l})}const d=String(c),p=await e5n(t,e,a),m=p&&a&&!e.validateResourceURL?a.resource:p,h=n||a?.scopes_supported?.join(" ")||e.clientMetadata.scope,f=await Promise.resolve(e.clientInformation());let y=Mye(f,d);const v=e.saveClientInformation!==void 0&&!!e.redirectUrl;if(f&&!y&&!v)throw LSr(f,d);const _=y?.issuer==null?y:void 0,w=async()=>{try{_&&await e.saveClientInformation?.({..._,issuer:d})}catch{}};if(!y){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const x=l?.client_id_metadata_document_supported===!0,O=e.clientMetadataUrl;if(O&&!QFn(O))throw new K4(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${O}`);if(x&&O)y={client_id:O,issuer:d},await e.saveClientInformation?.(y);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");y={...await u5n(c,{metadata:l,clientMetadata:e.clientMetadata,scope:h,fetchFn:i}),issuer:d},await e.saveClientInformation(y)}}const T=!e.redirectUrl;if(r!==void 0||T){const x=await l5n(e,c,{metadata:l,resource:m,authorizationCode:r,fetchFn:i});return await w(),await e.saveTokens({...x,issuer:d}),"AUTHORIZED"}const k=Mye(await e.tokens(),d);if(k?.refresh_token&&k.issuer==null&&console.warn("[mcp-sdk] stored OAuth tokens have no 'issuer' property (saved by an earlier version, or by a provider that does not keep it) and are used as-is; make sure your OAuthClientProvider stores what saveTokens() and saveClientInformation() receive unchanged."),k?.refresh_token)try{const x=await c5n(c,{metadata:l,clientInformation:y,refreshToken:k.refresh_token,resource:m,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await w(),await e.saveTokens({...x,issuer:d}),"AUTHORIZED"}catch(x){if(!(!(x instanceof $s)||x instanceof h_))throw x}const A=e.state?await e.state():void 0,{authorizationUrl:C,codeVerifier:M}=await s5n(c,{metadata:l,clientInformation:y,state:A,redirectUrl:e.redirectUrl,scope:h,resource:m});return await e.saveCodeVerifier(M),await e.redirectToAuthorization(C),"REDIRECT"}function QFn(e){if(!e)return!1;try{const t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function e5n(e,t,r){const n=qFn(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!GFn({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function d9(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};const o=Oye(e,"resource_metadata")||void 0;let i;if(o)try{i=new URL(o)}catch{}const s=Oye(e,"scope")||void 0,a=Oye(e,"error")||void 0;return{resourceMetadataUrl:i,scope:s,error:a}}function Oye(e,t){const r=e.headers.get("WWW-Authenticate");if(!r)return null;const n=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),o=r.match(n);return o?o[1]||o[2]:null}async function $Sr(e,t,r=fetch){const n=await n5n(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n||n.status===404)throw await n?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await n.body?.cancel(),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return kSr.parse(await n.json())}async function Dye(e,t,r=fetch){try{return await p_(r)(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?Dye(e,void 0,r):void 0;throw n}}function t5n(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function FSr(e,t,r=fetch){return await Dye(e,{"MCP-Protocol-Version":t},r)}function r5n(e,t){return!e||!e.ok&&e.status<500&&t!=="/"}async function n5n(e,t,r,n){const o=new URL(e),i=n?.protocolVersion??D4;let s;if(n?.metadataUrl)s=new URL(n.metadataUrl);else{const c=t5n(t,o.pathname);s=new URL(c,n?.metadataServerUrl??o),s.search=o.search}let a=await FSr(s,i,r);if(!n?.metadataUrl&&r5n(a,o.pathname)){const c=new URL(`/.well-known/${t}`,o);a=await FSr(c,i,r)}return a}function o5n(e){const t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let o=t.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,t.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${o}`,t.origin),type:"oidc"}),n.push({url:new URL(`${o}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}async function USr(e,{fetchFn:t=fetch,protocolVersion:r=D4}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"},o=o5n(e);for(const{url:i,type:s}of o){const a=await Dye(i,n,t);if(a){if(!a.ok){if(await a.body?.cancel(),a.status<500)continue;throw new Error(`HTTP ${a.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}return s==="oauth"?Iye.parse(await a.json()):CSr.parse(await a.json())}}}async function i5n(e,t){let r,n;try{r=await $Sr(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(n=r.authorization_servers[0])}catch{}n||(n=String(new URL("/",e)));const o=await USr(n,{fetchFn:t?.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:o,resourceMetadata:r}}function BSr(e){return typeof e=="string"?e:e.href}async function s5n(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:o,state:i,resource:s}){let a;if(t){if(a=new URL(t.authorization_endpoint),!t.response_types_supported.includes(p9))throw new Error(`Incompatible auth server: does not support response type ${p9}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(m9))throw new Error(`Incompatible auth server: does not support code challenge method ${m9}`)}else a=new URL("/authorize",e);const c=await SSr(),l=c.code_verifier,u=c.code_challenge;return a.searchParams.set("response_type",p9),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",u),a.searchParams.set("code_challenge_method",m9),a.searchParams.set("redirect_uri",String(n)),i&&a.searchParams.set("state",i),o&&a.searchParams.set("scope",o),o?.includes("offline_access")&&a.searchParams.append("prompt","consent"),s&&a.searchParams.set("resource",BSr(s)),{authorizationUrl:a,codeVerifier:l}}function a5n(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function zSr(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:o,resource:i,fetchFn:s}){const a=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),c=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(i&&r.set("resource",BSr(i)),o)await o(c,r,a,t);else if(n){const u=t?.token_endpoint_auth_methods_supported??[],d=WFn(n,u);KFn(d,n,c,r)}const l=await p_(s??fetch)(a,{method:"POST",headers:c,body:r});if(!l.ok)throw await NSr(l);return qSr.parse(await l.json())}async function c5n(e,{metadata:t,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:i,fetchFn:s}){const a=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),c=await zSr(e,{metadata:t,tokenRequestParams:a,clientInformation:r,addClientAuthentication:i,resource:o,fetchFn:s});return{refresh_token:n,...c}}async function l5n(e,t,{metadata:r,resource:n,authorizationCode:o,fetchFn:i}={}){const s=async()=>{const u=await e.clientInformation(),d=Mye(u,String(t));if(u&&!d)throw LSr(u,String(t));return d};let a=await s();const c=e.clientMetadata.scope;let l;if(e.prepareTokenRequest&&(l=await e.prepareTokenRequest(c)),!l){if(!o)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");const u=await e.codeVerifier();l=a5n(o,u,e.redirectUrl)}return a??(a=await s()),zSr(t,{metadata:r,tokenRequestParams:l,clientInformation:a,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:i})}async function u5n(e,{metadata:t,clientMetadata:r,scope:n,fetchFn:o}){let i;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(t.registration_endpoint)}else i=new URL("/register",e);const s=await p_(o??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...n!==void 0?{scope:n}:{}})});if(!s.ok)throw await NSr(s);return GSr.parse(await s.json())}var Su,p9,m9,qSr,GSr,jSr=E({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"(){UFn(),kg(),OSr(),OSr(),jFn(),VFn(),xye(),Su=class extends Error{constructor(e){super(e??"Unauthorized")}},p9="code",m9="S256",qSr=xSr.omit({issuer:!0}),GSr=PSr.omit({issuer:!0})}}),VSr={};ae(VSr,{SSEClientTransport:()=>HSr,SseError:()=>Nye});var Nye,HSr,d5n=E({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js"(){V$n(),xye(),kg(),jSr(),Nye=class extends Error{constructor(e,t,r){super(`SSE error: ${t}`),this.code=e,this.event=r}},HSr=class{constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=t?.eventSourceInit,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=wSr(t?.fetch,t?.requestInit),this._followRedirects=t?.redirectPolicy==="follow",this._followRedirects&&(this._fetch=ZB(this._fetch),this._fetchWithInit=ZB(this._fetchWithInit))}_unfollowedRedirect(e,t){const r=Aye(e,t);return r&&!this._followRedirects?`${r} (redirectPolicy: 'same-origin')`:r}async _authThenStart(){if(!this._authProvider)throw new Su("No auth provider");let e;try{e=await f_(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(t){throw this.onerror?.(t),t}if(e!=="AUTHORIZED")throw new Su;return await this._startOrAuth()}async _commonHeaders(){const e={};if(this._authProvider){const r=await this._authProvider.tokens();r&&(e.Authorization=`Bearer ${r.access_token}`)}this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);const t=YB(this._requestInit?.headers);return new Headers({...e,...t})}_startOrAuth(){const e=this?._eventSourceInit?.fetch??this._fetch??fetch,t=this._followRedirects?e:p_(e);let r;return new Promise((n,o)=>{this._eventSource=new j4(this._url.href,{...this._eventSourceInit,fetch:async(i,s)=>{const a=await this._commonHeaders();a.set("Accept","text/event-stream");const c=await t(i,{...s,headers:a});if(r=this._unfollowedRedirect(c,i),c.status===401&&c.headers.has("www-authenticate")){const{resourceMetadataUrl:l,scope:u}=d9(c);this._resourceMetadataUrl=l,this._scope=u}return c}}),this._abortController=new AbortController,this._eventSource.onerror=i=>{if(i.code===401&&this._authProvider){this._authThenStart().then(n,o);return}const s=new Nye(i.code,r??i.message,i);o(s),this.onerror?.(s)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",i=>{const s=i;try{if(this._endpoint=new URL(s.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(a){o(a),this.onerror?.(a),this.close();return}n()}),this._eventSource.onmessage=i=>{const s=i;let a;try{a=n_.parse(JSON.parse(s.data))}catch(c){this.onerror?.(c);return}this.onmessage?.(a)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new Su("No auth provider");if(await f_(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Su("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(e){if(!this._endpoint)throw new Error("Not connected");try{const t=await this._commonHeaders();t.set("content-type","application/json");const r={...this._requestInit,method:"POST",headers:t,body:JSON.stringify(e),signal:this._abortController?.signal},n=await p_(this._fetch??fetch)(this._endpoint,r);if(!n.ok){const o=await n.text().catch(()=>null);if(n.status===401&&this._authProvider){const{resourceMetadataUrl:i,scope:s}=d9(n);if(this._resourceMetadataUrl=i,this._scope=s,await f_(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Su;return this.send(e)}throw new Error(`Error POSTing to endpoint (HTTP ${n.status}): ${this._unfollowedRedirect(n,this._endpoint)??o}`)}await n.body?.cancel()}catch(t){throw this.onerror?.(t),t}}setProtocolVersion(e){this._protocolVersion=e}}}}),WSr={};ae(WSr,{WebSocketClientTransport:()=>JSr});var KSr,JSr,p5n=E({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/client/websocket.js"(){kg(),KSr="mcp",JSr=class{constructor(e){this._url=e}start(){if(this._socket)throw new Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,t)=>{this._socket=new WebSocket(this._url,KSr),this._socket.onerror=r=>{const n="error"in r?r.error:new Error(`WebSocket error: ${JSON.stringify(r)}`);t(n),this.onerror?.(n)},this._socket.onopen=()=>{e()},this._socket.onclose=()=>{this.onclose?.()},this._socket.onmessage=r=>{let n;try{n=n_.parse(JSON.parse(r.data))}catch(o){this.onerror?.(o);return}this.onmessage?.(n)}})}async close(){this._socket?.close()}send(e){return new Promise((t,r)=>{if(!this._socket){r(new Error("Not connected"));return}this._socket?.send(JSON.stringify(e)),t()})}}}}),m5n=Sn({"node_modules/.pnpm/content-type@1.0.5/node_modules/content-type/index.js"(e){"use strict";var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,r=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,n=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,o=/\\([\u000b\u0020-\u00ff])/g,i=/([\\"])/g,s=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.format=a,e.parse=c;function a(p){if(!p||typeof p!="object")throw new TypeError("argument obj is required");var m=p.parameters,h=p.type;if(!h||!s.test(h))throw new TypeError("invalid type");var f=h;if(m&&typeof m=="object")for(var y,v=Object.keys(m).sort(),_=0;_<v.length;_++){if(y=v[_],!n.test(y))throw new TypeError("invalid parameter name");f+="; "+y+"="+u(m[y])}return f}function c(p){if(!p)throw new TypeError("argument string is required");var m=typeof p=="object"?l(p):p;if(typeof m!="string")throw new TypeError("argument string is required to be a string");var h=m.indexOf(";"),f=h!==-1?m.slice(0,h).trim():m.trim();if(!s.test(f))throw new TypeError("invalid media type");var y=new d(f.toLowerCase());if(h!==-1){var v,_,w;for(t.lastIndex=h;_=t.exec(m);){if(_.index!==h)throw new TypeError("invalid parameter format");h+=_[0].length,v=_[1].toLowerCase(),w=_[2],w.charCodeAt(0)===34&&(w=w.slice(1,-1),w.indexOf("\\")!==-1&&(w=w.replace(o,"$1"))),y.parameters[v]=w}if(h!==m.length)throw new TypeError("invalid parameter format")}return y}function l(p){var m;if(typeof p.getHeader=="function"?m=p.getHeader("content-type"):typeof p.headers=="object"&&(m=p.headers&&p.headers["content-type"]),typeof m!="string")throw new TypeError("content-type header is missing from object");return m}function u(p){var m=String(p);if(n.test(m))return m;if(m.length>0&&!r.test(m))throw new TypeError("invalid parameter value");return'"'+m.replace(i,"\\$1")+'"'}function d(p){this.parameters=Object.create(null),this.type=p}}});function h5n(e){if(e)try{return XSr.default.parse(e).type}catch{const t=(e.split(";",1)[0]??"").trim().toLowerCase();return t===""||e.slice(t.length).includes(",")?void 0:t}}var XSr,f5n=E({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/mediaType.js"(){XSr=Hl(m5n(),1)}}),YSr,g5n=E({"node_modules/.pnpm/eventsource-parser@3.0.8/node_modules/eventsource-parser/dist/stream.js"(){hye(),YSr=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:r}={}){let n;super({start(o){n=dye({onEvent:i=>{o.enqueue(i)},onError(i){e==="terminate"?o.error(i):typeof e=="function"&&e(i)},onRetry:t,onComment:r})},transform(o){n.feed(o)}})}}}}),ZSr={};ae(ZSr,{StreamableHTTPClientTransport:()=>ekr,StreamableHTTPError:()=>xg});var QSr,xg,ekr,y5n=E({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js"(){f5n(),xye(),kg(),jSr(),g5n(),QSr={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},xg=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},ekr=class{constructor(e,t){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=wSr(t?.fetch,t?.requestInit),this._followRedirects=t?.redirectPolicy==="follow",this._followRedirects&&(this._fetch=ZB(this._fetch),this._fetchWithInit=ZB(this._fetchWithInit)),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??QSr}_unfollowedRedirect(e,t){const r=Aye(e,t);return r&&!this._followRedirects?`${r} (redirectPolicy: 'same-origin')`:r}async _authThenStart(){if(!this._authProvider)throw new Su("No auth provider");let e;try{e=await f_(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(t){throw this.onerror?.(t),t}if(e!=="AUTHORIZED")throw new Su;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){const e={};if(this._authProvider){const r=await this._authProvider.tokens();r&&(e.Authorization=`Bearer ${r.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);const t=YB(this._requestInit?.headers);return new Headers({...e,...t})}async _startOrAuthSse(e){const{resumptionToken:t}=e;try{const r=await this._commonHeaders();r.set("Accept","text/event-stream"),t&&r.set("last-event-id",t);const n=this._fetch??fetch,o={method:"GET",headers:r,signal:this._abortController?.signal};let i=await n(this._url,this._followRedirects?o:{...o,redirect:"manual"});const s=this._followRedirects?void 0:kye(n,this._url,o,i);if(s&&(i=await s),!i.ok){if(await i.body?.cancel(),i.status===401&&this._authProvider)return await this._authThenStart();if(i.status===405)return;throw new xg(i.status,`Failed to open SSE stream: ${this._unfollowedRedirect(i,this._url)??i.statusText}`)}this._handleSseStream(i.body,e,!0)}catch(r){throw this.onerror?.(r),r}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;const t=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(r,e),n)}_scheduleReconnection(e,t=0){const r=this._reconnectionOptions.maxRetries;if(t>=r){this.onerror?.(new Error(`Maximum reconnection attempts (${r}) exceeded.`));return}const n=this._getNextReconnectionDelay(t);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(o=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${o instanceof Error?o.message:String(o)}`)),this._scheduleReconnection(e,t+1)})},n)}_handleSseStream(e,t,r){if(!e)return;const{onresumptiontoken:n,replayMessageId:o}=t;let i,s=!1,a=!1;(async()=>{try{const l=e.pipeThrough(new TextDecoderStream).pipeThrough(new YSr({onRetry:p=>{this._serverRetryMs=p}})).getReader();for(;;){const{value:p,done:m}=await l.read();if(m)break;if(p.id&&(i=p.id,s=!0,n?.(p.id)),!!p.data&&(!p.event||p.event==="message"))try{const h=n_.parse(JSON.parse(p.data));dS(h)&&(a=!0,o!==void 0&&(h.id=o)),this.onmessage?.(h)}catch(h){this.onerror?.(h)}}(r||s)&&!a&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:i,onresumptiontoken:n,replayMessageId:o},0)}catch(l){if(this.onerror?.(new Error(`SSE stream disconnected: ${l}`)),(r||s)&&!a&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:n,replayMessageId:o},0)}catch(p){this.onerror?.(new Error(`Failed to reconnect: ${p instanceof Error?p.message:String(p)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Su("No auth provider");if(await f_(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Su("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,t){try{const{resumptionToken:r,onresumptiontoken:n}=t||{};if(r){this._startOrAuthSse({resumptionToken:r,replayMessageId:CB(e)?e.id:void 0}).catch(p=>this.onerror?.(p));return}const o=await this._commonHeaders();o.set("content-type","application/json"),o.set("accept","application/json, text/event-stream");const i={...this._requestInit,method:"POST",headers:o,body:JSON.stringify(e),signal:this._abortController?.signal},s=await p_(this._fetch??fetch)(this._url,i),a=s.headers.get("mcp-session-id");if(a&&(this._sessionId=a),!s.ok){const p=await s.text().catch(()=>null);if(s.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new xg(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:m,scope:h}=d9(s);if(this._resourceMetadataUrl=m,this._scope=h,await f_(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Su;return this._hasCompletedAuthFlow=!0,this.send(e)}if(s.status===403&&this._authProvider){const{resourceMetadataUrl:m,scope:h,error:f}=d9(s);if(f==="insufficient_scope"){const y=s.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===y)throw new xg(403,"Server returned 403 after trying upscoping");if(h&&(this._scope=h),m&&(this._resourceMetadataUrl=m),this._lastUpscopingHeader=y??void 0,await f_(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Su;return this.send(e)}}throw new xg(s.status,`Error POSTing to endpoint: ${this._unfollowedRedirect(s,this._url)??p}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,s.status===202){await s.body?.cancel(),Lbr(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(p=>this.onerror?.(p));return}const l=(Array.isArray(e)?e:[e]).filter(p=>"method"in p&&"id"in p&&p.id!==void 0).length>0,u=s.headers.get("content-type"),d=h5n(u);if(l)if(d==="text/event-stream")this._handleSseStream(s.body,{onresumptiontoken:n},!1);else if(d==="application/json"){const p=await s.json(),m=Array.isArray(p)?p.map(h=>n_.parse(h)):[n_.parse(p)];for(const h of m)this.onmessage?.(h)}else throw await s.body?.cancel(),new xg(-1,`Unexpected content type: ${u}`);else await s.body?.cancel()}catch(r){throw this.onerror?.(r),r}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{const e=await this._commonHeaders(),t={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},r=await p_(this._fetch??fetch)(this._url,t);if(await r.body?.cancel(),!r.ok&&r.status!==405)throw new xg(r.status,`Failed to terminate session: ${this._unfollowedRedirect(r,this._url)??r.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}}}}),tkr={};ae(tkr,{MCPClientFactory:()=>Ig,terminateLiveStdioServers:()=>g9});var rkr,Lye,nkr,$ye,h9,f9,Fye,Uye,Bye,g9,okr,ikr,Ig,zye=E({"src/lib/mcp/mcpClientFactory.ts"(){"use strict";G(),S0e(),ft(),abr(),cbr(),pbr(),gbr(),wo(),xy(),rkr=Math.max(5e3,Number(process.env.MCP_CLIENT_TIMEOUT)||6e4),Lye=20,nkr=class{lines=[];partial="";append(e){this.partial+=e.toString();const t=this.partial.split(/\r?\n/);this.partial=t.pop()??"";for(const r of t)r.trim().length!==0&&(this.lines.push(r),this.lines.length>Lye&&this.lines.shift())}snapshot(){const e=[...this.lines];return this.partial.trim().length>0&&e.push(this.partial),e.slice(-Lye)}},$ye=new WeakMap,h9=new Set,f9=new Set,Fye=!1,Bye=(e,t)=>{const r=Reflect.get(e,"_process");return r instanceof t?r:void 0},g9=()=>{for(const e of h9){const t=Uye&&Bye(e,Uye);try{t?t.kill("SIGTERM"):"pid"in e&&typeof e.pid=="number"&&process.kill(e.pid,"SIGTERM")}catch{}}for(const e of f9)try{e.kill("SIGKILL")}catch{}},okr=(e,t)=>{const r=Bye(e,t);if(!r||r.exitCode!==null||r.signalCode!==null)return;f9.add(r);const n=()=>{f9.delete(r)};r.once("exit",n),r.once("close",n)},ikr=(e,t)=>{Fye||(Fye=!0,process.on("exit",g9)),Uye=t,h9.add(e),e.onclose=()=>{h9.delete(e)};const r=e.close.bind(e);e.close=async()=>{okr(e,t),await r()}},Ig=class{static NEUROLINK_IMPLEMENTATION={name:"neurolink-sdk",version:"1.0.0"};static DEFAULT_CAPABILITIES={roots:{listChanged:!1}};static async createClient(e,t=rkr){const r=e.httpOptions?.connectionTimeout;r!==void 0&&(t=Math.min(t,r));const n=Date.now(),{traceId:o,parentSpanId:i}=Cy(),s=Oe.createSpan("mcp.transport","mcp.connect",{"mcp.transport":e.transport,"mcp.operation":"connect","mcp.server_id":e.id},i,o);try{le.info(`[MCPClientFactory] Creating client for ${e.id}`,{transport:e.transport,command:e.command,hasRetryConfig:!!e.retryConfig,hasRateLimiting:!!e.rateLimiting,hasAuth:!!e.auth}),(e.transport==="http"||e.transport==="sse")&&e.rateLimiting&&(await x0e.getLimiter(e.id,{requestsPerWindow:e.rateLimiting.requestsPerMinute??60,windowMs:6e4,maxBurst:e.rateLimiting.maxBurst??10,useTokenBucket:e.rateLimiting.useTokenBucket??!0,refillRate:(e.rateLimiting.requestsPerMinute??60)/60}).acquire(),le.debug(`[MCPClientFactory] Rate limit token acquired for ${e.id}`));const a=O4.getBreaker(`mcp-client-${e.id}`,{failureThreshold:3,resetTimeout:3e4,operationTimeout:t}),c=async()=>await a.execute(async()=>await this.createClientInternal(e,t));let l;(e.transport==="http"||e.transport==="sse")&&e.retryConfig?(le.debug(`[MCPClientFactory] Using retry logic for ${e.id}`,{maxAttempts:e.retryConfig.maxAttempts??Jp.maxAttempts}),l=await sbr(c,{maxAttempts:e.retryConfig.maxAttempts??Jp.maxAttempts,initialDelay:e.retryConfig.initialDelay??Jp.initialDelay,maxDelay:e.retryConfig.maxDelay??Jp.maxDelay,backoffMultiplier:e.retryConfig.backoffMultiplier??Jp.backoffMultiplier})):l=await c(),le.info(`[MCPClientFactory] Client created successfully for ${e.id}`,{duration:Date.now()-n,capabilities:l.capabilities}),s.durationMs=Date.now()-n;const u=Oe.endSpan(s,1);return pt().recordSpan(u),{...l,success:!0,duration:Date.now()-n}}catch(a){const c=a instanceof Error?a.message:String(a);if(a instanceof ef){le.warn(`[MCPClientFactory] Client creation blocked by circuit breaker for ${e.id}`,{serverId:e.id,breakerState:a.breakerState,retryAfter:a.retryAfter,retryAfterMs:a.retryAfterMs,failureCount:a.failureCount}),s.durationMs=Date.now()-n;const u=Oe.endSpan(s,2);return u.statusMessage=`Circuit breaker open: ${c}`,pt().recordSpan(u),{success:!1,error:c,duration:Date.now()-n}}le.debug(`[MCPClientFactory] Failed to create client for ${e.id}:`,a),s.durationMs=Date.now()-n;const l=Oe.endSpan(s,2);return l.statusMessage=c,pt().recordSpan(l),{success:!1,error:c,duration:Date.now()-n}}}static async createClientInternal(e,t){const n=(await this.createTransport(e)).transport;try{const{Client:o}=await Promise.resolve().then(()=>(w$n(),aEr)),i=new o(this.NEUROLINK_IMPLEMENTATION,{capabilities:this.DEFAULT_CAPABILITIES}),s=e.httpOptions?.requestTimeout;if(s!==void 0){const c=i.request.bind(i);i.request=(l,u,d)=>c(l,u,{...d,timeout:Math.min(s,d?.timeout??s),maxTotalTimeout:Math.min(s,d?.maxTotalTimeout??s)})}await this.raceWithTimeout(i.connect(n,{timeout:t}),t,`Client connection timeout for ${e.id}`);const a=await this.performHandshake(i,t);return le.debug(`[MCPClientFactory] Handshake completed for ${e.id}`,{capabilities:a}),{client:i,transport:n,capabilities:a}}catch(o){try{await n.close()}catch(s){le.debug("[MCPClientFactory] Error closing transport during cleanup:",s)}const i=this.getStderrTail(n);throw o instanceof Error&&i.length>0?new Error(`${o.message}
1254
1254
  Server stderr (last ${i.length} lines):
1255
1255
  ${i.join(`
1256
- `)}`,{cause:o}):o}}static getStderrTail(e){return $ye.get(e)?.snapshot()??[]}static async createTransport(e){switch(e.transport){case"stdio":return this.createStdioTransport(e);case"sse":return await this.assertNetworkUrlAllowed(e),this.createSSETransport(e);case"websocket":return await this.assertNetworkUrlAllowed(e),this.createWebSocketTransport(e);case"http":return await this.assertNetworkUrlAllowed(e),this.createHTTPTransport(e);default:throw new Error(`Unsupported transport type: ${e.transport}`)}}static async assertNetworkUrlAllowed(e){if(!e.url)throw new Error(`URL is required for ${e.transport} transport`);await mbr(e.url,{transport:e.transport,allowPrivateNetwork:e.allowPrivateNetwork,hostOwnedEgress:typeof e.fetch=="function",serverId:e.id})}static async createStdioTransport(e){if(le.debug(`[MCPClientFactory] Creating stdio transport for ${e.id}`,{command:e.command,args:e.args}),!e.command)throw new Error("Command is required for stdio transport");const{StdioClientTransport:t,getDefaultEnvironment:r}=await Promise.resolve().then(()=>(hSr(),cye)),{ChildProcess:n}=await Promise.resolve().then(()=>(ad(),yT)),o=e.inheritParentEnv===!0?{...process.env}:r(),i=new t({command:e.command,args:e.args||[],env:Object.fromEntries(Object.entries({...o,...e.env}).filter(([,a])=>a!==void 0).map(([a,c])=>[a,String(c)])),cwd:e.cwd,stderr:"pipe"});ikr(i,n);const s=new nkr;return $ye.set(i,s),i.stderr?.on("data",a=>{if(s.append(a),le.shouldLog("debug")){const c=a.toString().trim();c.length>0&&le.debug(`[MCPClientFactory] ${e.id} stderr:`,c)}}),{transport:i}}static async createSSETransport(e){if(!e.url)throw new Error("URL is required for SSE transport");le.debug(`[MCPClientFactory] Creating SSE transport for ${e.id}`,{url:e.url});try{const t=new URL(e.url),{SSEClientTransport:r}=await Promise.resolve().then(()=>(d5n(),VSr)),n=this.createEnhancedFetch(e,e.httpOptions?.requestTimeout??6e4);return{transport:new r(t,{requestInit:{headers:e.headers},fetch:n,eventSourceInit:{fetch:n}})}}catch(t){throw new Error(`Invalid SSE URL: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}static async createWebSocketTransport(e){if(!e.url)throw new Error("URL is required for WebSocket transport");le.debug(`[MCPClientFactory] Creating WebSocket transport for ${e.id}`,{url:e.url});const t=Object.keys(e.headers??{}).length;if(t>0||e.auth!==void 0)throw new Error(`WebSocket transport for ${e.id} cannot send the configured ${t>0?"headers":"auth"}: the WebSocket handshake carries no custom headers. Use the "http" or "sse" transport for an authenticated server, or remove the credentials.`);let r,n;try{r=new URL(e.url),n=await Promise.resolve().then(()=>(p5n(),WSr))}catch(a){throw new Error(`Invalid WebSocket URL: ${a instanceof Error?a.message:String(a)}`,{cause:a})}const o=new n.WebSocketClientTransport(r),i=e.httpOptions?.connectionTimeout??3e4,s=o.start.bind(o);return o.start=async()=>{try{await this.raceWithTimeout(s(),i,`WebSocket connection timeout for ${e.id} after ${i}ms`)}catch(a){throw await o.close().catch(()=>{}),a}},{transport:o}}static async createHTTPTransport(e){if(!e.url)throw new Error("URL is required for HTTP transport");const t={connectionTimeout:e.httpOptions?.connectionTimeout??3e4,requestTimeout:e.httpOptions?.requestTimeout??6e4,idleTimeout:e.httpOptions?.idleTimeout??12e4,keepAliveTimeout:e.httpOptions?.keepAliveTimeout??3e4};le.debug(`[MCPClientFactory] Creating HTTP transport for ${e.id}`,{url:e.url,hasHeaders:!!e.headers,hasAuth:!!e.auth,authType:e.auth?.type,httpOptions:t});try{const r=new URL(e.url),n=await this.setupAuthProvider(e),o={...e.headers??{}};if(e.auth){const l=await this.getAuthorizationHeader(e,n);l&&(o.Authorization=l)}const i=this.createEnhancedFetch(e,t.requestTimeout,n),s={headers:Object.keys(o).length>0?o:void 0},{StreamableHTTPClientTransport:a}=await Promise.resolve().then(()=>(y5n(),ZSr));return{transport:new a(r,{requestInit:s,fetch:i})}}catch(r){throw new Error(`Invalid HTTP URL: ${r instanceof Error?r.message:String(r)}`,{cause:r})}}static createFetchWithTimeout(e,t){return async(r,n)=>{const o=new AbortController,i=setTimeout(()=>o.abort(),e);try{const s=await t(r,{...n,redirect:"manual",signal:n?.signal?AbortSignal.any([o.signal,n.signal]):o.signal});if(s.status>=300&&s.status<400)throw await s.body?.cancel(),new Error("MCP transport redirects are not permitted");return s}finally{clearTimeout(i)}}}static createEnhancedFetch(e,t,r){const n=this.createFetchWithTimeout(t,e.fetch??globalThis.fetch);return async(o,i)=>{if(r&&e.auth?.type==="oauth2")try{const s=await r.getAuthorizationHeader(e.id);if(s){const a=i?.headers??{},c=new Headers(a);c.set("Authorization",s),i={...i,headers:c}}}catch(s){le.warn(`[MCPClientFactory] OAuth token refresh failed for ${e.id}:`,s instanceof Error?s.message:String(s))}return n(o,i)}}static async setupAuthProvider(e){if(e.auth?.type==="oauth2"&&e.auth.oauth){const t=new EB,r={clientId:e.auth.oauth.clientId,clientSecret:e.auth.oauth.clientSecret,authorizationUrl:e.auth.oauth.authorizationUrl,tokenUrl:e.auth.oauth.tokenUrl,redirectUrl:e.auth.oauth.redirectUrl,scope:e.auth.oauth.scope,usePKCE:e.auth.oauth.usePKCE??!0},n=new SB(r,t);return le.debug(`[MCPClientFactory] OAuth provider created for ${e.id}`,{clientId:r.clientId,usePKCE:r.usePKCE}),n}}static async getAuthorizationHeader(e,t){if(e.auth)switch(e.auth.type){case"oauth2":return t?await t.getAuthorizationHeader(e.id)??void 0:void 0;case"bearer":return e.auth.token?`Bearer ${e.auth.token}`:void 0;case"api-key":return;default:return}}static async performHandshake(e,t){try{const r=await this.raceWithTimeout(this.getServerInfo(e),t,"Handshake timeout");return this.extractCapabilities(r)}catch(r){return le.warn("[MCPClientFactory] Handshake failed, but connection may still be valid:",r),this.DEFAULT_CAPABILITIES}}static async getServerInfo(e){try{return{tools:(await e.listTools()).tools||[],capabilities:this.DEFAULT_CAPABILITIES}}catch{return le.debug("[MCPClientFactory] Tool listing failed, server may not support tools yet"),{tools:[],capabilities:this.DEFAULT_CAPABILITIES}}}static extractCapabilities(e){return{...this.DEFAULT_CAPABILITIES,...e.tools?{tools:{}}:{}}}static async raceWithTimeout(e,t,r,n){let o,i;const s=new Promise((a,c)=>{o=setTimeout(()=>{c(new Error(r))},t),n&&(i=()=>{clearTimeout(o),c(new Error(`Operation aborted: ${r}`))},n.addEventListener("abort",i))});try{return await Promise.race([e,s])}finally{clearTimeout(o),n&&i&&n.removeEventListener("abort",i)}}static async closeClient(e,t,r){const n=[];try{await e.close()}catch(o){n.push(`Client close error: ${o instanceof Error?o.message:String(o)}`)}try{await t.close()}catch(o){n.push(`Transport close error: ${o instanceof Error?o.message:String(o)}`)}if(r&&!r.killed)try{r.kill("SIGTERM"),await new Promise(o=>{const i=setTimeout(()=>{if(!r.killed){le.warn("[MCPClientFactory] Force killing process");try{r.kill("SIGKILL")}catch(s){le.debug("[MCPClientFactory] Error in force kill:",s)}}o()},5e3);r.on("exit",()=>{clearTimeout(i),o()})})}catch(o){n.push(`Process kill error: ${o instanceof Error?o.message:String(o)}`)}n.length>0&&le.warn("[MCPClientFactory] Errors during client cleanup:",n)}static async testConnection(e,t=5e3){let r,n,o;try{const i=await this.createClient(e,t);if(!i.success)return{success:!1,error:i.error};if(r=i.client,n=i.transport,o=i.process,r)try{await r.listTools()}catch{le.debug("[MCPClientFactory] Tool listing failed during test, but connection may be valid")}return{success:!0,capabilities:i.capabilities}}catch(i){return{success:!1,error:i instanceof Error?i.message:String(i)}}finally{if(r&&n)try{await this.closeClient(r,n,o)}catch(i){le.debug("[MCPClientFactory] Error cleaning up test connection:",i)}}}static validateClientConfig(e){const t=[];if(e.command||t.push("Command is required"),e.transport||t.push("Transport is required"),["stdio","sse","websocket","http"].includes(e.transport)||t.push("Transport must be stdio, sse, websocket, or http"),e.transport==="sse"||e.transport==="websocket"||e.transport==="http")if(!e.url)t.push(`URL is required for ${e.transport} transport`);else try{new URL(e.url)}catch{t.push(`Invalid URL for ${e.transport} transport`)}return e.transport==="stdio"&&(Array.isArray(e.args)||t.push("Args array is required for stdio transport")),{isValid:t.length===0,errors:t}}static getSupportedTransports(){return["stdio","sse","websocket","http"]}static getDefaultCapabilities(){return{...this.DEFAULT_CAPABILITIES}}}}});function skr(e,t){if(t<=0)return"";try{const r=JSON.stringify(e);return typeof r!="string"?"":r.length<=t?r:r.slice(0,Math.max(0,t-1))+"\u2026"}catch{return""}}function y9(e,t=0){if(t>10)return"[...]";if(e==null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>y9(n,t+1));const r={};for(const[n,o]of Object.entries(e))ckr.test(n)?r[n]="[REDACTED]":r[n]=y9(o,t+1);return r}var akr,ckr,qye,lkr,v5n=E({"src/lib/mcp/toolDiscoveryService.ts"(){"use strict";To(),G(),S0e(),Nm(),oh(),st(),tge(),_ue(),Gt(),gr(),qr(),akr=We.mcp,ckr=/^(password|passwd|secret|token|api[_-]?key|apikey|access[_-]?key|authorization|auth|bearer|credential|cookie|session[_-]?id|private[_-]?key|client[_-]?secret|refresh[_-]?token|x-api-key)$/i,qye=Math.max(5e3,Number(process.env.MCP_TOOL_TIMEOUT)||6e4),lkr=class extends On{serverToolStorage=new Map;toolRegistry=new Map;serverTools=new Map;discoveryInProgress=new Set;outputNormalizer;constructor(){super()}setOutputNormalizer(e){this.outputNormalizer=e}async discoverTools(e,t,r=qye,n=()=>!0,o=!1){return wt({name:"mcp.discoverTools",tracer:We.mcp,attributes:{"mcp.server_id":e}},async i=>{const s=Date.now();let a=!1;try{if(!n())throw new Error(`Discovery owner for '${e}' is no longer current`);if(this.discoveryInProgress.has(e))return{success:!1,error:`Discovery already in progress for server: ${e}`,toolCount:0,tools:[],duration:Date.now()-s,serverId:e};this.discoveryInProgress.add(e),a=!0,le.info(`[ToolDiscoveryService] Starting tool discovery for server: ${e}`);const c=()=>this.performToolDiscovery(e,t,r),l=o?await c():await O4.getBreaker(`tool-discovery-${e}`,{failureThreshold:2,resetTimeout:6e4,operationTimeout:r}).execute(c),u=await this.registerDiscoveredTools(e,l,n);i.setAttribute("mcp.tools_discovered",u.length);const d={success:!0,toolCount:u.length,tools:u,duration:Date.now()-s,serverId:e};return this.emit("discoveryCompleted",{serverId:e,toolCount:u.length,duration:d.duration,timestamp:new Date}),le.info(`[ToolDiscoveryService] Discovery completed for ${e}: ${u.length} tools`),d}catch(c){const l=c instanceof Error?c.message:String(c);return i.setStatus({code:Ve.ERROR,message:l}),i.recordException(c instanceof Error?c:new Error(l)),le.error(`[ToolDiscoveryService] Discovery failed for ${e}:`,c),this.emit("discoveryFailed",{serverId:e,error:l,timestamp:new Date}),{success:!1,error:l,toolCount:0,tools:[],duration:Date.now()-s,serverId:e}}finally{a&&this.discoveryInProgress.delete(e)}})}async performToolDiscovery(e,t,r){const n=await this.raceWithTimeout(t.listTools(),r,"Tool discovery timeout");if(!n||!n.tools)throw new Error("No tools returned from server");return le.debug(`[ToolDiscoveryService] Discovered ${n.tools.length} tools from ${e}`),n.tools}async registerDiscoveredTools(e,t,r){const n=[];if(!r())throw new Error(`Discovery owner for '${e}' is no longer current`);this.clearServerTools(e);for(const o of t)try{const i=await this.createToolInfo(e,o);if(!r())throw new Error(`Discovery owner for '${e}' is no longer current`);const s=this.validateTool(i);if(!s.isValid){le.warn(`[ToolDiscoveryService] Skipping invalid tool ${o.name} from ${e}:`,s.errors);continue}s.metadata&&(i.metadata={...i.metadata,...s.metadata});const a=this.createToolKey(e,o.name);this.toolRegistry.set(a,i),this.serverToolStorage.has(e)||this.serverToolStorage.set(e,[]);const c=this.serverToolStorage.get(e);if(!c)throw new Error(`Server tools storage not found for ${e}`);c.find(u=>u.name===o.name)||c.push(i),this.serverTools.has(e)||this.serverTools.set(e,new Set);const l=this.serverTools.get(e);l&&l.add(o.name),n.push(i),this.emit("toolRegistered",{serverId:e,toolName:o.name,toolInfo:i,timestamp:new Date}),le.debug(`[ToolDiscoveryService] Registered tool: ${o.name} from ${e}`)}catch(i){if(!r())throw i;le.error(`[ToolDiscoveryService] Failed to register tool ${o.name} from ${e}:`,i)}if(!r())throw new Error(`Discovery owner for '${e}' is no longer current`);return n}async createToolInfo(e,t){return{name:t.name,description:t.description||"No description provided",serverId:e,inputSchema:t.inputSchema,...t.annotations?{annotations:{...t.annotations}}:{},isAvailable:!0,stats:{totalCalls:0,successfulCalls:0,failedCalls:0,averageExecutionTime:0,lastExecutionTime:0},metadata:{category:this.inferToolCategory(t),version:"1.0.0",deprecated:!1}}}inferToolCategory(e){const t=e.name.toLowerCase(),r=(e.description||"").toLowerCase();return t.includes("git")||r.includes("git")?"version-control":t.includes("file")||t.includes("read")||t.includes("write")?"file-system":t.includes("api")||t.includes("http")||t.includes("request")?"api":t.includes("data")||t.includes("query")||t.includes("search")?"data":t.includes("auth")||t.includes("login")||t.includes("token")?"authentication":t.includes("deploy")||t.includes("build")||t.includes("ci")?"deployment":"general"}validateTool(e){const t=[],r=[],n=h4(e.name);n&&t.push(n.message);const o=OU(e.description);if(o&&r.push(o.message),e.serverId||t.push("Server ID is required"),e.inputSchema)try{JSON.stringify(e.inputSchema)}catch{t.push("Input schema is not valid JSON")}const i={category:typeof e.metadata?.category=="string"?e.metadata.category:"general",complexity:this.inferComplexity(e),requiresAuth:this.inferAuthRequirement(e),isDeprecated:typeof e.metadata?.deprecated=="boolean"?e.metadata.deprecated:!1};return{isValid:t.length===0,errors:t,warnings:r,metadata:i}}inferComplexity(e){const t=e.inputSchema;if(!t||!t.properties)return"simple";const r=Object.keys(t.properties).length;return r<=2?"simple":r<=5?"moderate":"complex"}inferAuthRequirement(e){const t=e.name.toLowerCase(),r=e.description.toLowerCase();return t.includes("auth")||t.includes("login")||t.includes("token")||r.includes("authentication")||r.includes("credentials")||r.includes("permission")}async executeTool(e,t,r,n,o={}){const i=Date.now();try{const s=this.createToolKey(t,e),a=this.toolRegistry.get(s);if(!a)throw new Error(`Tool '${e}' not found for server '${t}'`);if(!a.isAvailable)throw new Error(`Tool '${e}' is not available`);let c=n;o.validateInput!==!1&&(c=this.validateToolParameters(a,n)),le.debug(`[ToolDiscoveryService] Executing tool: ${e} on ${t}`,{parameters:c});const l=o.timeout||qye,u=O4.getBreaker(`tool-execution-${t}-${e}`,{failureThreshold:3,resetTimeout:3e4,operationTimeout:l});let d=!1;const p=await u.execute(async h=>akr.startActiveSpan("mcp.callTool",{kind:un.CLIENT,attributes:{"mcp.server_id":t,"mcp.tool_name":e,"mcp.timeout_ms":l,"ai.tool.name":e,"mcp.request":skr({name:e,arguments:y9(c)},2048)}},async f=>{try{const y=l,v=await Je(r.callTool({name:e,arguments:c},void 0,{timeout:l,...o.signal&&{signal:o.signal}}),y,new Error(`Tool execution timeout: ${e}`)),_=v;if(_&&_.isError===!0){const k=CF(_);f.setStatus({code:Ve.ERROR,message:k||`Tool ${e} returned isError`}),d=!0,h(k||`Tool ${e} returned isError`)}else f.setStatus({code:Ve.OK});let w=v,T=v;if(this.outputNormalizer)try{const k=await this.outputNormalizer.normalize(v,{toolName:e,serverId:t});f.setAttribute("mcp.output.strategy",k.isExternalized?"externalize":"inline"),k.isExternalized&&f.setAttribute("mcp.output.original_bytes",k.originalBytes),w=k.result,T=k.result}catch(k){le.warn(`[ToolDiscoveryService] McpOutputNormalizer failed for ${e}: ${k instanceof Error?k.message:String(k)} \u2014 returning raw result`)}return f.setAttribute("mcp.response",skr(y9(w),2048)),T}catch(y){throw f.setStatus({code:Ve.ERROR,message:y.message}),f.recordException(y),y}finally{f.end()}})),m=Date.now()-i;return this.updateToolStats(s,!d,m),o.validateOutput!==!1&&this.validateToolOutput(p),le.debug(`[ToolDiscoveryService] Tool execution completed: ${e}`,{duration:m,hasContent:!!p?.content}),{success:!0,data:p,isErrorResult:d,duration:m,metadata:{toolName:e,serverId:t,timestamp:Date.now()}}}catch(s){const a=Date.now()-i,c=s instanceof Error?s.message:String(s),l=this.createToolKey(t,e);if(this.updateToolStats(l,!1,a),o.signal?.aborted)throw s;return s instanceof ef?(le.warn(`[ToolDiscoveryService] Tool blocked by circuit breaker: ${e} on ${t}`,{breakerState:s.breakerState,retryAfter:s.retryAfter,retryAfterMs:s.retryAfterMs,failureCount:s.failureCount}),{success:!1,error:s.message,data:{isError:!0,content:[{type:"text",text:`TOOL TEMPORARILY UNAVAILABLE: "${e}" has been disabled after ${s.failureCount} failures. This is a circuit breaker protection \u2014 do NOT retry this tool. It will become available again after ${Math.ceil(s.retryAfterMs/1e3)} seconds (at ${s.retryAfter}). Instead, inform the user that the operation failed and suggest trying again later.`}]},duration:a,metadata:{toolName:e,serverId:t,timestamp:Date.now(),circuitBreaker:{state:s.breakerState,retryAfter:s.retryAfter,retryAfterMs:s.retryAfterMs,failureCount:s.failureCount}}}):(le.error(`[ToolDiscoveryService] Tool execution failed: ${e}`,s),{success:!1,error:c,duration:a,metadata:{toolName:e,serverId:t,timestamp:Date.now()}})}}validateToolParameters(e,t){if(!e.inputSchema)return t;const r=e.inputSchema,n=r.properties&&typeof r.properties=="object"?r.properties:{},o=Array.isArray(r.required)?r.required.filter(c=>typeof c=="string"):[],i=()=>Object.entries(n).map(([c,l])=>`${c}${o.includes(c)?"":"?"}: ${l.type??"any"}`).join(", "),s=o.filter(c=>!(c in t));if(s.length>0)throw new Error(`Missing required parameter${s.length>1?"s":""}: ${s.join(", ")}. Expected arguments: { ${i()} }; received keys: [${Object.keys(t).join(", ")}]`);let a;for(const[c,l]of Object.entries(n))if(c in t){const u=t[c],d=Qfe(u,l);d!==u&&(le.debug(`[ToolDiscoveryService] Coerced parameter '${c}' for tool '${e.name}': ${typeof u} \u2192 ${typeof d}`),a=a??{...t},a[c]=d),this.validateParameterType(c,a?a[c]:u,l)}return a??t}validateParameterType(e,t,r){if(!r.type)return;const n=r.type,o=typeof t;switch(n){case"string":if(o!=="string")throw new Error(`Parameter '${e}' must be a string, got ${o}`);break;case"number":if(o!=="number")throw new Error(`Parameter '${e}' must be a number, got ${o}`);break;case"integer":if(o!=="number"||!Number.isInteger(t))throw new Error(`Parameter '${e}' must be an integer, got ${o==="number"?String(t):o}`);break;case"boolean":if(o!=="boolean")throw new Error(`Parameter '${e}' must be a boolean, got ${o}`);break;case"array":if(!Array.isArray(t))throw new Error(`Parameter '${e}' must be an array, got ${o}`);break;case"object":if(o!=="object"||t===null||Array.isArray(t))throw new Error(`Parameter '${e}' must be an object, got ${o}`);break}}validateToolOutput(e){if(Ymn(e)){le.debug("[ToolDiscoveryService] Tool returned null/undefined, treating as empty response");return}le.debug("[ToolDiscoveryService] Tool response received",{type:typeof e,isArray:Array.isArray(e),isObject:b3(e),hasKeys:b3(e)?Object.keys(e).length:0,fullResponse:e})}updateToolStats(e,t,r){const n=this.toolRegistry.get(e);if(!n)return;n.stats.totalCalls++,n.lastCalled=new Date,n.stats.lastExecutionTime=r,t?n.stats.successfulCalls++:n.stats.failedCalls++;const o=n.stats.averageExecutionTime*(n.stats.totalCalls-1)+r;n.stats.averageExecutionTime=o/n.stats.totalCalls}getTool(e,t){const r=this.createToolKey(t,e);return this.toolRegistry.get(r)}getServerTools(e){const t=this.serverToolStorage.get(e);if(t)return t.map(o=>({name:o.name,description:o.description,serverId:e,inputSchema:o.inputSchema,...o.annotations?{annotations:{...o.annotations}}:{},isAvailable:!0,stats:{totalCalls:0,successfulCalls:0,failedCalls:0,averageExecutionTime:0,lastExecutionTime:0}}));const r=[],n=this.serverTools.get(e);if(n)for(const o of n){const i=this.createToolKey(e,o),s=this.toolRegistry.get(i);s&&r.push(s)}return r}getAllTools(){const e=[];for(const[r,n]of this.serverToolStorage.entries())for(const o of n)e.push({name:o.name,description:o.description,serverId:r,inputSchema:o.inputSchema,...o.annotations?{annotations:{...o.annotations}}:{},isAvailable:!0,stats:{totalCalls:0,successfulCalls:0,failedCalls:0,averageExecutionTime:0,lastExecutionTime:0}});const t=Array.from(this.toolRegistry.values()).filter(r=>!e.some(n=>n.name===r.name&&n.serverId===r.serverId));return[...e,...t]}clearServerTools(e){const t=this.serverToolStorage.get(e);if(t){for(const n of t)this.emit("toolUnregistered",{serverId:e,toolName:n.name,timestamp:new Date});this.serverToolStorage.delete(e)}const r=this.serverTools.get(e);if(r){for(const n of r){const o=this.createToolKey(e,n);this.toolRegistry.delete(o),(!t||!t.find(i=>i.name===n))&&this.emit("toolUnregistered",{serverId:e,toolName:n,timestamp:new Date})}this.serverTools.delete(e)}le.debug(`[ToolDiscoveryService] Cleared tools for server: ${e}`)}updateToolAvailability(e,t,r){const n=this.createToolKey(t,e),o=this.toolRegistry.get(n);o&&(o.isAvailable=r,le.debug(`[ToolDiscoveryService] Updated availability for ${e}: ${r}`))}createToolKey(e,t){return`${e}:${t}`}async raceWithTimeout(e,t,r){let n;const o=new Promise((i,s)=>{n=setTimeout(()=>{s(new Error(r))},t)});try{return await Promise.race([e,o])}finally{clearTimeout(n)}}destroy(){le.debug("[ToolDiscoveryService] Starting cleanup..."),this.removeAllListeners(),this.serverToolStorage.clear(),this.toolRegistry.clear(),this.serverTools.clear(),this.discoveryInProgress.clear(),le.debug("[ToolDiscoveryService] Destroyed and cleaned up")}resetStatistics(){for(const e of this.toolRegistry.values())e.stats={totalCalls:0,successfulCalls:0,failedCalls:0,averageExecutionTime:0,lastExecutionTime:0},e.lastCalled=void 0;le.debug("[ToolDiscoveryService] Statistics reset for all tools")}getListenerCount(){const e=["discoveryCompleted","discoveryFailed","toolRegistered","toolUnregistered"];let t=0;for(const r of e)t+=this.listenerCount(r);return t}getStatistics(){const e={},t={};let r=0,n=0;for(const o of this.toolRegistry.values()){e[o.serverId]=(e[o.serverId]||0)+1;const i=typeof o.metadata?.category=="string"?o.metadata.category:"unknown";t[i]=(t[i]||0)+1,o.isAvailable?r++:n++}return{totalTools:this.toolRegistry.size,availableTools:r,unavailableTools:n,totalServers:this.serverTools.size,toolsByServer:e,toolsByCategory:t}}}}}),ukr,_5n=E({"src/lib/mcp/registry.ts"(){"use strict";G(),ukr=class{plugins=new Map;register(e){this.plugins.set(e.metadata.name,e),Vr.debug(`Registered plugin: ${e.metadata.name}`)}unregister(e){const t=this.plugins.delete(e);return t&&Vr.debug(`Unregistered plugin: ${e}`),t}get(e){return this.plugins.get(e)}list(){return Array.from(this.plugins.values())}has(e){return this.plugins.has(e)}clear(){this.plugins.clear(),Vr.info("Registry cleared")}async registerServer(e,t,r){const n={metadata:{name:e,description:typeof t=="object"&&t&&t.description||"No description"},tools:typeof t=="object"&&t?t.tools:{},configuration:typeof t=="object"&&t?t:{}};this.register(n)}async executeTool(e,t,r){return Vr.info(`Executing tool: ${e}`),{result:`Mock execution of ${e}`,args:t}}async listTools(e){return this.list().map(r=>({name:r.metadata.name,description:r.metadata.description||"No description",serverId:r.metadata.name,category:"general"}))}registerServerSync(e){this.register(e)}executeToolSync(e,t){return Vr.info(`Executing tool (sync): ${e}`),{result:`Mock execution of ${e}`,args:t}}listToolsSync(){return this.list().map(t=>({name:t.metadata.name,description:t.metadata.description||"No description"}))}listServers(){return Array.from(this.plugins.keys())}}}});function oc(e){return e.existingCategory&&["external","in-memory","built-in","user-defined"].includes(e.existingCategory)?e.existingCategory:e.isCustomTool?"user-defined":e.isBuiltIn?"built-in":e.isExternal?"external":e.serverId?.startsWith("custom-tool-")?"user-defined":e.serverId?.includes("external")?"external":e.serverId==="direct"?"built-in":"in-memory"}function w5n(e,t){switch(t){case"external":return`External MCP server: ${e}`;case"built-in":return`Built-in tool server: ${e}`;case"custom":case"user-defined":return`Custom tool server: ${e}`;case"in-memory":return`In-memory MCP server: ${e}`;default:return e}}function dkr(e){const t=e.id||`server-${e.name}`,r=e.category||oc({isCustomTool:e.isCustomTool,isExternal:e.isExternal,isBuiltIn:e.isBuiltIn,serverId:t}),n=e.tools||(e.tool?[e.tool]:[]);return{id:t,name:e.name,transport:e.transport||"stdio",status:e.status||"connected",tools:n,description:e.description||w5n(e.name,r),...e.command&&{command:e.command},...e.args&&{args:e.args},...e.env&&{env:e.env},metadata:{category:r,toolCount:n.length}}}function b5n(e,t,r,n,o){const i=dkr({id:`custom-tool-${e}`,name:e,tool:{name:e,description:t.description||e,inputSchema:t.inputSchema||{},execute:t.execute},isCustomTool:!0});return i.metadata&&(r!==void 0&&(i.metadata.toolTimeoutMs=r),n!==void 0&&(i.metadata.toolMaxRetries=n),o!==void 0&&(i.metadata.toolTotalTimeoutMs=o)),i}var Gye=E({"src/lib/utils/mcpDefaults.ts"(){"use strict"}}),pkr,T5n=E({"src/lib/mcp/flexibleToolValidator.ts"(){"use strict";G(),pkr=class{static MAX_TOOL_NAME_LENGTH=1e3;static MIN_TOOL_NAME_LENGTH=1;static validateToolName(e){const t=[];if(!e||typeof e!="string")return{isValid:!1,error:"Tool name is required and must be a string"};if(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/.test(e))return{isValid:!1,error:"Tool name contains control characters that could break systems"};const n=e.trim();return n.length===0?{isValid:!1,error:"Tool name cannot be empty or whitespace-only"}:n.length<this.MIN_TOOL_NAME_LENGTH?{isValid:!1,error:`Tool name must be at least ${this.MIN_TOOL_NAME_LENGTH} character long`}:n.length>this.MAX_TOOL_NAME_LENGTH?{isValid:!1,error:`Tool name exceeds maximum length of ${this.MAX_TOOL_NAME_LENGTH} characters`}:(n!==e&&t.push("Tool name has leading/trailing whitespace (will be trimmed)"),n.length>200&&t.push("Tool name is unusually long but allowed"),Vr.debug(`\u2705 FlexibleToolValidator: Tool '${e}' passed universal safety checks`),{isValid:!0,warnings:t.length>0?t:void 0})}static validateToolInfo(e,t){const r=this.validateToolName(e);if(!r.isValid)return r;const n=[...r.warnings||[]];return t.description&&typeof t.description!="string"?{isValid:!1,error:"Tool description must be a string if provided"}:t.serverId&&typeof t.serverId!="string"?{isValid:!1,error:"Tool serverId must be a string if provided"}:(Vr.debug(`\u2705 FlexibleToolValidator: Tool info for '${e}' passed validation`),{isValid:!0,warnings:n.length>0?n:void 0})}static getValidationInfo(){return{philosophy:"Maximum flexibility with universal safety only - following Anthropic's MCP specification",checks:["Empty or whitespace-only names","Excessive length (over 1000 characters)","Control characters that could break systems"],whatIsAllowed:["Dots (github.create_repo, filesystem.read_file)","Hyphens and underscores (my-tool, user_helper)","Numbers (tool1, my_tool_v2)","Unicode characters (\u{1F680}_tool, caf\xE9_manager)","Mixed case (createRepo, ReadFile)","Long descriptive names (enterprise_database_connection_manager)","Any legitimate MCP tool naming pattern"],examples:{valid:["github.create_repo","filesystem.read_file","my-custom-tool","user_helper","tool1","\u{1F680}_rocket_tool","enterprise.database.connection.manager","UPPERCASE_TOOL","mixed_Case.Tool-Name_123"],invalid:[""," ","tool\0","a".repeat(1001)]}}}}}}),v9,jye,Vye=E({"src/lib/mcp/toolRegistry.ts"(){"use strict";_5n(),G(),tr(),S3(),yL(),Vte(),Ps(),Gye(),T5n(),st(),wb(),_T(),pu(),Gt(),lS(),v9=class extends ukr{tools=new Map;toolImplementations=new Map;toolExecutionStats=new Map;builtInServerInfos=[];hitlManager;unbatchableTools=new Set;fileToolRootResolver=()=>vL({});constructor(){super(),oZ()||this.registerDirectTools()}setHITLManager(e){this.hitlManager=e,e&&e.isEnabled()?Vr.info("HITL safety mechanisms enabled for tool execution"):Vr.debug("HITL safety mechanisms disabled or not configured")}getHITLManager(){return this.hitlManager}setToolUnbatchable(e,t){t?this.unbatchableTools.add(e):this.unbatchableTools.delete(e)}isToolUnbatchable(e){return this.unbatchableTools.has(e)}setFileToolRootResolver(e){this.fileToolRootResolver=e}directToolFor(e,t,r){const n=Gte(r)??this.fileToolRootResolver();return n.roots===null?t:Fte(n)[e]??t}registerDirectTools(){Vr.debug("Auto-registering direct tools...");for(const[e,t]of Object.entries(Kb)){if(!t){Vr.warn(`Skipping undefined tool during registration: ${e}`);continue}const r=`direct.${e}`,n=$i(t.inputSchema),o={name:e,description:t.description||`Direct tool: ${e}`,inputSchema:n,serverId:"direct",category:oc({isBuiltIn:!0,serverId:"direct"})};this.tools.set(r,o),this.toolImplementations.set(r,{execute:async(i,s)=>{try{return{success:!0,data:await this.directToolFor(e,t,s).execute(i,{toolCallId:s?.sessionId||"unknown",messages:[]}),metadata:{toolName:e,serverId:"direct",executionTime:0}}}catch(a){return{success:!1,error:a instanceof Error?a.message:String(a),metadata:{toolName:e,serverId:"direct",executionTime:0}}}},description:t.description,inputSchema:n}),Vr.debug(`Registered direct tool: ${e} as ${r}`)}Vr.debug(`Auto-registered ${Object.keys(Kb).length} direct tools`)}async registerServer(e,t,r){let n;if(typeof e=="string"){const c=e;n=dkr({id:c,name:c,tools:[],isExternal:!0})}else n=e;const o=n.id,i={};for(const c of n.tools)i[c.name]={execute:c.execute||(async()=>{throw new Error(`Tool ${c.name} has no execute function`)}),description:c.description,inputSchema:c.inputSchema,category:oc({existingCategory:n.metadata?.category,serverId:n.id})};const s={metadata:{name:n.name,description:n.description,category:oc({existingCategory:n.metadata?.category,serverId:n.id})},tools:i,configuration:{}};this.plugins.set(o,s),Vr.debug(`Registered plugin: ${s.metadata.name}`);const a=n.tools;for(const c of a){const u=o.startsWith("custom-tool-")?c.name:`${o}.${c.name}`,d=n.metadata?.toolTimeoutMs,p=n.metadata?.toolMaxRetries,m=n.metadata?.toolTotalTimeoutMs,h={name:c.name,description:c.description,inputSchema:c.inputSchema,outputSchema:void 0,serverId:o,category:oc({existingCategory:n.metadata?.category,serverId:n.id}),permissions:[],...d!==void 0&&{timeoutMs:d},...p!==void 0&&{maxRetries:p},...m!==void 0&&{totalTimeoutMs:m}};this.tools.set(u,h),this.toolImplementations.set(u,{execute:c.execute||(async()=>{throw new Error(`Tool ${c.name} has no execute function`)}),description:c.description,inputSchema:c.inputSchema,category:oc({existingCategory:n.metadata?.category,serverId:n.id}),...d!==void 0&&{timeoutMs:d},...p!==void 0&&{maxRetries:p},...m!==void 0&&{totalTimeoutMs:m}})}if(a.length>0){const c=oc({existingCategory:n.metadata?.category,serverId:n.id});c==="in-memory"&&(this.builtInServerInfos.push(n),Vr.debug(`Added ${c} server to builtInServerInfos: ${o} with ${a.length} tools`))}}async executeTool(e,t,r){const n=Date.now();let o;const i=this.tools.get(e);if(i)o=i.serverId;else for(const s of this.tools.values())if(s.name===e){o=s.serverId;break}return wt({name:"tool.registry.execute",tracer:We.mcp,attributes:{"tool.name":e,[Ge.MCP_SERVER_ID]:o||"builtin",[Ge.NL_INTERNAL]:!0}},async s=>{try{Vr.info(`\u{1F527} [TOOL_EXECUTION] Starting execution: ${e}`,{hasArgs:t!==void 0,hasContext:r!==void 0,sessionId:r?.sessionId});const{tool:a,toolId:c}=this.resolveToolExecutionTarget(e);if(!a)throw new Error(`Tool '${e}' not found in registry`);const l=a.serverId||"unknown",u=l==="direct"?"builtin":l.startsWith("custom-tool-")?"custom":"mcp";s.setAttribute("tool.type",u),s.setAttribute(Ge.MCP_SERVER_ID,l);const d=this.createExecutionContext(r),p=this.toolImplementations.get(c);if(Vr.debug(`Looking for tool '${e}' (toolId: '${c}'), found: ${!!p}, type: ${typeof p?.execute}`),Vr.debug("Available tools:",Array.from(this.toolImplementations.keys())),!p||typeof p?.execute!="function")throw new Error(`Tool '${e}' implementation not found or not executable`);let m;try{m=JSON.stringify(t).slice(0,4096)}catch{m="[unserializable]"}s.setAttribute("tool.arguments_present",t!==void 0),s.setAttribute("tool.arguments_size",m.length);const h=await this.confirmToolCall(e,t,a.serverId,d,s);G0(d.abortSignal),Vr.debug(`Executing tool '${e}' with args:`,h);const f=await p.execute(h,d);let y;if(f&&typeof f=="object"&&"success"in f&&typeof f.success=="boolean"){const w=f;y={...w,usage:{...w.usage||{},executionTime:Date.now()-n},metadata:{...w.metadata||{},toolName:e,serverId:a.serverId,sessionId:d.sessionId,executionTime:Date.now()-n}},nI(f)&&rI(y)}else y={success:!0,data:f,usage:{executionTime:Date.now()-n},metadata:{toolName:e,serverId:a.serverId,sessionId:d.sessionId,executionTime:Date.now()-n}};const v=Date.now()-n;this.updateStats(e,v);let _;try{_=JSON.stringify(y.data)??"undefined"}catch{_="[unserializable]"}return s.setAttribute("tool.result_length",_.length),s.setAttribute("tool.success",!0),Vr.debug(`Tool '${e}' executed successfully in ${v}ms`),y}catch(a){a instanceof nu?Vr.info(`Tool '${e}' refused by its HITL confirmation: ${a.message}`):cr(a)?Vr.info(`Tool '${e}' stopped by its signal`):Vr.error(`Tool execution failed: ${e}`,a),s.setAttribute("tool.success",!1);const c=a instanceof Error?a.message:String(a);if(c.includes("not found in registry")||c.includes("not executable"))throw a;s.setStatus({code:Ve.ERROR,message:c}),a instanceof Error&&s.recordException(a);const l={success:!1,data:null,error:a instanceof Error?a.message:String(a),usage:{executionTime:Date.now()-n},metadata:{toolName:e,sessionId:r?.sessionId}};return a instanceof nu?rI(l):l}})}async listTools(e){const t=new Map;for(const o of this.tools.values()){const i=`${o.serverId||"unknown"}.${o.name}`;t.has(i)||t.set(i,o)}let r=Array.from(t.values()),n;return e&&("sessionId"in e||"userId"in e?n=void 0:n=e),n&&(n.category&&(r=r.filter(o=>o.category===n.category)),n.serverId&&(r=r.filter(o=>o.serverId===n.serverId)),n.serverCategory&&(r=r.filter(o=>this.get(o.serverId||"")?.metadata?.category===n.serverCategory)),n.permissions&&n.permissions.length>0&&(r=r.filter(o=>{const i=o.permissions||[];return n.permissions?.some(s=>i.includes(s))??!1}))),Vr.debug(`Listed ${r.length} unique tools (${n?"filtered":"unfiltered"})`),r}resolveToolExecutionTarget(e){let t=this.tools.get(e);Vr.info(`\u{1F50D} [TOOL_LOOKUP] Direct lookup result for '${e}':`,!!t);let r=e;if(!t){const n=Array.from(this.tools.entries()).filter(([,o])=>o.name===e);if(n.length>1)throw Te.toolExecutionFailed(e,new Error(`Ambiguous tool name '${e}'. Use fully-qualified name 'serverId.${e}'.`));n.length===1&&([r,t]=n[0])}return{tool:t,toolId:r}}createExecutionContext(e){let t;try{t=aS()?.user?.id}catch{}return{...e,sessionId:e?.sessionId??ht(),userId:e?.userId??t}}async confirmToolCall(e,t,r,n,o){const i=await K6(this.hitlManager,e,t,n.hitlState,{serverId:r,sessionId:n.sessionId,userId:n.userId,signal:n.abortSignal},{log:s=>Vr.info(s),span:o});if(!i.run)throw i.error;return i.args}getToolInfo(e){let t=this.tools.get(e);if(!t){for(const r of this.tools.values())if(r.name===e){t=r;break}}if(t)return{tool:t,server:{id:t.serverId||"unknown-server"}}}updateStats(e,t){const r=this.toolExecutionStats.get(e)||{count:0,totalTime:0};r.count+=1,r.totalTime+=t,this.toolExecutionStats.set(e,r)}getExecutionStats(){const e={};for(const[t,r]of this.toolExecutionStats.entries())e[t]={count:r.count,totalTime:r.totalTime,averageTime:r.totalTime/r.count};return e}clearStats(){this.toolExecutionStats.clear()}getBuiltInServerInfos(){return this.builtInServerInfos}getToolsByCategory(e){const t=new Map;for(const[r,n]of this.tools.entries())n.category===e&&!t.has(r)&&t.set(r,n);return Array.from(t.values())}getAvailableTools(e){const t=Array.from(this.tools.values()),r=[],n=[];for(const o of t){const i=`${o.serverId||"unknown"}.${o.name}`,s=e.get(i);s&&s.getState()==="open"?r.push(o.name):n.push(o)}return{tools:n,unavailableTools:r}}hasTool(e){if(this.tools.has(e))return!0;for(const t of this.tools.values())if(t.name===e)return!0;return!1}async registerTool(e,t,r){Vr.debug(`Registering tool: ${e}`);const n=pkr.validateToolInfo(e,{description:t.description,serverId:t.serverId});if(!n.isValid)throw Vr.error(`Tool registration failed for ${e}: ${n.error}`),new Error(`Tool validation failed: ${n.error}`);n.warnings&&n.warnings.length>0&&Vr.warn(`Tool registration warnings for ${e}:`,n.warnings),Vr.debug(`\u2705 Tool '${e}' passed flexible validation - registration proceeding`),this.tools.set(e,t),this.toolImplementations.set(e,r),Vr.debug(`Successfully registered tool: ${e}`)}removeTool(e){let t=!1;if(this.tools.has(e))this.tools.delete(e),this.toolImplementations.delete(e),this.toolExecutionStats.delete(e),Vr.info(`Removed tool: ${e}`),t=!0;else for(const[r,n]of Array.from(this.tools.entries()))n.name===e&&(this.tools.delete(r),this.toolImplementations.delete(r),this.toolExecutionStats.delete(r),Vr.info(`Removed tool: ${r}`),t=!0);return t}getToolCount(){return this.tools.size}getStats(){const e=this.list(),t=Array.from(this.tools.values()),r={};for(const o of e){const i=o.metadata?.category||"uncategorized";r[i]=(r[i]||0)+1}const n={};for(const o of t){const i=o.category||"uncategorized";n[i]=(n[i]||0)+1}return{totalServers:e.length,totalTools:t.length,serversByCategory:r,toolsByCategory:n,executionStats:this.getExecutionStats()}}unregisterServer(e){const t=[];for(const[i,s]of this.tools.entries())s.serverId===e&&(this.tools.delete(i),this.toolImplementations.delete(i),this.toolExecutionStats.delete(i),this.unbatchableTools.delete(i),t.push(i));const r=this.builtInServerInfos.length;this.builtInServerInfos=this.builtInServerInfos.filter(i=>i.id!==e);const n=r>this.builtInServerInfos.length,o=this.unregister(e);return Vr.info(`Unregistered server ${e}, removed ${t.length} tools${n?" and server from builtInServerInfos":""}`),o}},jye=new v9}});function _9(e,t){if(typeof e=="string")return e.replace(gkr,(r,n)=>{const o=n.trim();if(!vkr.test(o))return le.warn(`[ExternalServerManager] ${t}: "${r}" is not a valid environment variable reference (names must match ^[A-Z][A-Z0-9_]*$); left as written`),r;const i=process.env[o];return i===void 0?(le.warn(`[ExternalServerManager] ${t}: environment variable ${o} is not defined, using empty string`),""):i});if(Array.isArray(e))return e.map(r=>_9(r,t));if(lr(e)){const r={};for(const[n,o]of Object.entries(e))r[n]=_9(o,t);return r}return e}function w9(e,t){if(typeof e=="string"){ykr.test(e)&&le.warn(`[ExternalServerManager] ${t} contains a \${VAR} reference; environment variables are never expanded in ${t} (only in env and args). The value is used as written.`);return}if(Array.isArray(e)){for(const r of e)w9(r,t);return}if(lr(e))for(const[r,n]of Object.entries(e))w9(n,`${t}.${r}`)}function mkr(e){const t=e instanceof Error?e.message:String(e);return _kr.test(t)}function E5n(e){if(!e||e.length===0)return e;const t=[...e];for(let r=0;r<t.length;r++){const n=t[r].indexOf("=");if(n!==-1){const o=t[r].substring(0,n);Xye.test(o)&&(t[r]=`${o}=[REDACTED]`);continue}Xye.test(t[r])&&r+1<t.length&&!t[r+1].startsWith("--")&&(t[r+1]="[REDACTED]",r++)}return t}function Hye(e){return b3(e)?Object.values(e).every(r=>r===null||typeof r=="string"||typeof r=="number"||typeof r=="boolean"?!0:Array.isArray(r)?r.every(n=>Hye(n)||typeof n=="string"||typeof n=="number"||typeof n=="boolean"||n===null):lr(r)?Hye(r):!1):!1}function b9(e){return Hye(e)?e:void 0}function S5n(e){if(!lr(e))return!1;const t=e;if(t.blockedTools!==void 0&&(!Array.isArray(t.blockedTools)||!t.blockedTools.every(o=>typeof o=="string")))return!1;const r=typeof t.command=="string",n=typeof t.url=="string";return!r&&!n?!1:(t.command===void 0||typeof t.command=="string")&&(t.args===void 0||Array.isArray(t.args))&&(t.env===void 0||lr(t.env))&&(t.transport===void 0||typeof t.transport=="string")&&(t.timeout===void 0||typeof t.timeout=="number")&&(t.retries===void 0||typeof t.retries=="number")&&(t.healthCheckInterval===void 0||typeof t.healthCheckInterval=="number")&&(t.autoRestart===void 0||typeof t.autoRestart=="boolean")&&(t.cwd===void 0||typeof t.cwd=="string")&&(t.url===void 0||typeof t.url=="string")&&(t.headers===void 0||lr(t.headers))&&(t.httpOptions===void 0||lr(t.httpOptions))&&(t.retryConfig===void 0||lr(t.retryConfig))&&(t.rateLimiting===void 0||lr(t.rateLimiting))&&(t.inheritParentEnv===void 0||typeof t.inheritParentEnv=="boolean")&&(t.allowPrivateNetwork===void 0||typeof t.allowPrivateNetwork=="boolean")&&(t.metadata===void 0||lr(t.metadata))}function hkr(e,t){if(!S5n(t))throw new Error(`Invalid server config for ${e}: missing required properties or wrong types`);return t.headers!==void 0&&w9(t.headers,`${e}.headers`),t.url!==void 0&&w9(t.url,`${e}.url`),{id:e,name:e,description:typeof t.description=="string"?t.description:`External MCP server: ${e}`,transport:typeof t.transport=="string"?t.transport:"stdio",status:"initializing",tools:[],command:typeof t.command=="string"?t.command:void 0,args:Array.isArray(t.args)?_9(t.args.map(r=>String(r)),`${e}.args`):[],env:lr(t.env)?_9(t.env,`${e}.env`):{},inheritParentEnv:typeof t.inheritParentEnv=="boolean"?t.inheritParentEnv:void 0,allowPrivateNetwork:typeof t.allowPrivateNetwork=="boolean"?t.allowPrivateNetwork:void 0,timeout:typeof t.timeout=="number"?t.timeout:void 0,retries:typeof t.retries=="number"?t.retries:void 0,healthCheckInterval:typeof t.healthCheckInterval=="number"?t.healthCheckInterval:void 0,autoRestart:typeof t.autoRestart=="boolean"?t.autoRestart:void 0,cwd:typeof t.cwd=="string"?t.cwd:void 0,url:typeof t.url=="string"?t.url:void 0,headers:lr(t.headers)?t.headers:void 0,fetch:fkr(t.fetch),httpOptions:lr(t.httpOptions)?t.httpOptions:void 0,retryConfig:lr(t.retryConfig)?t.retryConfig:void 0,rateLimiting:lr(t.rateLimiting)?t.rateLimiting:void 0,blockedTools:Array.isArray(t.blockedTools)?t.blockedTools:void 0,metadata:b9(t.metadata)}}var Wye,fkr,gkr,ykr,vkr,_kr,Kye,Jye,Xye,T9,Yye,Zye,wkr,bkr,Tkr,E9,Ekr,Qye,Skr=E({"src/lib/mcp/externalServerManager.ts"(){"use strict";To(),G(),zye(),v5n(),Vye(),wb(),_T(),st(),Gye(),Nm(),Ffe(),gr(),Gt(),process.stdin&&typeof process.stdin.unref=="function"&&(process.stdin.listenerCount("data")>0||process.stdin.listenerCount("readable")>0||process.stdin.unref(),process.stdin.prependListener("newListener",t=>{(t==="data"||t==="readable")&&process.stdin.ref()})),Wye=e=>typeof e=="function",fkr=e=>{if(e!=null){if(!Wye(e))throw new Error("MCP fetch hook must be a function");return e}},gkr=/\$\{([^}]*)\}/g,ykr=/\$\{[^}]*\}/,vkr=/^[A-Z][A-Z0-9_]*$/,_kr=/^Not connected$|MCP error -32000: Connection closed/,Kye=class extends Error{constructor(e,t,r){super(`Server '${e}' discovered ${t} tool(s), below the configured minTools=${r}`),this.serverId=e,this.toolsDiscovered=t,this.minTools=r,this.name="InsufficientToolsError"}serverId;toolsDiscovered;minTools;readiness="insufficient_tools"},Jye=2,Xye=/^--(api-key|token|secret|password|key|figma-api-key|access-token|auth|credential)$/i,T9=new Set,Yye=!1,Zye=async()=>{await Promise.all(Array.from(T9).map(e=>e.shutdown().catch(t=>{le.error("[ExternalServerManager] Error during process-exit cleanup:",t)})))},wkr=()=>{Zye()},bkr=Symbol.for("signal-exit emitter"),Tkr=()=>{const t=globalThis[bkr]?.count;return typeof t=="number"&&t>0?t:0},E9=e=>{const t=process.listenerCount(e)-Tkr()>1;Zye().finally(()=>{t||(process.removeListener(e,E9),g9(),process.kill(process.pid,e))})},Ekr=e=>{T9.add(e),Yye||(Yye=!0,process.prependListener("SIGINT",E9),process.prependListener("SIGTERM",E9),process.on("beforeExit",wkr))},Qye=class extends On{servers=new Map;config;isShuttingDown=!1;healthChecksInFlight=new Set;inFlightToolCalls=new Map;unresponsiveChecks=new Map;consecutiveFailures=new Map;retryDeadlines=new Map;lastHealth=new Map;lifecycleStates=new Map;closedClients=new WeakSet;toolDiscovery;enableMainRegistryIntegration;hitlManager;fallbackHITLManager;constructor(e={},t={}){super();const r=Math.max(5e3,Number(process.env.MCP_CLIENT_TIMEOUT)||6e4);this.config={maxServers:e.maxServers??10,defaultTimeout:e.defaultTimeout??r,defaultHealthCheckInterval:e.defaultHealthCheckInterval??3e4,enableAutoRestart:e.enableAutoRestart??!0,maxRestartAttempts:e.maxRestartAttempts??3,restartBackoffMultiplier:e.restartBackoffMultiplier??2,enablePerformanceMonitoring:e.enablePerformanceMonitoring??!0,logLevel:e.logLevel??"info"},this.enableMainRegistryIntegration=t.enableMainRegistryIntegration??!1,this.toolDiscovery=new lkr,this.toolDiscovery.on("toolRegistered",n=>{this.emit("toolDiscovered",{...n,serverName:this.getServerName(n.serverId)})}),this.toolDiscovery.on("toolUnregistered",n=>{this.emit("toolRemoved",{...n,serverName:this.getServerName(n.serverId)})}),Ekr(this)}setOutputNormalizer(e){this.toolDiscovery.setOutputNormalizer(e),le.debug("[ExternalServerManager] MCP output normalizer attached to ToolDiscoveryService")}setHITLManager(e){this.hitlManager=e,e&&e.isEnabled()?le.info("[ExternalServerManager] HITL safety mechanisms enabled for external tool execution"):le.debug("[ExternalServerManager] HITL safety mechanisms disabled or not configured")}setFallbackHITLManager(e){this.fallbackHITLManager=e}getHITLManager(){return this.hitlManager?.isEnabled()?this.hitlManager:this.fallbackHITLManager?.()??this.hitlManager}getServerName(e){return this.servers.get(e)?.config?.name||e}async loadMCPConfiguration(e,t={}){return t.parallel?this.loadMCPConfigurationParallel(e):this.loadMCPConfigurationSequential(e)}async loadMCPConfigurationParallel(e){const t=await Promise.resolve().then(()=>(yo(),up)),r=await Promise.resolve().then(()=>(Nr(),qh)),n=e||r.join(process.cwd(),".mcp-config.json");if(!t.existsSync(n))return le.debug(`[ExternalServerManager] No MCP config found at ${n}`),{serversLoaded:0,errors:[]};le.debug(`[ExternalServerManager] Loading MCP configuration in PARALLEL mode from ${n}`);try{const o=t.readFileSync(n,"utf8"),i=JSON.parse(o);if(!i.mcpServers||typeof i.mcpServers!="object")return le.debug("[ExternalServerManager] No mcpServers found in configuration"),{serversLoaded:0,errors:[]};const s=Object.entries(i.mcpServers).map(async([u,d])=>{try{const p=hkr(u,d),m=await this.addServer(u,p);return{serverId:u,result:m}}catch(p){const m=`Failed to load MCP server ${u}: ${p instanceof Error?p.message:String(p)}`;return{serverId:u,error:m}}}),a=await Promise.allSettled(s);let c=0;const l=[];for(const u of a)if(u.status==="fulfilled"){const{serverId:d,result:p,error:m}=u.value;if(p&&p.success)c++,le.debug(`[ExternalServerManager] Successfully loaded MCP server in parallel: ${d}`);else if(m)l.push(m),le.error(`[ExternalServerManager] Failed to load server ${d}: ${m}`);else if(p&&!p.success){const h=`Failed to load server ${d}: ${p.error}`;l.push(h),le.error(`[ExternalServerManager] ${h}`)}}else{const d=`Unexpected error during parallel loading: ${u.reason}`;l.push(d),le.error(`[ExternalServerManager] ${d}`)}return le.info(`[ExternalServerManager] PARALLEL MCP configuration loading complete: ${c} servers loaded, ${l.length} errors`),{serversLoaded:c,errors:l}}catch(o){const i=`Failed to load MCP configuration in parallel mode: ${o instanceof Error?o.message:String(o)}`;return le.error(`[ExternalServerManager] ${i}`),{serversLoaded:0,errors:[i]}}}async loadMCPConfigurationSequential(e){const t=await Promise.resolve().then(()=>(yo(),up)),r=await Promise.resolve().then(()=>(Nr(),qh)),n=e||r.join(process.cwd(),".mcp-config.json");if(!t.existsSync(n))return le.debug(`[ExternalServerManager] No MCP config found at ${n}`),{serversLoaded:0,errors:[]};le.debug(`[ExternalServerManager] Loading MCP configuration from ${n}`);try{const o=t.readFileSync(n,"utf8"),i=JSON.parse(o);if(!i.mcpServers||typeof i.mcpServers!="object")return le.debug("[ExternalServerManager] No mcpServers found in configuration"),{serversLoaded:0,errors:[]};let s=0;const a=[];for(const[c,l]of Object.entries(i.mcpServers))try{const u=hkr(c,l),d=await this.addServer(c,u);if(d.success)s++,le.debug(`[ExternalServerManager] Successfully loaded MCP server: ${c}`);else{const p=`Failed to load server ${c}: ${d.error}`;a.push(p),le.error(`[ExternalServerManager] ${p}`)}}catch(u){const d=`Failed to load MCP server ${c}: ${u instanceof Error?u.message:String(u)}`;a.push(d),le.error(`[ExternalServerManager] ${d}`)}return le.info(`[ExternalServerManager] MCP configuration loading complete: ${s} servers loaded, ${a.length} errors`),{serversLoaded:s,errors:a}}catch(o){const i=`Failed to load MCP configuration: ${o instanceof Error?o.message:String(o)}`;return le.error(`[ExternalServerManager] ${i}`),{serversLoaded:0,errors:[i]}}}validateConfig(e){const t=[],r=[],n=[];(!e.id||typeof e.id!="string")&&t.push("Server ID is required and must be a string"),["stdio","sse","websocket","http"].includes(e.transport)||t.push("Transport must be one of: stdio, sse, websocket, http"),e.fetch!==void 0&&!Wye(e.fetch)&&t.push("MCP fetch hook must be a function");for(const[o,i]of Object.entries({connectionTimeout:e.httpOptions?.connectionTimeout,requestTimeout:e.httpOptions?.requestTimeout}))i!==void 0&&(!Number.isFinite(i)||i<=0)&&t.push(`${o} must be a positive finite number`);return e.transport==="stdio"?((!e.command||typeof e.command!="string")&&t.push("Command is required and must be a string for stdio transport"),Array.isArray(e.args)||t.push("Args must be an array")):(e.transport==="sse"||e.transport==="websocket"||e.transport==="http")&&(!e.url||typeof e.url!="string")&&t.push(`URL is required for ${e.transport} transport`),e.timeout&&e.timeout<5e3&&r.push("Timeout less than 5 seconds may cause connection issues"),e.retries&&e.retries>5&&r.push("High retry count may slow down error recovery"),e.healthCheckInterval||n.push("Consider setting a health check interval for better reliability"),e.autoRestart===void 0&&n.push("Consider enabling auto-restart for production use"),{isValid:t.length===0,errors:t,warnings:r,suggestions:n}}convertConfigToMCPServerInfo(e,t){return{id:e,name:String(t.metadata?.title||e),description:`External MCP server (${t.transport})`,status:"initializing",transport:t.transport,command:t.command,args:t.args,env:t.env,tools:[],blockedTools:t.blockedTools,timeout:t.timeout,retries:t.retries,healthCheckInterval:t.healthCheckInterval,autoRestart:t.autoRestart,minTools:t.minTools,cwd:t.cwd,inheritParentEnv:t.inheritParentEnv,allowPrivateNetwork:t.allowPrivateNetwork,url:t.url,headers:t.headers,fetch:t.fetch,httpOptions:t.httpOptions,retryConfig:t.retryConfig,rateLimiting:t.rateLimiting,auth:t.auth,metadata:{category:"external",...b9(t.metadata)||{}}}}async addServer(e,t){const r=Date.now();let n;try{const o="transport"in t&&"command"in t&&!("tools"in t)?this.convertConfigToMCPServerInfo(e,t):t;if(this.servers.size>=this.config.maxServers)return{success:!1,error:`Maximum number of servers (${this.config.maxServers}) reached`,serverId:e,duration:Date.now()-r};const i={id:e,name:o.name,description:o.description,transport:o.transport,status:o.status,tools:o.tools,command:o.command||"",args:o.args||[],env:o.env||{},timeout:o.timeout,retries:o.retries,healthCheckInterval:o.healthCheckInterval,autoRestart:o.autoRestart,minTools:o.minTools,cwd:o.cwd,inheritParentEnv:o.inheritParentEnv,allowPrivateNetwork:o.allowPrivateNetwork,url:o.url,blockedTools:o.blockedTools,metadata:b9(o.metadata),headers:o.headers,auth:o.auth,fetch:o.fetch,httpOptions:o.httpOptions,retryConfig:o.retryConfig,rateLimiting:o.rateLimiting},s=this.validateConfig(i);if(!s.isValid)return{success:!1,error:`Configuration validation failed: ${s.errors.join(", ")}`,serverId:e,duration:Date.now()-r};if(this.servers.has(e))return{success:!1,error:`Server with ID '${e}' already exists`,serverId:e,duration:Date.now()-r};le.info(`[ExternalServerManager] Adding server: ${e}`,{command:o.command,transport:o.transport});const a={...o,process:null,client:null,transportInstance:null,status:"initializing",reconnectAttempts:0,maxReconnectAttempts:this.config.maxRestartAttempts,toolsMap:new Map,metrics:{totalConnections:0,totalDisconnections:0,totalErrors:0,totalToolCalls:0,averageResponseTime:0,lastResponseTime:0},config:i};n=a,this.servers.set(e,a),await this.startServer(e);const c=this.servers.get(e);if(!c)throw new Error(`Server ${e} not found after registration`);return{success:!0,data:{config:c.config,process:c.process,pid:c.pid,client:c.client,transport:c.transportInstance,status:c.status,lastError:c.lastError,startTime:c.startTime,lastHealthCheck:c.lastHealthCheck,reconnectAttempts:c.reconnectAttempts,maxReconnectAttempts:c.maxReconnectAttempts,tools:c.toolsMap,toolsArray:c.toolsArray,capabilities:c.capabilities,healthTimer:c.healthTimer,restartTimer:c.restartTimer,metrics:c.metrics},serverId:e,duration:Date.now()-r,metadata:{timestamp:Date.now(),operation:"addServer",readiness:"ready",toolsDiscovered:c.tools.length}}}catch(o){return le.debug(`[ExternalServerManager] Failed to add server ${e}:`,o),n!==void 0&&this.servers.get(e)===n&&n.status!=="stopping"&&(this.servers.delete(e),this.consecutiveFailures.delete(e),this.retryDeadlines.delete(e),this.lastHealth.delete(e),this.lifecycleStates.delete(e)),o instanceof Kye?{success:!1,error:o.message,serverId:e,duration:Date.now()-r,metadata:{timestamp:Date.now(),operation:"addServer",readiness:o.readiness,toolsDiscovered:o.toolsDiscovered}}:{success:!1,error:o instanceof Error?o.message:String(o),serverId:e,duration:Date.now()-r}}}async removeServer(e){const t=Date.now();try{const r=this.servers.get(e);if(!r)return{success:!1,error:`Server '${e}' not found`,serverId:e,duration:Date.now()-t};le.info(`[ExternalServerManager] Removing server: ${e}`);const n=this.getServerName(e);return await this.stopServer(e),this.servers.get(e)===r&&(this.servers.delete(e),this.consecutiveFailures.delete(e),this.retryDeadlines.delete(e),this.lastHealth.delete(e),this.lifecycleStates.delete(e),this.emit("disconnected",{serverId:e,serverName:n,reason:"Manually removed",timestamp:new Date})),{success:!0,serverId:e,duration:Date.now()-t,metadata:{timestamp:Date.now(),operation:"removeServer"}}}catch(r){return le.error(`[ExternalServerManager] Failed to remove server ${e}:`,r),{success:!1,error:r instanceof Error?r.message:String(r),serverId:e,duration:Date.now()-t}}}async startServer(e){const t=this.servers.get(e);if(!t)throw new Error(`Server '${e}' not found`);const r=t.config,n=We.mcp.startSpan("mcp.server.start",{attributes:{"mcp.server_id":e,"mcp.transport":r.transport,"mcp.command_name":r.command&&r.command.split(/[\\/]/).pop()||"","mcp.command_present":!!r.command}});try{this.updateServerStatus(e,"connecting"),this.toolDiscovery.clearServerTools(e),t.toolsMap.clear(),t.toolsArray=void 0,t.tools=[],le.debug(`[ExternalServerManager] Starting server: ${e}`,{command:r.command,args:E5n(r.args),transport:r.transport});const o=await Ig.createClient(r,r.timeout||this.config.defaultTimeout);if(!o.success||!o.client||!o.transport)throw new Error(`Failed to create MCP client: ${o.error}`);if(this.servers.get(e)!==t||this.isShuttingDown)throw await Ig.closeClient(o.client,o.transport,o.process??void 0),new Error(`MCP startup for '${e}' was superseded`);t.client=o.client,t.transportInstance=o.transport,t.process=o.process||null;const{StdioClientTransport:i}=await Promise.resolve().then(()=>(hSr(),cye));t.pid=o.transport instanceof i?o.transport.pid??void 0:void 0,t.capabilities=b9(o.capabilities),t.startTime=new Date,t.lastHealthCheck=new Date,t.metrics.totalConnections++,this.unresponsiveChecks.delete(e),this.attachClientLifecycle(e,o.client,o.transport);const s=()=>{if(this.servers.get(e)!==t||t.client!==o.client||o.client.transport!==o.transport||this.closedClients.has(o.client)||t.status!=="initializing"||this.isShuttingDown)throw new Error(`MCP connection for '${e}' was lost during startup`)};s(),await this.discoverServerTools(e),s();const a=r.minTools??0;if(t.toolsMap.size<a){const c=t.toolsMap.size;throw le.warn(`[ExternalServerManager] Server '${e}' discovered ${c} tool(s), below the configured minTools=${a}; tearing the connection back down`),await this.closeInstanceConnection(e,t),new Kye(e,c,a)}this.enableMainRegistryIntegration&&await this.registerServerToolsWithMainRegistry(e),s(),this.consecutiveFailures.delete(e),this.lastHealth.delete(e),this.retryDeadlines.delete(e),t.lastError=void 0,this.updateServerStatus(e,"connected"),this.startHealthMonitoring(e),this.emit("connected",{serverId:e,serverName:this.getServerName(e),toolCount:t.toolsMap.size,timestamp:new Date}),n.setAttribute("mcp.tool_count",t.toolsMap.size),n.setStatus({code:Ve.OK}),le.info(`[ExternalServerManager] Server started successfully: ${e}`)}catch(o){if(le.debug(`[ExternalServerManager] Failed to start server ${e}:`,o),this.servers.get(e)===t&&t.status!=="stopping"){await this.closeInstanceConnection(e,t);const i=this.servers.get(e);i===t&&i.status!=="stopping"&&!this.isShuttingDown&&(this.updateServerStatus(e,"failed",t),t.lastError=o instanceof Error?o.message:String(o),this.consecutiveFailures.set(e,(this.consecutiveFailures.get(e)??0)+1),this.emit("failed",{serverId:e,serverName:this.getServerName(e),error:t.lastError,timestamp:new Date}))}else this.servers.get(e)!==t&&t.client&&t.transportInstance&&(t.client.onclose=void 0,t.client.onerror=void 0,await Ig.closeClient(t.client,t.transportInstance,t.process??void 0),t.client=null,t.transportInstance=null,t.process=null);throw n.recordException(o instanceof Error?o:new Error(String(o))),n.setStatus({code:Ve.ERROR,message:o instanceof Error?o.message:String(o)}),o}finally{n.end()}}async closeInstanceConnection(e,t){if(this.enableMainRegistryIntegration&&this.unregisterServerToolsFromMainRegistry(e),this.toolDiscovery.clearServerTools(e),t.toolsMap.clear(),t.toolsArray=void 0,t.tools=[],!(!t.client||!t.transportInstance)){t.client.onclose=void 0,t.client.onerror=void 0;try{await Ig.closeClient(t.client,t.transportInstance,t.process??void 0)}catch(r){le.debug(`[ExternalServerManager] Error closing client for ${e}:`,r)}t.client=null,t.transportInstance=null,t.process=null,t.pid=void 0}}async stopServer(e){const t=this.servers.get(e);if(!t)return;const r=We.mcp.startSpan("mcp.server.stop",{attributes:{"mcp.server_id":e}});try{this.updateServerStatus(e,"stopping",t),t.healthTimer&&(clearInterval(t.healthTimer),t.healthTimer=void 0),t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0),this.enableMainRegistryIntegration&&this.unregisterServerToolsFromMainRegistry(e),this.toolDiscovery.clearServerTools(e),await this.closeInstanceConnection(e,t),this.updateServerStatus(e,"stopped",t),r.setStatus({code:Ve.OK}),le.info(`[ExternalServerManager] Server stopped: ${e}`)}catch(n){le.error(`[ExternalServerManager] Error stopping server ${e}:`,n),this.updateServerStatus(e,"failed",t),r.recordException(n instanceof Error?n:new Error(String(n))),r.setStatus({code:Ve.ERROR,message:n instanceof Error?n.message:String(n)})}finally{r.end()}}updateServerStatus(e,t,r){const n=this.servers.get(e);if(!n||r!==void 0&&n!==r)return;const o=n.status;this.lifecycleStates.set(e,t);const i=t==="connecting"||t==="restarting"?"initializing":t==="stopping"||t==="stopped"?"stopping":t==="connected"?"connected":t==="disconnected"?"disconnected":"failed";n.status=i,this.emit("statusChanged",{serverId:e,serverName:this.getServerName(e),oldStatus:o,newStatus:t,timestamp:new Date}),le.debug(`[ExternalServerManager] Status changed for ${e}: ${o} -> ${t}`)}attachClientLifecycle(e,t,r){t.onclose=()=>{this.closedClients.add(t);const n=this.servers.get(e),o=n?.pid?` (pid ${n.pid})`:"",i=Ig.getStderrTail(r),s=i.length>0?`Server process closed${o}; last stderr: ${i.slice(-5).join(" | ")}`:`Server process closed${o}`;this.handleConnectionLost(e,t,s,i)},t.onerror=n=>{le.warn(`[ExternalServerManager] Transport error for ${e}: ${n.message}`)}}handleConnectionLost(e,t,r,n=[],o=!1){const i=this.servers.get(e);!i||i.client!==t||i.status!=="connected"||(le.warn(`[ExternalServerManager] Connection lost for ${e}: ${r}`,n.length>0?{stderrTail:n}:void 0),i.lastError=r,this.handleServerDisconnection(e,r,o))}trackToolCall(e,t){const r=(this.inFlightToolCalls.get(e)??0)+t;r<=0?this.inFlightToolCalls.delete(e):this.inFlightToolCalls.set(e,r)}handleServerError(e,t){const r=this.servers.get(e);r&&(r.lastError=t.message,r.metrics.totalErrors++,this.consecutiveFailures.set(e,(this.consecutiveFailures.get(e)??0)+1),le.error(`[ExternalServerManager] Server error for ${e}:`,t),this.emit("failed",{serverId:e,serverName:this.getServerName(e),error:t.message,timestamp:new Date}),(r.config.autoRestart??this.config.enableAutoRestart)&&!this.isShuttingDown?this.scheduleRestart(e):this.updateServerStatus(e,"failed"))}handleServerDisconnection(e,t,r=!1){const n=this.servers.get(e);n&&(n.metrics.totalDisconnections++,r||this.consecutiveFailures.set(e,(this.consecutiveFailures.get(e)??0)+1),le.warn(`[ExternalServerManager] Server disconnected ${e}: ${t}`),this.emit("disconnected",{serverId:e,serverName:this.getServerName(e),reason:t,timestamp:new Date}),(n.config.autoRestart??this.config.enableAutoRestart)&&!this.isShuttingDown?this.scheduleRestart(e):this.updateServerStatus(e,"disconnected"))}scheduleRestart(e){const t=this.servers.get(e);if(!t||t.restartTimer)return;if(t.reconnectAttempts>=t.maxReconnectAttempts){le.error(`[ExternalServerManager] Max restart attempts reached for ${e}`),this.updateServerStatus(e,"failed"),this.retryDeadlines.delete(e);return}t.reconnectAttempts++,this.updateServerStatus(e,"restarting");const r=Math.min(1e3*Math.pow(this.config.restartBackoffMultiplier,t.reconnectAttempts-1),3e4);le.info(`[ExternalServerManager] Scheduling restart for ${e} in ${r}ms (attempt ${t.reconnectAttempts})`),this.retryDeadlines.set(e,new Date(Date.now()+r));const n=this.getServerStatuses().find(o=>o.serverId===e);n&&this.emit("healthCheck",{serverId:e,serverName:this.getServerName(e),health:n,timestamp:new Date}),t.restartTimer=setTimeout(async()=>{this.retryDeadlines.delete(e);const o=We.mcp.startSpan("mcp.server.restart",{attributes:{"mcp.server_id":e,"mcp.restart_attempt":t.reconnectAttempts,"mcp.restart_delay_ms":r}});try{if(this.servers.get(e)!==t||(await this.stopServer(e),this.servers.get(e)!==t)||(await this.startServer(e),this.servers.get(e)!==t))return;t.reconnectAttempts=0,o.setStatus({code:Ve.OK})}catch(i){le.error(`[ExternalServerManager] Restart failed for ${e}:`,i),o.recordException(i instanceof Error?i:new Error(String(i))),o.setStatus({code:Ve.ERROR,message:i instanceof Error?i.message:String(i)}),this.servers.get(e)===t&&this.scheduleRestart(e)}finally{o.end()}},r)}startHealthMonitoring(e){const t=this.servers.get(e);if(!t||!this.config.enablePerformanceMonitoring)return;const r=t.config.healthCheckInterval??this.config.defaultHealthCheckInterval;t.healthTimer=setInterval(async()=>{await this.performHealthCheck(e)},r),t.healthTimer.unref&&t.healthTimer.unref()}async performHealthCheck(e){const t=this.servers.get(e);if(!t||t.status!=="connected"||!t.client||this.healthChecksInFlight.has(e))return;this.healthChecksInFlight.add(e);const r=t.client,n=t.config.healthCheckInterval??this.config.defaultHealthCheckInterval,o=Math.max(1,Math.min(t.config.timeout||this.config.defaultTimeout,n)),i=Date.now(),s=[];let a=!0,c=!1,l=!1;try{try{if(await r.ping({timeout:o}),t.client!==r||t.status!=="connected")return;this.unresponsiveChecks.delete(e),this.consecutiveFailures.delete(e),t.lastError=void 0}catch(p){if(t.client!==r||t.status!=="connected")return;if(a=!1,this.consecutiveFailures.set(e,(this.consecutiveFailures.get(e)??0)+1),t.lastError=p instanceof Error?p.message:String(p),mkr(p))c=!0,s.push("connection closed");else{const m=this.inFlightToolCalls.get(e)??0;if(m>0)s.push(`ping timed out after ${o}ms while ${m} tool call(s) in flight`);else{const h=(this.unresponsiveChecks.get(e)??0)+1;this.unresponsiveChecks.set(e,h),s.push(`ping timed out after ${o}ms while idle (${h}/${Jye})`),l=h>=Jye}}}const u=Date.now()-i;t.lastHealthCheck=new Date;const d={serverId:e,isHealthy:a,status:this.lifecycleStates.get(e)??t.status,checkedAt:new Date,responseTime:u,toolCount:t.toolsMap.size,issues:s,consecutiveFailures:this.consecutiveFailures.get(e)??0,lastError:t.lastError,nextRetryAt:this.retryDeadlines.get(e),performance:{uptime:t.startTime?Date.now()-t.startTime.getTime():0,averageResponseTime:t.metrics.averageResponseTime}};this.lastHealth.set(e,d),this.emit("healthCheck",{serverId:e,serverName:this.getServerName(e),health:d,timestamp:new Date}),c||l?this.handleConnectionLost(e,r,`Health check failed: ${s.join(", ")}`,[],!0):a||le.warn(`[ExternalServerManager] Health check failed for ${e}:`,s)}catch(u){le.error(`[ExternalServerManager] Health check error for ${e}:`,u)}finally{this.healthChecksInFlight.delete(e)}}getServer(e){const t=this.servers.get(e);if(t)return{config:t.config,process:t.process,pid:t.pid,client:t.client,transport:t.transportInstance,status:t.status,lastError:t.lastError,startTime:t.startTime,lastHealthCheck:t.lastHealthCheck,reconnectAttempts:t.reconnectAttempts,maxReconnectAttempts:t.maxReconnectAttempts,tools:t.toolsMap,toolsArray:t.toolsArray,capabilities:t.capabilities,healthTimer:t.healthTimer,restartTimer:t.restartTimer,metrics:t.metrics}}getAllServers(){const e=new Map;for(const[t,r]of this.servers.entries())e.set(t,{config:r.config,process:r.process,pid:r.pid,client:r.client,transport:r.transportInstance,status:r.status,lastError:r.lastError,startTime:r.startTime,lastHealthCheck:r.lastHealthCheck,reconnectAttempts:r.reconnectAttempts,maxReconnectAttempts:r.maxReconnectAttempts,tools:r.toolsMap,toolsArray:r.toolsArray,capabilities:r.capabilities,healthTimer:r.healthTimer,restartTimer:r.restartTimer,metrics:r.metrics});return e}listServers(){return Array.from(this.servers.values())}getServerStatuses(){const e=[];for(const[t,r]of Array.from(this.servers.entries())){const n=r.startTime?Date.now()-r.startTime.getTime():0;e.push({serverId:t,isHealthy:r.status==="connected"&&(this.lastHealth.get(t)?.isHealthy??!0),status:this.lifecycleStates.get(t)??r.status,checkedAt:r.lastHealthCheck||new Date,toolCount:r.toolsMap.size,issues:r.lastError?[r.lastError]:[],consecutiveFailures:this.consecutiveFailures.get(t)??0,lastError:r.lastError,nextRetryAt:this.retryDeadlines.get(t),performance:{uptime:n,averageResponseTime:r.metrics.averageResponseTime}})}return e}async shutdown(){if(this.isShuttingDown)return;this.isShuttingDown=!0,T9.delete(this),le.info("[ExternalServerManager] Shutting down all servers...");const e=Array.from(this.servers.keys()).map(t=>this.stopServer(t).catch(r=>{le.error(`[ExternalServerManager] Error shutting down ${t}:`,r)}));await Promise.all(e),this.servers.clear(),this.toolDiscovery.destroy(),this.removeAllListeners(),le.info("[ExternalServerManager] All servers shut down and resources cleaned up")}async destroy(){return this.shutdown()}getStatistics(){let e=0,t=0,r=0,n=0,o=0;for(const i of Array.from(this.servers.values()))i.status==="connected"?e++:i.status==="failed"&&t++,r+=i.toolsMap.size,n+=i.metrics.totalConnections,o+=i.metrics.totalErrors;return{totalServers:this.servers.size,connectedServers:e,failedServers:t,totalTools:r,totalConnections:n,totalErrors:o}}async discoverServerTools(e){const t=this.servers.get(e);if(!t||!t.client)throw new Error(`Server '${e}' not found or not connected`);if(t.client.getServerCapabilities()?.tools!==void 0)try{le.debug(`[ExternalServerManager] Discovering tools for server: ${e}`);const r=t.client,n=()=>this.servers.get(e)===t&&t.client===r&&t.status==="initializing"&&r.transport===t.transportInstance&&!this.closedClients.has(r)&&!this.isShuttingDown,o=await this.toolDiscovery.discoverTools(e,r,t.config.timeout||this.config.defaultTimeout,n,!0);if(!n())throw new Error(`MCP discovery for '${e}' was superseded`);if(o.success){t.toolsMap.clear(),t.toolsArray=void 0,t.tools=[];const i=t.blockedTools||[];let s=0;for(const a of o.tools){if(i.includes(a.name)){le.info(`[ExternalServerManager] Blocking tool '${a.name}' from server '${e}' (configured in blockedTools)`),s++;continue}t.toolsMap.set(a.name,a),t.tools.push({name:a.name,description:a.description,inputSchema:a.inputSchema})}le.info(`[ExternalServerManager] Discovered ${o.toolCount} tools for ${e} (${s} blocked, ${t.toolsMap.size} available)`)}else throw new Error(`Tool discovery failed for ${e}: ${o.error??"unknown failure"}`)}catch(r){throw le.error(`[ExternalServerManager] Tool discovery error for ${e}:`,r),r}}async registerServerToolsWithMainRegistry(e){const t=this.servers.get(e);if(!t)throw new Error(`Server '${e}' not found`);try{le.debug(`[ExternalServerManager] Registering ${t.toolsMap.size} tools with main registry for server: ${e}`);const r=[];for(const[s,a]of t.toolsMap.entries()){const c=`${e}.${s}`,l={name:s,description:a.description||s,inputSchema:a.inputSchema||{},serverId:e,category:oc({isExternal:!0,serverId:e})};try{r.push(jye.registerTool(c,l,{execute:async(u,d)=>await this.executeTool(e,s,u,{timeout:t.config.timeout||this.config.defaultTimeout})})),le.debug(`[ExternalServerManager] Registered tool with main registry: ${c}`)}catch(u){le.warn(`[ExternalServerManager] Failed to register tool ${c} with main registry:`,u)}}const n=await Promise.allSettled(r),o=n.filter(s=>s.status==="fulfilled").length,i=n.length-o;le.info(`[ExternalServerManager] Registered ${o}/${n.length} tools with main registry for ${e}${i?` (${i} failed)`:""}`)}catch(r){le.error(`[ExternalServerManager] Failed to register tools with main registry for ${e}:`,r)}}unregisterServerToolsFromMainRegistry(e){const t=this.servers.get(e);if(!(!t||!this.enableMainRegistryIntegration))try{le.debug(`[ExternalServerManager] Unregistering tools from main registry for server: ${e}`);for(const[r]of t.toolsMap.entries()){const n=`${e}.${r}`;try{jye.removeTool(n),le.debug(`[ExternalServerManager] Unregistered tool from main registry: ${n}`)}catch(o){le.debug(`[ExternalServerManager] Failed to unregister tool ${n}:`,o)}}le.debug(`[ExternalServerManager] Completed unregistering tools from main registry for ${e}`)}catch(r){le.error(`[ExternalServerManager] Error unregistering tools from main registry for ${e}:`,r)}}async executeTool(e,t,r,n){const o=this.servers.get(e);if(!o)throw new Error(`Server '${e}' not found`);const i=o.client;if(!i)throw new Error(`Server '${e}' is not connected`);if(o.status!=="connected")throw new Error(`Server '${e}' is not in connected state: ${o.status}`);if((o.blockedTools||[]).includes(t))throw new Error(`Tool '${t}' is blocked on server '${e}' by configuration`);G0(n?.signal);const a=Date.now();try{const c=await this.confirmExternalToolCall(e,t,r,n);G0(n?.signal),this.trackToolCall(e,1);let l;try{l=await this.toolDiscovery.executeTool(t,e,i,c,{timeout:n?.timeout||o.config.timeout||this.config.defaultTimeout,signal:n?.signal})}finally{this.trackToolCall(e,-1)}const u=Date.now()-a;o.metrics.totalToolCalls++,o.metrics.lastResponseTime=u;const d=o.metrics.averageResponseTime*(o.metrics.totalToolCalls-1)+u;if(o.metrics.averageResponseTime=d/o.metrics.totalToolCalls,l.success){const p=l.isErrorResult===!0;return p&&o.metrics.totalErrors++,le.debug(p?`[ExternalServerManager] Tool returned a resolved MCP error: ${t} on ${e}`:`[ExternalServerManager] Tool executed successfully: ${t} on ${e}`,{duration:u}),syr(t,u,!p),l.data}else throw new Error(l.error||"Tool execution failed")}catch(c){throw c instanceof nu||n?.signal?.aborted===!0?le.info(`[ExternalServerManager] External tool '${t}' on ${e} refused or cancelled before it ran: ${c instanceof Error?c.message:String(c)}`):(o.metrics.totalErrors++,syr(t,Date.now()-a,!1),le.error(`[ExternalServerManager] Tool execution failed: ${t} on ${e}`,c)),mkr(c)&&this.handleConnectionLost(e,i,`Connection lost during tool call '${t}': ${c instanceof Error?c.message:String(c)}`),c}}async confirmExternalToolCall(e,t,r,n){const o=await K6(this.getHITLManager(),t,r,n?.hitlState,{serverId:e,sessionId:`external-${e}-${Date.now()}`,userId:void 0,signal:n?.signal},{log:i=>le.info(`[ExternalServerManager] ${i}`),subject:"External tool",pauseDeadline:n?.pauseDeadline});if(!o.run)throw o.error;return o.args}getAllTools(){return this.toolDiscovery.getAllTools()}getServerTools(e){return this.toolDiscovery.getServerTools(e)}getToolDiscovery(){return this.toolDiscovery}}}});function k5n(e,t,r,n){return{content:[{type:"text",text:`[MCP Tool Output \u2014 ${r.toolName} | ${r.serverId}]
1256
+ `)}`,{cause:o}):o}}static getStderrTail(e){return $ye.get(e)?.snapshot()??[]}static async createTransport(e){switch(e.transport){case"stdio":return this.createStdioTransport(e);case"sse":return await this.assertNetworkUrlAllowed(e),this.createSSETransport(e);case"websocket":return await this.assertNetworkUrlAllowed(e),this.createWebSocketTransport(e);case"http":return await this.assertNetworkUrlAllowed(e),this.createHTTPTransport(e);default:throw new Error(`Unsupported transport type: ${e.transport}`)}}static async assertNetworkUrlAllowed(e){if(!e.url)throw new Error(`URL is required for ${e.transport} transport`);await mbr(e.url,{transport:e.transport,allowPrivateNetwork:e.allowPrivateNetwork,hostOwnedEgress:typeof e.fetch=="function",serverId:e.id})}static async createStdioTransport(e){if(le.debug(`[MCPClientFactory] Creating stdio transport for ${e.id}`,{command:e.command,args:e.args}),!e.command)throw new Error("Command is required for stdio transport");const{StdioClientTransport:t,getDefaultEnvironment:r}=await Promise.resolve().then(()=>(hSr(),cye)),{ChildProcess:n}=await Promise.resolve().then(()=>(ad(),yT)),o=e.inheritParentEnv===!0?{...process.env}:r(),i=new t({command:e.command,args:e.args||[],env:Object.fromEntries(Object.entries({...o,...e.env}).filter(([,a])=>a!==void 0).map(([a,c])=>[a,String(c)])),cwd:e.cwd,stderr:"pipe"});ikr(i,n);const s=new nkr;return $ye.set(i,s),i.stderr?.on("data",a=>{if(s.append(a),le.shouldLog("debug")){const c=a.toString().trim();c.length>0&&le.debug(`[MCPClientFactory] ${e.id} stderr:`,c)}}),{transport:i}}static async createSSETransport(e){if(!e.url)throw new Error("URL is required for SSE transport");le.debug(`[MCPClientFactory] Creating SSE transport for ${e.id}`,{url:e.url});try{const t=new URL(e.url),{SSEClientTransport:r}=await Promise.resolve().then(()=>(d5n(),VSr)),n=this.createEnhancedFetch(e,e.httpOptions?.requestTimeout??6e4);return{transport:new r(t,{requestInit:{headers:e.headers},fetch:n,eventSourceInit:{fetch:n}})}}catch(t){throw new Error(`Invalid SSE URL: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}static async createWebSocketTransport(e){if(!e.url)throw new Error("URL is required for WebSocket transport");le.debug(`[MCPClientFactory] Creating WebSocket transport for ${e.id}`,{url:e.url});const t=Object.keys(e.headers??{}).length;if(t>0||e.auth!==void 0)throw new Error(`WebSocket transport for ${e.id} cannot send the configured ${t>0?"headers":"auth"}: the WebSocket handshake carries no custom headers. Use the "http" or "sse" transport for an authenticated server, or remove the credentials.`);let r,n;try{r=new URL(e.url),n=await Promise.resolve().then(()=>(p5n(),WSr))}catch(a){throw new Error(`Invalid WebSocket URL: ${a instanceof Error?a.message:String(a)}`,{cause:a})}const o=new n.WebSocketClientTransport(r),i=e.httpOptions?.connectionTimeout??3e4,s=o.start.bind(o);return o.start=async()=>{try{await this.raceWithTimeout(s(),i,`WebSocket connection timeout for ${e.id} after ${i}ms`)}catch(a){throw await o.close().catch(()=>{}),a}},{transport:o}}static async createHTTPTransport(e){if(!e.url)throw new Error("URL is required for HTTP transport");const t={connectionTimeout:e.httpOptions?.connectionTimeout??3e4,requestTimeout:e.httpOptions?.requestTimeout??6e4,idleTimeout:e.httpOptions?.idleTimeout??12e4,keepAliveTimeout:e.httpOptions?.keepAliveTimeout??3e4};le.debug(`[MCPClientFactory] Creating HTTP transport for ${e.id}`,{url:e.url,hasHeaders:!!e.headers,hasAuth:!!e.auth,authType:e.auth?.type,httpOptions:t});try{const r=new URL(e.url),n=await this.setupAuthProvider(e),o={...e.headers??{}};if(e.auth){const l=await this.getAuthorizationHeader(e,n);l&&(o.Authorization=l)}const i=this.createEnhancedFetch(e,t.requestTimeout,n),s={headers:Object.keys(o).length>0?o:void 0},{StreamableHTTPClientTransport:a}=await Promise.resolve().then(()=>(y5n(),ZSr));return{transport:new a(r,{requestInit:s,fetch:i})}}catch(r){throw new Error(`Invalid HTTP URL: ${r instanceof Error?r.message:String(r)}`,{cause:r})}}static createFetchWithTimeout(e,t){return async(r,n)=>{const o=new AbortController,i=setTimeout(()=>o.abort(),e);try{const s=await t(r,{...n,redirect:"manual",signal:n?.signal?AbortSignal.any([o.signal,n.signal]):o.signal});if(s.status>=300&&s.status<400)throw await s.body?.cancel(),new Error("MCP transport redirects are not permitted");return s}finally{clearTimeout(i)}}}static createEnhancedFetch(e,t,r){const n=this.createFetchWithTimeout(t,e.fetch??globalThis.fetch);return async(o,i)=>{if(r&&e.auth?.type==="oauth2")try{const s=await r.getAuthorizationHeader(e.id);if(s){const a=i?.headers??{},c=new Headers(a);c.set("Authorization",s),i={...i,headers:c}}}catch(s){le.warn(`[MCPClientFactory] OAuth token refresh failed for ${e.id}:`,s instanceof Error?s.message:String(s))}return n(o,i)}}static async setupAuthProvider(e){if(e.auth?.type==="oauth2"&&e.auth.oauth){const t=new EB,r={clientId:e.auth.oauth.clientId,clientSecret:e.auth.oauth.clientSecret,authorizationUrl:e.auth.oauth.authorizationUrl,tokenUrl:e.auth.oauth.tokenUrl,redirectUrl:e.auth.oauth.redirectUrl,scope:e.auth.oauth.scope,usePKCE:e.auth.oauth.usePKCE??!0},n=new SB(r,t);return le.debug(`[MCPClientFactory] OAuth provider created for ${e.id}`,{clientId:r.clientId,usePKCE:r.usePKCE}),n}}static async getAuthorizationHeader(e,t){if(e.auth)switch(e.auth.type){case"oauth2":return t?await t.getAuthorizationHeader(e.id)??void 0:void 0;case"bearer":return e.auth.token?`Bearer ${e.auth.token}`:void 0;case"api-key":return;default:return}}static async performHandshake(e,t){try{const r=await this.raceWithTimeout(this.getServerInfo(e),t,"Handshake timeout");return this.extractCapabilities(r)}catch(r){return le.warn("[MCPClientFactory] Handshake failed, but connection may still be valid:",r),this.DEFAULT_CAPABILITIES}}static async getServerInfo(e){try{return{tools:(await e.listTools()).tools||[],capabilities:this.DEFAULT_CAPABILITIES}}catch{return le.debug("[MCPClientFactory] Tool listing failed, server may not support tools yet"),{tools:[],capabilities:this.DEFAULT_CAPABILITIES}}}static extractCapabilities(e){return{...this.DEFAULT_CAPABILITIES,...e.tools?{tools:{}}:{}}}static async raceWithTimeout(e,t,r,n){let o,i;const s=new Promise((a,c)=>{o=setTimeout(()=>{c(new Error(r))},t),n&&(i=()=>{clearTimeout(o),c(new Error(`Operation aborted: ${r}`))},n.addEventListener("abort",i))});try{return await Promise.race([e,s])}finally{clearTimeout(o),n&&i&&n.removeEventListener("abort",i)}}static async closeClient(e,t,r){const n=[];try{await e.close()}catch(o){n.push(`Client close error: ${o instanceof Error?o.message:String(o)}`)}try{await t.close()}catch(o){n.push(`Transport close error: ${o instanceof Error?o.message:String(o)}`)}if(r&&!r.killed)try{r.kill("SIGTERM"),await new Promise(o=>{const i=setTimeout(()=>{if(!r.killed){le.warn("[MCPClientFactory] Force killing process");try{r.kill("SIGKILL")}catch(s){le.debug("[MCPClientFactory] Error in force kill:",s)}}o()},5e3);r.on("exit",()=>{clearTimeout(i),o()})})}catch(o){n.push(`Process kill error: ${o instanceof Error?o.message:String(o)}`)}n.length>0&&le.warn("[MCPClientFactory] Errors during client cleanup:",n)}static async testConnection(e,t=5e3){let r,n,o;try{const i=await this.createClient(e,t);if(!i.success)return{success:!1,error:i.error};if(r=i.client,n=i.transport,o=i.process,r)try{await r.listTools()}catch{le.debug("[MCPClientFactory] Tool listing failed during test, but connection may be valid")}return{success:!0,capabilities:i.capabilities}}catch(i){return{success:!1,error:i instanceof Error?i.message:String(i)}}finally{if(r&&n)try{await this.closeClient(r,n,o)}catch(i){le.debug("[MCPClientFactory] Error cleaning up test connection:",i)}}}static validateClientConfig(e){const t=[];if(e.command||t.push("Command is required"),e.transport||t.push("Transport is required"),["stdio","sse","websocket","http"].includes(e.transport)||t.push("Transport must be stdio, sse, websocket, or http"),e.transport==="sse"||e.transport==="websocket"||e.transport==="http")if(!e.url)t.push(`URL is required for ${e.transport} transport`);else try{new URL(e.url)}catch{t.push(`Invalid URL for ${e.transport} transport`)}return e.transport==="stdio"&&(Array.isArray(e.args)||t.push("Args array is required for stdio transport")),{isValid:t.length===0,errors:t}}static getSupportedTransports(){return["stdio","sse","websocket","http"]}static getDefaultCapabilities(){return{...this.DEFAULT_CAPABILITIES}}}}});function skr(e,t){if(t<=0)return"";try{const r=JSON.stringify(e);return typeof r!="string"?"":r.length<=t?r:r.slice(0,Math.max(0,t-1))+"\u2026"}catch{return""}}function y9(e,t=0){if(t>10)return"[...]";if(e==null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>y9(n,t+1));const r={};for(const[n,o]of Object.entries(e))ckr.test(n)?r[n]="[REDACTED]":r[n]=y9(o,t+1);return r}var akr,ckr,qye,lkr,v5n=E({"src/lib/mcp/toolDiscoveryService.ts"(){"use strict";To(),G(),S0e(),Nm(),oh(),st(),tge(),_ue(),Gt(),gr(),qr(),akr=We.mcp,ckr=/^(password|passwd|secret|token|api[_-]?key|apikey|access[_-]?key|authorization|auth|bearer|credential|cookie|session[_-]?id|private[_-]?key|client[_-]?secret|refresh[_-]?token|x-api-key)$/i,qye=Math.max(5e3,Number(process.env.MCP_TOOL_TIMEOUT)||6e4),lkr=class extends On{serverToolStorage=new Map;toolRegistry=new Map;serverTools=new Map;discoveryInProgress=new Set;outputNormalizer;constructor(){super()}setOutputNormalizer(e){this.outputNormalizer=e}async discoverTools(e,t,r=qye,n=()=>!0,o=!1){return wt({name:"mcp.discoverTools",tracer:We.mcp,attributes:{"mcp.server_id":e}},async i=>{const s=Date.now();let a=!1;try{if(!n())throw new Error(`Discovery owner for '${e}' is no longer current`);if(this.discoveryInProgress.has(e))return{success:!1,error:`Discovery already in progress for server: ${e}`,toolCount:0,tools:[],duration:Date.now()-s,serverId:e};this.discoveryInProgress.add(e),a=!0,le.info(`[ToolDiscoveryService] Starting tool discovery for server: ${e}`);const c=()=>this.performToolDiscovery(e,t,r),l=o?await c():await O4.getBreaker(`tool-discovery-${e}`,{failureThreshold:2,resetTimeout:6e4,operationTimeout:r}).execute(c),u=await this.registerDiscoveredTools(e,l,n);i.setAttribute("mcp.tools_discovered",u.length);const d={success:!0,toolCount:u.length,tools:u,duration:Date.now()-s,serverId:e};return this.emit("discoveryCompleted",{serverId:e,toolCount:u.length,duration:d.duration,timestamp:new Date}),le.info(`[ToolDiscoveryService] Discovery completed for ${e}: ${u.length} tools`),d}catch(c){const l=c instanceof Error?c.message:String(c);return i.setStatus({code:Ve.ERROR,message:l}),i.recordException(c instanceof Error?c:new Error(l)),le.error(`[ToolDiscoveryService] Discovery failed for ${e}:`,c),this.emit("discoveryFailed",{serverId:e,error:l,timestamp:new Date}),{success:!1,error:l,toolCount:0,tools:[],duration:Date.now()-s,serverId:e}}finally{a&&this.discoveryInProgress.delete(e)}})}async performToolDiscovery(e,t,r){const n=await this.raceWithTimeout(t.listTools(),r,"Tool discovery timeout");if(!n||!n.tools)throw new Error("No tools returned from server");return le.debug(`[ToolDiscoveryService] Discovered ${n.tools.length} tools from ${e}`),n.tools}async registerDiscoveredTools(e,t,r){const n=[];if(!r())throw new Error(`Discovery owner for '${e}' is no longer current`);this.clearServerTools(e);for(const o of t)try{const i=await this.createToolInfo(e,o);if(!r())throw new Error(`Discovery owner for '${e}' is no longer current`);const s=this.validateTool(i);if(!s.isValid){le.warn(`[ToolDiscoveryService] Skipping invalid tool ${o.name} from ${e}:`,s.errors);continue}s.metadata&&(i.metadata={...i.metadata,...s.metadata});const a=this.createToolKey(e,o.name);this.toolRegistry.set(a,i),this.serverToolStorage.has(e)||this.serverToolStorage.set(e,[]);const c=this.serverToolStorage.get(e);if(!c)throw new Error(`Server tools storage not found for ${e}`);c.find(u=>u.name===o.name)||c.push(i),this.serverTools.has(e)||this.serverTools.set(e,new Set);const l=this.serverTools.get(e);l&&l.add(o.name),n.push(i),this.emit("toolRegistered",{serverId:e,toolName:o.name,toolInfo:i,timestamp:new Date}),le.debug(`[ToolDiscoveryService] Registered tool: ${o.name} from ${e}`)}catch(i){if(!r())throw i;le.error(`[ToolDiscoveryService] Failed to register tool ${o.name} from ${e}:`,i)}if(!r())throw new Error(`Discovery owner for '${e}' is no longer current`);return n}async createToolInfo(e,t){return{name:t.name,description:t.description||"No description provided",serverId:e,inputSchema:t.inputSchema,...t.annotations?{annotations:{...t.annotations}}:{},isAvailable:!0,stats:{totalCalls:0,successfulCalls:0,failedCalls:0,averageExecutionTime:0,lastExecutionTime:0},metadata:{category:this.inferToolCategory(t),version:"1.0.0",deprecated:!1}}}inferToolCategory(e){const t=e.name.toLowerCase(),r=(e.description||"").toLowerCase();return t.includes("git")||r.includes("git")?"version-control":t.includes("file")||t.includes("read")||t.includes("write")?"file-system":t.includes("api")||t.includes("http")||t.includes("request")?"api":t.includes("data")||t.includes("query")||t.includes("search")?"data":t.includes("auth")||t.includes("login")||t.includes("token")?"authentication":t.includes("deploy")||t.includes("build")||t.includes("ci")?"deployment":"general"}validateTool(e){const t=[],r=[],n=h4(e.name);n&&t.push(n.message);const o=OU(e.description);if(o&&r.push(o.message),e.serverId||t.push("Server ID is required"),e.inputSchema)try{JSON.stringify(e.inputSchema)}catch{t.push("Input schema is not valid JSON")}const i={category:typeof e.metadata?.category=="string"?e.metadata.category:"general",complexity:this.inferComplexity(e),requiresAuth:this.inferAuthRequirement(e),isDeprecated:typeof e.metadata?.deprecated=="boolean"?e.metadata.deprecated:!1};return{isValid:t.length===0,errors:t,warnings:r,metadata:i}}inferComplexity(e){const t=e.inputSchema;if(!t||!t.properties)return"simple";const r=Object.keys(t.properties).length;return r<=2?"simple":r<=5?"moderate":"complex"}inferAuthRequirement(e){const t=e.name.toLowerCase(),r=e.description.toLowerCase();return t.includes("auth")||t.includes("login")||t.includes("token")||r.includes("authentication")||r.includes("credentials")||r.includes("permission")}async executeTool(e,t,r,n,o={}){const i=Date.now();try{const s=this.createToolKey(t,e),a=this.toolRegistry.get(s);if(!a)throw new Error(`Tool '${e}' not found for server '${t}'`);if(!a.isAvailable)throw new Error(`Tool '${e}' is not available`);let c=n;o.validateInput!==!1&&(c=this.validateToolParameters(a,n)),le.debug(`[ToolDiscoveryService] Executing tool: ${e} on ${t}`,{parameters:c});const l=o.timeout||qye,u=O4.getBreaker(`tool-execution-${t}-${e}`,{failureThreshold:3,resetTimeout:3e4,operationTimeout:l});let d=!1;const p=await u.execute(async h=>akr.startActiveSpan("mcp.callTool",{kind:un.CLIENT,attributes:{"mcp.server_id":t,"mcp.tool_name":e,"mcp.timeout_ms":l,"ai.tool.name":e,"mcp.request":skr({name:e,arguments:y9(c)},2048)}},async f=>{try{const y=l,v=await Je(r.callTool({name:e,arguments:c},void 0,{timeout:l,...o.signal&&{signal:o.signal}}),y,new Error(`Tool execution timeout: ${e}`)),_=v;if(_&&_.isError===!0){const k=CF(_);f.setStatus({code:Ve.ERROR,message:k||`Tool ${e} returned isError`}),d=!0,h(k||`Tool ${e} returned isError`)}else f.setStatus({code:Ve.OK});let w=v,T=v;if(this.outputNormalizer)try{const k=await this.outputNormalizer.normalize(v,{toolName:e,serverId:t});f.setAttribute("mcp.output.strategy",k.isExternalized?"externalize":"inline"),k.isExternalized&&f.setAttribute("mcp.output.original_bytes",k.originalBytes),w=k.result,T=k.result}catch(k){le.warn(`[ToolDiscoveryService] McpOutputNormalizer failed for ${e}: ${k instanceof Error?k.message:String(k)} \u2014 returning raw result`)}return f.setAttribute("mcp.response",skr(y9(w),2048)),T}catch(y){throw f.setStatus({code:Ve.ERROR,message:y.message}),f.recordException(y),y}finally{f.end()}}),{isCancelled:()=>o.signal?.aborted===!0}),m=Date.now()-i;return this.updateToolStats(s,!d,m),o.validateOutput!==!1&&this.validateToolOutput(p),le.debug(`[ToolDiscoveryService] Tool execution completed: ${e}`,{duration:m,hasContent:!!p?.content}),{success:!0,data:p,isErrorResult:d,duration:m,metadata:{toolName:e,serverId:t,timestamp:Date.now()}}}catch(s){const a=Date.now()-i,c=s instanceof Error?s.message:String(s),l=this.createToolKey(t,e);if(this.updateToolStats(l,!1,a),o.signal?.aborted)throw s;return s instanceof ef?(le.warn(`[ToolDiscoveryService] Tool blocked by circuit breaker: ${e} on ${t}`,{breakerState:s.breakerState,retryAfter:s.retryAfter,retryAfterMs:s.retryAfterMs,failureCount:s.failureCount}),{success:!1,error:s.message,data:{isError:!0,content:[{type:"text",text:`TOOL TEMPORARILY UNAVAILABLE: "${e}" has been disabled after ${s.failureCount} failures. This is a circuit breaker protection \u2014 do NOT retry this tool. It will become available again after ${Math.ceil(s.retryAfterMs/1e3)} seconds (at ${s.retryAfter}). Instead, inform the user that the operation failed and suggest trying again later.`}]},duration:a,metadata:{toolName:e,serverId:t,timestamp:Date.now(),circuitBreaker:{state:s.breakerState,retryAfter:s.retryAfter,retryAfterMs:s.retryAfterMs,failureCount:s.failureCount}}}):(le.error(`[ToolDiscoveryService] Tool execution failed: ${e}`,s),{success:!1,error:c,duration:a,metadata:{toolName:e,serverId:t,timestamp:Date.now()}})}}validateToolParameters(e,t){if(!e.inputSchema)return t;const r=e.inputSchema,n=r.properties&&typeof r.properties=="object"?r.properties:{},o=Array.isArray(r.required)?r.required.filter(c=>typeof c=="string"):[],i=()=>Object.entries(n).map(([c,l])=>`${c}${o.includes(c)?"":"?"}: ${l.type??"any"}`).join(", "),s=o.filter(c=>!(c in t));if(s.length>0)throw new Error(`Missing required parameter${s.length>1?"s":""}: ${s.join(", ")}. Expected arguments: { ${i()} }; received keys: [${Object.keys(t).join(", ")}]`);let a;for(const[c,l]of Object.entries(n))if(c in t){const u=t[c],d=Qfe(u,l);d!==u&&(le.debug(`[ToolDiscoveryService] Coerced parameter '${c}' for tool '${e.name}': ${typeof u} \u2192 ${typeof d}`),a=a??{...t},a[c]=d),this.validateParameterType(c,a?a[c]:u,l)}return a??t}validateParameterType(e,t,r){if(!r.type)return;const n=r.type,o=typeof t;switch(n){case"string":if(o!=="string")throw new Error(`Parameter '${e}' must be a string, got ${o}`);break;case"number":if(o!=="number")throw new Error(`Parameter '${e}' must be a number, got ${o}`);break;case"integer":if(o!=="number"||!Number.isInteger(t))throw new Error(`Parameter '${e}' must be an integer, got ${o==="number"?String(t):o}`);break;case"boolean":if(o!=="boolean")throw new Error(`Parameter '${e}' must be a boolean, got ${o}`);break;case"array":if(!Array.isArray(t))throw new Error(`Parameter '${e}' must be an array, got ${o}`);break;case"object":if(o!=="object"||t===null||Array.isArray(t))throw new Error(`Parameter '${e}' must be an object, got ${o}`);break}}validateToolOutput(e){if(Ymn(e)){le.debug("[ToolDiscoveryService] Tool returned null/undefined, treating as empty response");return}le.debug("[ToolDiscoveryService] Tool response received",{type:typeof e,isArray:Array.isArray(e),isObject:b3(e),hasKeys:b3(e)?Object.keys(e).length:0,fullResponse:e})}updateToolStats(e,t,r){const n=this.toolRegistry.get(e);if(!n)return;n.stats.totalCalls++,n.lastCalled=new Date,n.stats.lastExecutionTime=r,t?n.stats.successfulCalls++:n.stats.failedCalls++;const o=n.stats.averageExecutionTime*(n.stats.totalCalls-1)+r;n.stats.averageExecutionTime=o/n.stats.totalCalls}getTool(e,t){const r=this.createToolKey(t,e);return this.toolRegistry.get(r)}getServerTools(e){const t=this.serverToolStorage.get(e);if(t)return t.map(o=>({name:o.name,description:o.description,serverId:e,inputSchema:o.inputSchema,...o.annotations?{annotations:{...o.annotations}}:{},isAvailable:!0,stats:{totalCalls:0,successfulCalls:0,failedCalls:0,averageExecutionTime:0,lastExecutionTime:0}}));const r=[],n=this.serverTools.get(e);if(n)for(const o of n){const i=this.createToolKey(e,o),s=this.toolRegistry.get(i);s&&r.push(s)}return r}getAllTools(){const e=[];for(const[r,n]of this.serverToolStorage.entries())for(const o of n)e.push({name:o.name,description:o.description,serverId:r,inputSchema:o.inputSchema,...o.annotations?{annotations:{...o.annotations}}:{},isAvailable:!0,stats:{totalCalls:0,successfulCalls:0,failedCalls:0,averageExecutionTime:0,lastExecutionTime:0}});const t=Array.from(this.toolRegistry.values()).filter(r=>!e.some(n=>n.name===r.name&&n.serverId===r.serverId));return[...e,...t]}clearServerTools(e){const t=this.serverToolStorage.get(e);if(t){for(const n of t)this.emit("toolUnregistered",{serverId:e,toolName:n.name,timestamp:new Date});this.serverToolStorage.delete(e)}const r=this.serverTools.get(e);if(r){for(const n of r){const o=this.createToolKey(e,n);this.toolRegistry.delete(o),(!t||!t.find(i=>i.name===n))&&this.emit("toolUnregistered",{serverId:e,toolName:n,timestamp:new Date})}this.serverTools.delete(e)}le.debug(`[ToolDiscoveryService] Cleared tools for server: ${e}`)}updateToolAvailability(e,t,r){const n=this.createToolKey(t,e),o=this.toolRegistry.get(n);o&&(o.isAvailable=r,le.debug(`[ToolDiscoveryService] Updated availability for ${e}: ${r}`))}createToolKey(e,t){return`${e}:${t}`}async raceWithTimeout(e,t,r){let n;const o=new Promise((i,s)=>{n=setTimeout(()=>{s(new Error(r))},t)});try{return await Promise.race([e,o])}finally{clearTimeout(n)}}destroy(){le.debug("[ToolDiscoveryService] Starting cleanup..."),this.removeAllListeners(),this.serverToolStorage.clear(),this.toolRegistry.clear(),this.serverTools.clear(),this.discoveryInProgress.clear(),le.debug("[ToolDiscoveryService] Destroyed and cleaned up")}resetStatistics(){for(const e of this.toolRegistry.values())e.stats={totalCalls:0,successfulCalls:0,failedCalls:0,averageExecutionTime:0,lastExecutionTime:0},e.lastCalled=void 0;le.debug("[ToolDiscoveryService] Statistics reset for all tools")}getListenerCount(){const e=["discoveryCompleted","discoveryFailed","toolRegistered","toolUnregistered"];let t=0;for(const r of e)t+=this.listenerCount(r);return t}getStatistics(){const e={},t={};let r=0,n=0;for(const o of this.toolRegistry.values()){e[o.serverId]=(e[o.serverId]||0)+1;const i=typeof o.metadata?.category=="string"?o.metadata.category:"unknown";t[i]=(t[i]||0)+1,o.isAvailable?r++:n++}return{totalTools:this.toolRegistry.size,availableTools:r,unavailableTools:n,totalServers:this.serverTools.size,toolsByServer:e,toolsByCategory:t}}}}}),ukr,_5n=E({"src/lib/mcp/registry.ts"(){"use strict";G(),ukr=class{plugins=new Map;register(e){this.plugins.set(e.metadata.name,e),Vr.debug(`Registered plugin: ${e.metadata.name}`)}unregister(e){const t=this.plugins.delete(e);return t&&Vr.debug(`Unregistered plugin: ${e}`),t}get(e){return this.plugins.get(e)}list(){return Array.from(this.plugins.values())}has(e){return this.plugins.has(e)}clear(){this.plugins.clear(),Vr.info("Registry cleared")}async registerServer(e,t,r){const n={metadata:{name:e,description:typeof t=="object"&&t&&t.description||"No description"},tools:typeof t=="object"&&t?t.tools:{},configuration:typeof t=="object"&&t?t:{}};this.register(n)}async executeTool(e,t,r){return Vr.info(`Executing tool: ${e}`),{result:`Mock execution of ${e}`,args:t}}async listTools(e){return this.list().map(r=>({name:r.metadata.name,description:r.metadata.description||"No description",serverId:r.metadata.name,category:"general"}))}registerServerSync(e){this.register(e)}executeToolSync(e,t){return Vr.info(`Executing tool (sync): ${e}`),{result:`Mock execution of ${e}`,args:t}}listToolsSync(){return this.list().map(t=>({name:t.metadata.name,description:t.metadata.description||"No description"}))}listServers(){return Array.from(this.plugins.keys())}}}});function oc(e){return e.existingCategory&&["external","in-memory","built-in","user-defined"].includes(e.existingCategory)?e.existingCategory:e.isCustomTool?"user-defined":e.isBuiltIn?"built-in":e.isExternal?"external":e.serverId?.startsWith("custom-tool-")?"user-defined":e.serverId?.includes("external")?"external":e.serverId==="direct"?"built-in":"in-memory"}function w5n(e,t){switch(t){case"external":return`External MCP server: ${e}`;case"built-in":return`Built-in tool server: ${e}`;case"custom":case"user-defined":return`Custom tool server: ${e}`;case"in-memory":return`In-memory MCP server: ${e}`;default:return e}}function dkr(e){const t=e.id||`server-${e.name}`,r=e.category||oc({isCustomTool:e.isCustomTool,isExternal:e.isExternal,isBuiltIn:e.isBuiltIn,serverId:t}),n=e.tools||(e.tool?[e.tool]:[]);return{id:t,name:e.name,transport:e.transport||"stdio",status:e.status||"connected",tools:n,description:e.description||w5n(e.name,r),...e.command&&{command:e.command},...e.args&&{args:e.args},...e.env&&{env:e.env},metadata:{category:r,toolCount:n.length}}}function b5n(e,t,r,n,o){const i=dkr({id:`custom-tool-${e}`,name:e,tool:{name:e,description:t.description||e,inputSchema:t.inputSchema||{},execute:t.execute},isCustomTool:!0});return i.metadata&&(r!==void 0&&(i.metadata.toolTimeoutMs=r),n!==void 0&&(i.metadata.toolMaxRetries=n),o!==void 0&&(i.metadata.toolTotalTimeoutMs=o)),i}var Gye=E({"src/lib/utils/mcpDefaults.ts"(){"use strict"}}),pkr,T5n=E({"src/lib/mcp/flexibleToolValidator.ts"(){"use strict";G(),pkr=class{static MAX_TOOL_NAME_LENGTH=1e3;static MIN_TOOL_NAME_LENGTH=1;static validateToolName(e){const t=[];if(!e||typeof e!="string")return{isValid:!1,error:"Tool name is required and must be a string"};if(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/.test(e))return{isValid:!1,error:"Tool name contains control characters that could break systems"};const n=e.trim();return n.length===0?{isValid:!1,error:"Tool name cannot be empty or whitespace-only"}:n.length<this.MIN_TOOL_NAME_LENGTH?{isValid:!1,error:`Tool name must be at least ${this.MIN_TOOL_NAME_LENGTH} character long`}:n.length>this.MAX_TOOL_NAME_LENGTH?{isValid:!1,error:`Tool name exceeds maximum length of ${this.MAX_TOOL_NAME_LENGTH} characters`}:(n!==e&&t.push("Tool name has leading/trailing whitespace (will be trimmed)"),n.length>200&&t.push("Tool name is unusually long but allowed"),Vr.debug(`\u2705 FlexibleToolValidator: Tool '${e}' passed universal safety checks`),{isValid:!0,warnings:t.length>0?t:void 0})}static validateToolInfo(e,t){const r=this.validateToolName(e);if(!r.isValid)return r;const n=[...r.warnings||[]];return t.description&&typeof t.description!="string"?{isValid:!1,error:"Tool description must be a string if provided"}:t.serverId&&typeof t.serverId!="string"?{isValid:!1,error:"Tool serverId must be a string if provided"}:(Vr.debug(`\u2705 FlexibleToolValidator: Tool info for '${e}' passed validation`),{isValid:!0,warnings:n.length>0?n:void 0})}static getValidationInfo(){return{philosophy:"Maximum flexibility with universal safety only - following Anthropic's MCP specification",checks:["Empty or whitespace-only names","Excessive length (over 1000 characters)","Control characters that could break systems"],whatIsAllowed:["Dots (github.create_repo, filesystem.read_file)","Hyphens and underscores (my-tool, user_helper)","Numbers (tool1, my_tool_v2)","Unicode characters (\u{1F680}_tool, caf\xE9_manager)","Mixed case (createRepo, ReadFile)","Long descriptive names (enterprise_database_connection_manager)","Any legitimate MCP tool naming pattern"],examples:{valid:["github.create_repo","filesystem.read_file","my-custom-tool","user_helper","tool1","\u{1F680}_rocket_tool","enterprise.database.connection.manager","UPPERCASE_TOOL","mixed_Case.Tool-Name_123"],invalid:[""," ","tool\0","a".repeat(1001)]}}}}}}),v9,jye,Vye=E({"src/lib/mcp/toolRegistry.ts"(){"use strict";_5n(),G(),tr(),S3(),yL(),Vte(),Ps(),Gye(),T5n(),st(),wb(),_T(),pu(),Gt(),lS(),v9=class extends ukr{tools=new Map;toolImplementations=new Map;toolExecutionStats=new Map;builtInServerInfos=[];hitlManager;unbatchableTools=new Set;fileToolRootResolver=()=>vL({});constructor(){super(),oZ()||this.registerDirectTools()}setHITLManager(e){this.hitlManager=e,e&&e.isEnabled()?Vr.info("HITL safety mechanisms enabled for tool execution"):Vr.debug("HITL safety mechanisms disabled or not configured")}getHITLManager(){return this.hitlManager}setToolUnbatchable(e,t){t?this.unbatchableTools.add(e):this.unbatchableTools.delete(e)}isToolUnbatchable(e){return this.unbatchableTools.has(e)}setFileToolRootResolver(e){this.fileToolRootResolver=e}directToolFor(e,t,r){const n=Gte(r)??this.fileToolRootResolver();return n.roots===null?t:Fte(n)[e]??t}registerDirectTools(){Vr.debug("Auto-registering direct tools...");for(const[e,t]of Object.entries(Kb)){if(!t){Vr.warn(`Skipping undefined tool during registration: ${e}`);continue}const r=`direct.${e}`,n=$i(t.inputSchema),o={name:e,description:t.description||`Direct tool: ${e}`,inputSchema:n,serverId:"direct",category:oc({isBuiltIn:!0,serverId:"direct"})};this.tools.set(r,o),this.toolImplementations.set(r,{execute:async(i,s)=>{try{return{success:!0,data:await this.directToolFor(e,t,s).execute(i,{toolCallId:s?.sessionId||"unknown",messages:[]}),metadata:{toolName:e,serverId:"direct",executionTime:0}}}catch(a){return{success:!1,error:a instanceof Error?a.message:String(a),metadata:{toolName:e,serverId:"direct",executionTime:0}}}},description:t.description,inputSchema:n}),Vr.debug(`Registered direct tool: ${e} as ${r}`)}Vr.debug(`Auto-registered ${Object.keys(Kb).length} direct tools`)}async registerServer(e,t,r){let n;if(typeof e=="string"){const c=e;n=dkr({id:c,name:c,tools:[],isExternal:!0})}else n=e;const o=n.id,i={};for(const c of n.tools)i[c.name]={execute:c.execute||(async()=>{throw new Error(`Tool ${c.name} has no execute function`)}),description:c.description,inputSchema:c.inputSchema,category:oc({existingCategory:n.metadata?.category,serverId:n.id})};const s={metadata:{name:n.name,description:n.description,category:oc({existingCategory:n.metadata?.category,serverId:n.id})},tools:i,configuration:{}};this.plugins.set(o,s),Vr.debug(`Registered plugin: ${s.metadata.name}`);const a=n.tools;for(const c of a){const u=o.startsWith("custom-tool-")?c.name:`${o}.${c.name}`,d=n.metadata?.toolTimeoutMs,p=n.metadata?.toolMaxRetries,m=n.metadata?.toolTotalTimeoutMs,h={name:c.name,description:c.description,inputSchema:c.inputSchema,outputSchema:void 0,serverId:o,category:oc({existingCategory:n.metadata?.category,serverId:n.id}),permissions:[],...d!==void 0&&{timeoutMs:d},...p!==void 0&&{maxRetries:p},...m!==void 0&&{totalTimeoutMs:m}};this.tools.set(u,h),this.toolImplementations.set(u,{execute:c.execute||(async()=>{throw new Error(`Tool ${c.name} has no execute function`)}),description:c.description,inputSchema:c.inputSchema,category:oc({existingCategory:n.metadata?.category,serverId:n.id}),...d!==void 0&&{timeoutMs:d},...p!==void 0&&{maxRetries:p},...m!==void 0&&{totalTimeoutMs:m}})}if(a.length>0){const c=oc({existingCategory:n.metadata?.category,serverId:n.id});c==="in-memory"&&(this.builtInServerInfos.push(n),Vr.debug(`Added ${c} server to builtInServerInfos: ${o} with ${a.length} tools`))}}async executeTool(e,t,r){const n=Date.now();let o;const i=this.tools.get(e);if(i)o=i.serverId;else for(const s of this.tools.values())if(s.name===e){o=s.serverId;break}return wt({name:"tool.registry.execute",tracer:We.mcp,attributes:{"tool.name":e,[Ge.MCP_SERVER_ID]:o||"builtin",[Ge.NL_INTERNAL]:!0}},async s=>{try{Vr.info(`\u{1F527} [TOOL_EXECUTION] Starting execution: ${e}`,{hasArgs:t!==void 0,hasContext:r!==void 0,sessionId:r?.sessionId});const{tool:a,toolId:c}=this.resolveToolExecutionTarget(e);if(!a)throw new Error(`Tool '${e}' not found in registry`);const l=a.serverId||"unknown",u=l==="direct"?"builtin":l.startsWith("custom-tool-")?"custom":"mcp";s.setAttribute("tool.type",u),s.setAttribute(Ge.MCP_SERVER_ID,l);const d=this.createExecutionContext(r),p=this.toolImplementations.get(c);if(Vr.debug(`Looking for tool '${e}' (toolId: '${c}'), found: ${!!p}, type: ${typeof p?.execute}`),Vr.debug("Available tools:",Array.from(this.toolImplementations.keys())),!p||typeof p?.execute!="function")throw new Error(`Tool '${e}' implementation not found or not executable`);let m;try{m=JSON.stringify(t).slice(0,4096)}catch{m="[unserializable]"}s.setAttribute("tool.arguments_present",t!==void 0),s.setAttribute("tool.arguments_size",m.length);const h=await this.confirmToolCall(e,t,a.serverId,d,s);G0(d.abortSignal),Vr.debug(`Executing tool '${e}' with args:`,h);const f=await p.execute(h,d);let y;if(f&&typeof f=="object"&&"success"in f&&typeof f.success=="boolean"){const w=f;y={...w,usage:{...w.usage||{},executionTime:Date.now()-n},metadata:{...w.metadata||{},toolName:e,serverId:a.serverId,sessionId:d.sessionId,executionTime:Date.now()-n}},nI(f)&&rI(y)}else y={success:!0,data:f,usage:{executionTime:Date.now()-n},metadata:{toolName:e,serverId:a.serverId,sessionId:d.sessionId,executionTime:Date.now()-n}};const v=Date.now()-n;this.updateStats(e,v);let _;try{_=JSON.stringify(y.data)??"undefined"}catch{_="[unserializable]"}return s.setAttribute("tool.result_length",_.length),s.setAttribute("tool.success",!0),Vr.debug(`Tool '${e}' executed successfully in ${v}ms`),y}catch(a){a instanceof nu?Vr.info(`Tool '${e}' refused by its HITL confirmation: ${a.message}`):cr(a)?Vr.info(`Tool '${e}' stopped by its signal`):Vr.error(`Tool execution failed: ${e}`,a),s.setAttribute("tool.success",!1);const c=a instanceof Error?a.message:String(a);if(c.includes("not found in registry")||c.includes("not executable"))throw a;s.setStatus({code:Ve.ERROR,message:c}),a instanceof Error&&s.recordException(a);const l={success:!1,data:null,error:a instanceof Error?a.message:String(a),usage:{executionTime:Date.now()-n},metadata:{toolName:e,sessionId:r?.sessionId}};return a instanceof nu?rI(l):l}})}async listTools(e){const t=new Map;for(const o of this.tools.values()){const i=`${o.serverId||"unknown"}.${o.name}`;t.has(i)||t.set(i,o)}let r=Array.from(t.values()),n;return e&&("sessionId"in e||"userId"in e?n=void 0:n=e),n&&(n.category&&(r=r.filter(o=>o.category===n.category)),n.serverId&&(r=r.filter(o=>o.serverId===n.serverId)),n.serverCategory&&(r=r.filter(o=>this.get(o.serverId||"")?.metadata?.category===n.serverCategory)),n.permissions&&n.permissions.length>0&&(r=r.filter(o=>{const i=o.permissions||[];return n.permissions?.some(s=>i.includes(s))??!1}))),Vr.debug(`Listed ${r.length} unique tools (${n?"filtered":"unfiltered"})`),r}resolveToolExecutionTarget(e){let t=this.tools.get(e);Vr.info(`\u{1F50D} [TOOL_LOOKUP] Direct lookup result for '${e}':`,!!t);let r=e;if(!t){const n=Array.from(this.tools.entries()).filter(([,o])=>o.name===e);if(n.length>1)throw Te.toolExecutionFailed(e,new Error(`Ambiguous tool name '${e}'. Use fully-qualified name 'serverId.${e}'.`));n.length===1&&([r,t]=n[0])}return{tool:t,toolId:r}}createExecutionContext(e){let t;try{t=aS()?.user?.id}catch{}return{...e,sessionId:e?.sessionId??ht(),userId:e?.userId??t}}async confirmToolCall(e,t,r,n,o){const i=await K6(this.hitlManager,e,t,n.hitlState,{serverId:r,sessionId:n.sessionId,userId:n.userId,signal:n.abortSignal},{log:s=>Vr.info(s),span:o});if(!i.run)throw i.error;return i.args}getToolInfo(e){let t=this.tools.get(e);if(!t){for(const r of this.tools.values())if(r.name===e){t=r;break}}if(t)return{tool:t,server:{id:t.serverId||"unknown-server"}}}updateStats(e,t){const r=this.toolExecutionStats.get(e)||{count:0,totalTime:0};r.count+=1,r.totalTime+=t,this.toolExecutionStats.set(e,r)}getExecutionStats(){const e={};for(const[t,r]of this.toolExecutionStats.entries())e[t]={count:r.count,totalTime:r.totalTime,averageTime:r.totalTime/r.count};return e}clearStats(){this.toolExecutionStats.clear()}getBuiltInServerInfos(){return this.builtInServerInfos}getToolsByCategory(e){const t=new Map;for(const[r,n]of this.tools.entries())n.category===e&&!t.has(r)&&t.set(r,n);return Array.from(t.values())}getAvailableTools(e){const t=Array.from(this.tools.values()),r=[],n=[];for(const o of t){const i=`${o.serverId||"unknown"}.${o.name}`,s=e.get(i);s&&s.getState()==="open"?r.push(o.name):n.push(o)}return{tools:n,unavailableTools:r}}hasTool(e){if(this.tools.has(e))return!0;for(const t of this.tools.values())if(t.name===e)return!0;return!1}async registerTool(e,t,r){Vr.debug(`Registering tool: ${e}`);const n=pkr.validateToolInfo(e,{description:t.description,serverId:t.serverId});if(!n.isValid)throw Vr.error(`Tool registration failed for ${e}: ${n.error}`),new Error(`Tool validation failed: ${n.error}`);n.warnings&&n.warnings.length>0&&Vr.warn(`Tool registration warnings for ${e}:`,n.warnings),Vr.debug(`\u2705 Tool '${e}' passed flexible validation - registration proceeding`),this.tools.set(e,t),this.toolImplementations.set(e,r),Vr.debug(`Successfully registered tool: ${e}`)}removeTool(e){let t=!1;if(this.tools.has(e))this.tools.delete(e),this.toolImplementations.delete(e),this.toolExecutionStats.delete(e),Vr.info(`Removed tool: ${e}`),t=!0;else for(const[r,n]of Array.from(this.tools.entries()))n.name===e&&(this.tools.delete(r),this.toolImplementations.delete(r),this.toolExecutionStats.delete(r),Vr.info(`Removed tool: ${r}`),t=!0);return t}getToolCount(){return this.tools.size}getStats(){const e=this.list(),t=Array.from(this.tools.values()),r={};for(const o of e){const i=o.metadata?.category||"uncategorized";r[i]=(r[i]||0)+1}const n={};for(const o of t){const i=o.category||"uncategorized";n[i]=(n[i]||0)+1}return{totalServers:e.length,totalTools:t.length,serversByCategory:r,toolsByCategory:n,executionStats:this.getExecutionStats()}}unregisterServer(e){const t=[];for(const[i,s]of this.tools.entries())s.serverId===e&&(this.tools.delete(i),this.toolImplementations.delete(i),this.toolExecutionStats.delete(i),this.unbatchableTools.delete(i),t.push(i));const r=this.builtInServerInfos.length;this.builtInServerInfos=this.builtInServerInfos.filter(i=>i.id!==e);const n=r>this.builtInServerInfos.length,o=this.unregister(e);return Vr.info(`Unregistered server ${e}, removed ${t.length} tools${n?" and server from builtInServerInfos":""}`),o}},jye=new v9}});function _9(e,t){if(typeof e=="string")return e.replace(gkr,(r,n)=>{const o=n.trim();if(!vkr.test(o))return le.warn(`[ExternalServerManager] ${t}: "${r}" is not a valid environment variable reference (names must match ^[A-Z][A-Z0-9_]*$); left as written`),r;const i=process.env[o];return i===void 0?(le.warn(`[ExternalServerManager] ${t}: environment variable ${o} is not defined, using empty string`),""):i});if(Array.isArray(e))return e.map(r=>_9(r,t));if(lr(e)){const r={};for(const[n,o]of Object.entries(e))r[n]=_9(o,t);return r}return e}function w9(e,t){if(typeof e=="string"){ykr.test(e)&&le.warn(`[ExternalServerManager] ${t} contains a \${VAR} reference; environment variables are never expanded in ${t} (only in env and args). The value is used as written.`);return}if(Array.isArray(e)){for(const r of e)w9(r,t);return}if(lr(e))for(const[r,n]of Object.entries(e))w9(n,`${t}.${r}`)}function mkr(e){const t=e instanceof Error?e.message:String(e);return _kr.test(t)}function E5n(e){if(!e||e.length===0)return e;const t=[...e];for(let r=0;r<t.length;r++){const n=t[r].indexOf("=");if(n!==-1){const o=t[r].substring(0,n);Xye.test(o)&&(t[r]=`${o}=[REDACTED]`);continue}Xye.test(t[r])&&r+1<t.length&&!t[r+1].startsWith("--")&&(t[r+1]="[REDACTED]",r++)}return t}function Hye(e){return b3(e)?Object.values(e).every(r=>r===null||typeof r=="string"||typeof r=="number"||typeof r=="boolean"?!0:Array.isArray(r)?r.every(n=>Hye(n)||typeof n=="string"||typeof n=="number"||typeof n=="boolean"||n===null):lr(r)?Hye(r):!1):!1}function b9(e){return Hye(e)?e:void 0}function S5n(e){if(!lr(e))return!1;const t=e;if(t.blockedTools!==void 0&&(!Array.isArray(t.blockedTools)||!t.blockedTools.every(o=>typeof o=="string")))return!1;const r=typeof t.command=="string",n=typeof t.url=="string";return!r&&!n?!1:(t.command===void 0||typeof t.command=="string")&&(t.args===void 0||Array.isArray(t.args))&&(t.env===void 0||lr(t.env))&&(t.transport===void 0||typeof t.transport=="string")&&(t.timeout===void 0||typeof t.timeout=="number")&&(t.retries===void 0||typeof t.retries=="number")&&(t.healthCheckInterval===void 0||typeof t.healthCheckInterval=="number")&&(t.autoRestart===void 0||typeof t.autoRestart=="boolean")&&(t.cwd===void 0||typeof t.cwd=="string")&&(t.url===void 0||typeof t.url=="string")&&(t.headers===void 0||lr(t.headers))&&(t.httpOptions===void 0||lr(t.httpOptions))&&(t.retryConfig===void 0||lr(t.retryConfig))&&(t.rateLimiting===void 0||lr(t.rateLimiting))&&(t.inheritParentEnv===void 0||typeof t.inheritParentEnv=="boolean")&&(t.allowPrivateNetwork===void 0||typeof t.allowPrivateNetwork=="boolean")&&(t.metadata===void 0||lr(t.metadata))}function hkr(e,t){if(!S5n(t))throw new Error(`Invalid server config for ${e}: missing required properties or wrong types`);return t.headers!==void 0&&w9(t.headers,`${e}.headers`),t.url!==void 0&&w9(t.url,`${e}.url`),{id:e,name:e,description:typeof t.description=="string"?t.description:`External MCP server: ${e}`,transport:typeof t.transport=="string"?t.transport:"stdio",status:"initializing",tools:[],command:typeof t.command=="string"?t.command:void 0,args:Array.isArray(t.args)?_9(t.args.map(r=>String(r)),`${e}.args`):[],env:lr(t.env)?_9(t.env,`${e}.env`):{},inheritParentEnv:typeof t.inheritParentEnv=="boolean"?t.inheritParentEnv:void 0,allowPrivateNetwork:typeof t.allowPrivateNetwork=="boolean"?t.allowPrivateNetwork:void 0,timeout:typeof t.timeout=="number"?t.timeout:void 0,retries:typeof t.retries=="number"?t.retries:void 0,healthCheckInterval:typeof t.healthCheckInterval=="number"?t.healthCheckInterval:void 0,autoRestart:typeof t.autoRestart=="boolean"?t.autoRestart:void 0,cwd:typeof t.cwd=="string"?t.cwd:void 0,url:typeof t.url=="string"?t.url:void 0,headers:lr(t.headers)?t.headers:void 0,fetch:fkr(t.fetch),httpOptions:lr(t.httpOptions)?t.httpOptions:void 0,retryConfig:lr(t.retryConfig)?t.retryConfig:void 0,rateLimiting:lr(t.rateLimiting)?t.rateLimiting:void 0,blockedTools:Array.isArray(t.blockedTools)?t.blockedTools:void 0,metadata:b9(t.metadata)}}var Wye,fkr,gkr,ykr,vkr,_kr,Kye,Jye,Xye,T9,Yye,Zye,wkr,bkr,Tkr,E9,Ekr,Qye,Skr=E({"src/lib/mcp/externalServerManager.ts"(){"use strict";To(),G(),zye(),v5n(),Vye(),wb(),_T(),st(),Gye(),Nm(),Ffe(),gr(),Gt(),process.stdin&&typeof process.stdin.unref=="function"&&(process.stdin.listenerCount("data")>0||process.stdin.listenerCount("readable")>0||process.stdin.unref(),process.stdin.prependListener("newListener",t=>{(t==="data"||t==="readable")&&process.stdin.ref()})),Wye=e=>typeof e=="function",fkr=e=>{if(e!=null){if(!Wye(e))throw new Error("MCP fetch hook must be a function");return e}},gkr=/\$\{([^}]*)\}/g,ykr=/\$\{[^}]*\}/,vkr=/^[A-Z][A-Z0-9_]*$/,_kr=/^Not connected$|MCP error -32000: Connection closed/,Kye=class extends Error{constructor(e,t,r){super(`Server '${e}' discovered ${t} tool(s), below the configured minTools=${r}`),this.serverId=e,this.toolsDiscovered=t,this.minTools=r,this.name="InsufficientToolsError"}serverId;toolsDiscovered;minTools;readiness="insufficient_tools"},Jye=2,Xye=/^--(api-key|token|secret|password|key|figma-api-key|access-token|auth|credential)$/i,T9=new Set,Yye=!1,Zye=async()=>{await Promise.all(Array.from(T9).map(e=>e.shutdown().catch(t=>{le.error("[ExternalServerManager] Error during process-exit cleanup:",t)})))},wkr=()=>{Zye()},bkr=Symbol.for("signal-exit emitter"),Tkr=()=>{const t=globalThis[bkr]?.count;return typeof t=="number"&&t>0?t:0},E9=e=>{const t=process.listenerCount(e)-Tkr()>1;Zye().finally(()=>{t||(process.removeListener(e,E9),g9(),process.kill(process.pid,e))})},Ekr=e=>{T9.add(e),Yye||(Yye=!0,process.prependListener("SIGINT",E9),process.prependListener("SIGTERM",E9),process.on("beforeExit",wkr))},Qye=class extends On{servers=new Map;config;isShuttingDown=!1;healthChecksInFlight=new Set;inFlightToolCalls=new Map;unresponsiveChecks=new Map;consecutiveFailures=new Map;retryDeadlines=new Map;lastHealth=new Map;lifecycleStates=new Map;closedClients=new WeakSet;toolDiscovery;enableMainRegistryIntegration;hitlManager;fallbackHITLManager;constructor(e={},t={}){super();const r=Math.max(5e3,Number(process.env.MCP_CLIENT_TIMEOUT)||6e4);this.config={maxServers:e.maxServers??10,defaultTimeout:e.defaultTimeout??r,defaultHealthCheckInterval:e.defaultHealthCheckInterval??3e4,enableAutoRestart:e.enableAutoRestart??!0,maxRestartAttempts:e.maxRestartAttempts??3,restartBackoffMultiplier:e.restartBackoffMultiplier??2,enablePerformanceMonitoring:e.enablePerformanceMonitoring??!0,logLevel:e.logLevel??"info"},this.enableMainRegistryIntegration=t.enableMainRegistryIntegration??!1,this.toolDiscovery=new lkr,this.toolDiscovery.on("toolRegistered",n=>{this.emit("toolDiscovered",{...n,serverName:this.getServerName(n.serverId)})}),this.toolDiscovery.on("toolUnregistered",n=>{this.emit("toolRemoved",{...n,serverName:this.getServerName(n.serverId)})}),Ekr(this)}setOutputNormalizer(e){this.toolDiscovery.setOutputNormalizer(e),le.debug("[ExternalServerManager] MCP output normalizer attached to ToolDiscoveryService")}setHITLManager(e){this.hitlManager=e,e&&e.isEnabled()?le.info("[ExternalServerManager] HITL safety mechanisms enabled for external tool execution"):le.debug("[ExternalServerManager] HITL safety mechanisms disabled or not configured")}setFallbackHITLManager(e){this.fallbackHITLManager=e}getHITLManager(){return this.hitlManager?.isEnabled()?this.hitlManager:this.fallbackHITLManager?.()??this.hitlManager}getServerName(e){return this.servers.get(e)?.config?.name||e}async loadMCPConfiguration(e,t={}){return t.parallel?this.loadMCPConfigurationParallel(e):this.loadMCPConfigurationSequential(e)}async loadMCPConfigurationParallel(e){const t=await Promise.resolve().then(()=>(yo(),up)),r=await Promise.resolve().then(()=>(Nr(),qh)),n=e||r.join(process.cwd(),".mcp-config.json");if(!t.existsSync(n))return le.debug(`[ExternalServerManager] No MCP config found at ${n}`),{serversLoaded:0,errors:[]};le.debug(`[ExternalServerManager] Loading MCP configuration in PARALLEL mode from ${n}`);try{const o=t.readFileSync(n,"utf8"),i=JSON.parse(o);if(!i.mcpServers||typeof i.mcpServers!="object")return le.debug("[ExternalServerManager] No mcpServers found in configuration"),{serversLoaded:0,errors:[]};const s=Object.entries(i.mcpServers).map(async([u,d])=>{try{const p=hkr(u,d),m=await this.addServer(u,p);return{serverId:u,result:m}}catch(p){const m=`Failed to load MCP server ${u}: ${p instanceof Error?p.message:String(p)}`;return{serverId:u,error:m}}}),a=await Promise.allSettled(s);let c=0;const l=[];for(const u of a)if(u.status==="fulfilled"){const{serverId:d,result:p,error:m}=u.value;if(p&&p.success)c++,le.debug(`[ExternalServerManager] Successfully loaded MCP server in parallel: ${d}`);else if(m)l.push(m),le.error(`[ExternalServerManager] Failed to load server ${d}: ${m}`);else if(p&&!p.success){const h=`Failed to load server ${d}: ${p.error}`;l.push(h),le.error(`[ExternalServerManager] ${h}`)}}else{const d=`Unexpected error during parallel loading: ${u.reason}`;l.push(d),le.error(`[ExternalServerManager] ${d}`)}return le.info(`[ExternalServerManager] PARALLEL MCP configuration loading complete: ${c} servers loaded, ${l.length} errors`),{serversLoaded:c,errors:l}}catch(o){const i=`Failed to load MCP configuration in parallel mode: ${o instanceof Error?o.message:String(o)}`;return le.error(`[ExternalServerManager] ${i}`),{serversLoaded:0,errors:[i]}}}async loadMCPConfigurationSequential(e){const t=await Promise.resolve().then(()=>(yo(),up)),r=await Promise.resolve().then(()=>(Nr(),qh)),n=e||r.join(process.cwd(),".mcp-config.json");if(!t.existsSync(n))return le.debug(`[ExternalServerManager] No MCP config found at ${n}`),{serversLoaded:0,errors:[]};le.debug(`[ExternalServerManager] Loading MCP configuration from ${n}`);try{const o=t.readFileSync(n,"utf8"),i=JSON.parse(o);if(!i.mcpServers||typeof i.mcpServers!="object")return le.debug("[ExternalServerManager] No mcpServers found in configuration"),{serversLoaded:0,errors:[]};let s=0;const a=[];for(const[c,l]of Object.entries(i.mcpServers))try{const u=hkr(c,l),d=await this.addServer(c,u);if(d.success)s++,le.debug(`[ExternalServerManager] Successfully loaded MCP server: ${c}`);else{const p=`Failed to load server ${c}: ${d.error}`;a.push(p),le.error(`[ExternalServerManager] ${p}`)}}catch(u){const d=`Failed to load MCP server ${c}: ${u instanceof Error?u.message:String(u)}`;a.push(d),le.error(`[ExternalServerManager] ${d}`)}return le.info(`[ExternalServerManager] MCP configuration loading complete: ${s} servers loaded, ${a.length} errors`),{serversLoaded:s,errors:a}}catch(o){const i=`Failed to load MCP configuration: ${o instanceof Error?o.message:String(o)}`;return le.error(`[ExternalServerManager] ${i}`),{serversLoaded:0,errors:[i]}}}validateConfig(e){const t=[],r=[],n=[];(!e.id||typeof e.id!="string")&&t.push("Server ID is required and must be a string"),["stdio","sse","websocket","http"].includes(e.transport)||t.push("Transport must be one of: stdio, sse, websocket, http"),e.fetch!==void 0&&!Wye(e.fetch)&&t.push("MCP fetch hook must be a function");for(const[o,i]of Object.entries({connectionTimeout:e.httpOptions?.connectionTimeout,requestTimeout:e.httpOptions?.requestTimeout}))i!==void 0&&(!Number.isFinite(i)||i<=0)&&t.push(`${o} must be a positive finite number`);return e.transport==="stdio"?((!e.command||typeof e.command!="string")&&t.push("Command is required and must be a string for stdio transport"),Array.isArray(e.args)||t.push("Args must be an array")):(e.transport==="sse"||e.transport==="websocket"||e.transport==="http")&&(!e.url||typeof e.url!="string")&&t.push(`URL is required for ${e.transport} transport`),e.timeout&&e.timeout<5e3&&r.push("Timeout less than 5 seconds may cause connection issues"),e.retries&&e.retries>5&&r.push("High retry count may slow down error recovery"),e.healthCheckInterval||n.push("Consider setting a health check interval for better reliability"),e.autoRestart===void 0&&n.push("Consider enabling auto-restart for production use"),{isValid:t.length===0,errors:t,warnings:r,suggestions:n}}convertConfigToMCPServerInfo(e,t){return{id:e,name:String(t.metadata?.title||e),description:`External MCP server (${t.transport})`,status:"initializing",transport:t.transport,command:t.command,args:t.args,env:t.env,tools:[],blockedTools:t.blockedTools,timeout:t.timeout,retries:t.retries,healthCheckInterval:t.healthCheckInterval,autoRestart:t.autoRestart,minTools:t.minTools,cwd:t.cwd,inheritParentEnv:t.inheritParentEnv,allowPrivateNetwork:t.allowPrivateNetwork,url:t.url,headers:t.headers,fetch:t.fetch,httpOptions:t.httpOptions,retryConfig:t.retryConfig,rateLimiting:t.rateLimiting,auth:t.auth,metadata:{category:"external",...b9(t.metadata)||{}}}}async addServer(e,t){const r=Date.now();let n;try{const o="transport"in t&&"command"in t&&!("tools"in t)?this.convertConfigToMCPServerInfo(e,t):t;if(this.servers.size>=this.config.maxServers)return{success:!1,error:`Maximum number of servers (${this.config.maxServers}) reached`,serverId:e,duration:Date.now()-r};const i={id:e,name:o.name,description:o.description,transport:o.transport,status:o.status,tools:o.tools,command:o.command||"",args:o.args||[],env:o.env||{},timeout:o.timeout,retries:o.retries,healthCheckInterval:o.healthCheckInterval,autoRestart:o.autoRestart,minTools:o.minTools,cwd:o.cwd,inheritParentEnv:o.inheritParentEnv,allowPrivateNetwork:o.allowPrivateNetwork,url:o.url,blockedTools:o.blockedTools,metadata:b9(o.metadata),headers:o.headers,auth:o.auth,fetch:o.fetch,httpOptions:o.httpOptions,retryConfig:o.retryConfig,rateLimiting:o.rateLimiting},s=this.validateConfig(i);if(!s.isValid)return{success:!1,error:`Configuration validation failed: ${s.errors.join(", ")}`,serverId:e,duration:Date.now()-r};if(this.servers.has(e))return{success:!1,error:`Server with ID '${e}' already exists`,serverId:e,duration:Date.now()-r};le.info(`[ExternalServerManager] Adding server: ${e}`,{command:o.command,transport:o.transport});const a={...o,process:null,client:null,transportInstance:null,status:"initializing",reconnectAttempts:0,maxReconnectAttempts:this.config.maxRestartAttempts,toolsMap:new Map,metrics:{totalConnections:0,totalDisconnections:0,totalErrors:0,totalToolCalls:0,averageResponseTime:0,lastResponseTime:0},config:i};n=a,this.servers.set(e,a),await this.startServer(e);const c=this.servers.get(e);if(!c)throw new Error(`Server ${e} not found after registration`);return{success:!0,data:{config:c.config,process:c.process,pid:c.pid,client:c.client,transport:c.transportInstance,status:c.status,lastError:c.lastError,startTime:c.startTime,lastHealthCheck:c.lastHealthCheck,reconnectAttempts:c.reconnectAttempts,maxReconnectAttempts:c.maxReconnectAttempts,tools:c.toolsMap,toolsArray:c.toolsArray,capabilities:c.capabilities,healthTimer:c.healthTimer,restartTimer:c.restartTimer,metrics:c.metrics},serverId:e,duration:Date.now()-r,metadata:{timestamp:Date.now(),operation:"addServer",readiness:"ready",toolsDiscovered:c.tools.length}}}catch(o){return le.debug(`[ExternalServerManager] Failed to add server ${e}:`,o),n!==void 0&&this.servers.get(e)===n&&n.status!=="stopping"&&(this.servers.delete(e),this.consecutiveFailures.delete(e),this.retryDeadlines.delete(e),this.lastHealth.delete(e),this.lifecycleStates.delete(e)),o instanceof Kye?{success:!1,error:o.message,serverId:e,duration:Date.now()-r,metadata:{timestamp:Date.now(),operation:"addServer",readiness:o.readiness,toolsDiscovered:o.toolsDiscovered}}:{success:!1,error:o instanceof Error?o.message:String(o),serverId:e,duration:Date.now()-r}}}async removeServer(e){const t=Date.now();try{const r=this.servers.get(e);if(!r)return{success:!1,error:`Server '${e}' not found`,serverId:e,duration:Date.now()-t};le.info(`[ExternalServerManager] Removing server: ${e}`);const n=this.getServerName(e);return await this.stopServer(e),this.servers.get(e)===r&&(this.servers.delete(e),this.consecutiveFailures.delete(e),this.retryDeadlines.delete(e),this.lastHealth.delete(e),this.lifecycleStates.delete(e),this.emit("disconnected",{serverId:e,serverName:n,reason:"Manually removed",timestamp:new Date})),{success:!0,serverId:e,duration:Date.now()-t,metadata:{timestamp:Date.now(),operation:"removeServer"}}}catch(r){return le.error(`[ExternalServerManager] Failed to remove server ${e}:`,r),{success:!1,error:r instanceof Error?r.message:String(r),serverId:e,duration:Date.now()-t}}}async startServer(e){const t=this.servers.get(e);if(!t)throw new Error(`Server '${e}' not found`);const r=t.config,n=We.mcp.startSpan("mcp.server.start",{attributes:{"mcp.server_id":e,"mcp.transport":r.transport,"mcp.command_name":r.command&&r.command.split(/[\\/]/).pop()||"","mcp.command_present":!!r.command}});try{this.updateServerStatus(e,"connecting"),this.toolDiscovery.clearServerTools(e),t.toolsMap.clear(),t.toolsArray=void 0,t.tools=[],le.debug(`[ExternalServerManager] Starting server: ${e}`,{command:r.command,args:E5n(r.args),transport:r.transport});const o=await Ig.createClient(r,r.timeout||this.config.defaultTimeout);if(!o.success||!o.client||!o.transport)throw new Error(`Failed to create MCP client: ${o.error}`);if(this.servers.get(e)!==t||this.isShuttingDown)throw await Ig.closeClient(o.client,o.transport,o.process??void 0),new Error(`MCP startup for '${e}' was superseded`);t.client=o.client,t.transportInstance=o.transport,t.process=o.process||null;const{StdioClientTransport:i}=await Promise.resolve().then(()=>(hSr(),cye));t.pid=o.transport instanceof i?o.transport.pid??void 0:void 0,t.capabilities=b9(o.capabilities),t.startTime=new Date,t.lastHealthCheck=new Date,t.metrics.totalConnections++,this.unresponsiveChecks.delete(e),this.attachClientLifecycle(e,o.client,o.transport);const s=()=>{if(this.servers.get(e)!==t||t.client!==o.client||o.client.transport!==o.transport||this.closedClients.has(o.client)||t.status!=="initializing"||this.isShuttingDown)throw new Error(`MCP connection for '${e}' was lost during startup`)};s(),await this.discoverServerTools(e),s();const a=r.minTools??0;if(t.toolsMap.size<a){const c=t.toolsMap.size;throw le.warn(`[ExternalServerManager] Server '${e}' discovered ${c} tool(s), below the configured minTools=${a}; tearing the connection back down`),await this.closeInstanceConnection(e,t),new Kye(e,c,a)}this.enableMainRegistryIntegration&&await this.registerServerToolsWithMainRegistry(e),s(),this.consecutiveFailures.delete(e),this.lastHealth.delete(e),this.retryDeadlines.delete(e),t.lastError=void 0,this.updateServerStatus(e,"connected"),this.startHealthMonitoring(e),this.emit("connected",{serverId:e,serverName:this.getServerName(e),toolCount:t.toolsMap.size,timestamp:new Date}),n.setAttribute("mcp.tool_count",t.toolsMap.size),n.setStatus({code:Ve.OK}),le.info(`[ExternalServerManager] Server started successfully: ${e}`)}catch(o){if(le.debug(`[ExternalServerManager] Failed to start server ${e}:`,o),this.servers.get(e)===t&&t.status!=="stopping"){await this.closeInstanceConnection(e,t);const i=this.servers.get(e);i===t&&i.status!=="stopping"&&!this.isShuttingDown&&(this.updateServerStatus(e,"failed",t),t.lastError=o instanceof Error?o.message:String(o),this.consecutiveFailures.set(e,(this.consecutiveFailures.get(e)??0)+1),this.emit("failed",{serverId:e,serverName:this.getServerName(e),error:t.lastError,timestamp:new Date}))}else this.servers.get(e)!==t&&t.client&&t.transportInstance&&(t.client.onclose=void 0,t.client.onerror=void 0,await Ig.closeClient(t.client,t.transportInstance,t.process??void 0),t.client=null,t.transportInstance=null,t.process=null);throw n.recordException(o instanceof Error?o:new Error(String(o))),n.setStatus({code:Ve.ERROR,message:o instanceof Error?o.message:String(o)}),o}finally{n.end()}}async closeInstanceConnection(e,t){if(this.enableMainRegistryIntegration&&this.unregisterServerToolsFromMainRegistry(e),this.toolDiscovery.clearServerTools(e),t.toolsMap.clear(),t.toolsArray=void 0,t.tools=[],!(!t.client||!t.transportInstance)){t.client.onclose=void 0,t.client.onerror=void 0;try{await Ig.closeClient(t.client,t.transportInstance,t.process??void 0)}catch(r){le.debug(`[ExternalServerManager] Error closing client for ${e}:`,r)}t.client=null,t.transportInstance=null,t.process=null,t.pid=void 0}}async stopServer(e){const t=this.servers.get(e);if(!t)return;const r=We.mcp.startSpan("mcp.server.stop",{attributes:{"mcp.server_id":e}});try{this.updateServerStatus(e,"stopping",t),t.healthTimer&&(clearInterval(t.healthTimer),t.healthTimer=void 0),t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0),this.enableMainRegistryIntegration&&this.unregisterServerToolsFromMainRegistry(e),this.toolDiscovery.clearServerTools(e),await this.closeInstanceConnection(e,t),this.updateServerStatus(e,"stopped",t),r.setStatus({code:Ve.OK}),le.info(`[ExternalServerManager] Server stopped: ${e}`)}catch(n){le.error(`[ExternalServerManager] Error stopping server ${e}:`,n),this.updateServerStatus(e,"failed",t),r.recordException(n instanceof Error?n:new Error(String(n))),r.setStatus({code:Ve.ERROR,message:n instanceof Error?n.message:String(n)})}finally{r.end()}}updateServerStatus(e,t,r){const n=this.servers.get(e);if(!n||r!==void 0&&n!==r)return;const o=n.status;this.lifecycleStates.set(e,t);const i=t==="connecting"||t==="restarting"?"initializing":t==="stopping"||t==="stopped"?"stopping":t==="connected"?"connected":t==="disconnected"?"disconnected":"failed";n.status=i,this.emit("statusChanged",{serverId:e,serverName:this.getServerName(e),oldStatus:o,newStatus:t,timestamp:new Date}),le.debug(`[ExternalServerManager] Status changed for ${e}: ${o} -> ${t}`)}attachClientLifecycle(e,t,r){t.onclose=()=>{this.closedClients.add(t);const n=this.servers.get(e),o=n?.pid?` (pid ${n.pid})`:"",i=Ig.getStderrTail(r),s=i.length>0?`Server process closed${o}; last stderr: ${i.slice(-5).join(" | ")}`:`Server process closed${o}`;this.handleConnectionLost(e,t,s,i)},t.onerror=n=>{le.warn(`[ExternalServerManager] Transport error for ${e}: ${n.message}`)}}handleConnectionLost(e,t,r,n=[],o=!1){const i=this.servers.get(e);!i||i.client!==t||i.status!=="connected"||(le.warn(`[ExternalServerManager] Connection lost for ${e}: ${r}`,n.length>0?{stderrTail:n}:void 0),i.lastError=r,this.handleServerDisconnection(e,r,o))}trackToolCall(e,t){const r=(this.inFlightToolCalls.get(e)??0)+t;r<=0?this.inFlightToolCalls.delete(e):this.inFlightToolCalls.set(e,r)}handleServerError(e,t){const r=this.servers.get(e);r&&(r.lastError=t.message,r.metrics.totalErrors++,this.consecutiveFailures.set(e,(this.consecutiveFailures.get(e)??0)+1),le.error(`[ExternalServerManager] Server error for ${e}:`,t),this.emit("failed",{serverId:e,serverName:this.getServerName(e),error:t.message,timestamp:new Date}),(r.config.autoRestart??this.config.enableAutoRestart)&&!this.isShuttingDown?this.scheduleRestart(e):this.updateServerStatus(e,"failed"))}handleServerDisconnection(e,t,r=!1){const n=this.servers.get(e);n&&(n.metrics.totalDisconnections++,r||this.consecutiveFailures.set(e,(this.consecutiveFailures.get(e)??0)+1),le.warn(`[ExternalServerManager] Server disconnected ${e}: ${t}`),this.emit("disconnected",{serverId:e,serverName:this.getServerName(e),reason:t,timestamp:new Date}),(n.config.autoRestart??this.config.enableAutoRestart)&&!this.isShuttingDown?this.scheduleRestart(e):this.updateServerStatus(e,"disconnected"))}scheduleRestart(e){const t=this.servers.get(e);if(!t||t.restartTimer)return;if(t.reconnectAttempts>=t.maxReconnectAttempts){le.error(`[ExternalServerManager] Max restart attempts reached for ${e}`),this.updateServerStatus(e,"failed"),this.retryDeadlines.delete(e);return}t.reconnectAttempts++,this.updateServerStatus(e,"restarting");const r=Math.min(1e3*Math.pow(this.config.restartBackoffMultiplier,t.reconnectAttempts-1),3e4);le.info(`[ExternalServerManager] Scheduling restart for ${e} in ${r}ms (attempt ${t.reconnectAttempts})`),this.retryDeadlines.set(e,new Date(Date.now()+r));const n=this.getServerStatuses().find(o=>o.serverId===e);n&&this.emit("healthCheck",{serverId:e,serverName:this.getServerName(e),health:n,timestamp:new Date}),t.restartTimer=setTimeout(async()=>{this.retryDeadlines.delete(e);const o=We.mcp.startSpan("mcp.server.restart",{attributes:{"mcp.server_id":e,"mcp.restart_attempt":t.reconnectAttempts,"mcp.restart_delay_ms":r}});try{if(this.servers.get(e)!==t||(await this.stopServer(e),this.servers.get(e)!==t)||(await this.startServer(e),this.servers.get(e)!==t))return;t.reconnectAttempts=0,o.setStatus({code:Ve.OK})}catch(i){le.error(`[ExternalServerManager] Restart failed for ${e}:`,i),o.recordException(i instanceof Error?i:new Error(String(i))),o.setStatus({code:Ve.ERROR,message:i instanceof Error?i.message:String(i)}),this.servers.get(e)===t&&this.scheduleRestart(e)}finally{o.end()}},r)}startHealthMonitoring(e){const t=this.servers.get(e);if(!t||!this.config.enablePerformanceMonitoring)return;const r=t.config.healthCheckInterval??this.config.defaultHealthCheckInterval;t.healthTimer=setInterval(async()=>{await this.performHealthCheck(e)},r),t.healthTimer.unref&&t.healthTimer.unref()}async performHealthCheck(e){const t=this.servers.get(e);if(!t||t.status!=="connected"||!t.client||this.healthChecksInFlight.has(e))return;this.healthChecksInFlight.add(e);const r=t.client,n=t.config.healthCheckInterval??this.config.defaultHealthCheckInterval,o=Math.max(1,Math.min(t.config.timeout||this.config.defaultTimeout,n)),i=Date.now(),s=[];let a=!0,c=!1,l=!1;try{try{if(await r.ping({timeout:o}),t.client!==r||t.status!=="connected")return;this.unresponsiveChecks.delete(e),this.consecutiveFailures.delete(e),t.lastError=void 0}catch(p){if(t.client!==r||t.status!=="connected")return;if(a=!1,this.consecutiveFailures.set(e,(this.consecutiveFailures.get(e)??0)+1),t.lastError=p instanceof Error?p.message:String(p),mkr(p))c=!0,s.push("connection closed");else{const m=this.inFlightToolCalls.get(e)??0;if(m>0)s.push(`ping timed out after ${o}ms while ${m} tool call(s) in flight`);else{const h=(this.unresponsiveChecks.get(e)??0)+1;this.unresponsiveChecks.set(e,h),s.push(`ping timed out after ${o}ms while idle (${h}/${Jye})`),l=h>=Jye}}}const u=Date.now()-i;t.lastHealthCheck=new Date;const d={serverId:e,isHealthy:a,status:this.lifecycleStates.get(e)??t.status,checkedAt:new Date,responseTime:u,toolCount:t.toolsMap.size,issues:s,consecutiveFailures:this.consecutiveFailures.get(e)??0,lastError:t.lastError,nextRetryAt:this.retryDeadlines.get(e),performance:{uptime:t.startTime?Date.now()-t.startTime.getTime():0,averageResponseTime:t.metrics.averageResponseTime}};this.lastHealth.set(e,d),this.emit("healthCheck",{serverId:e,serverName:this.getServerName(e),health:d,timestamp:new Date}),c||l?this.handleConnectionLost(e,r,`Health check failed: ${s.join(", ")}`,[],!0):a||le.warn(`[ExternalServerManager] Health check failed for ${e}:`,s)}catch(u){le.error(`[ExternalServerManager] Health check error for ${e}:`,u)}finally{this.healthChecksInFlight.delete(e)}}getServer(e){const t=this.servers.get(e);if(t)return{config:t.config,process:t.process,pid:t.pid,client:t.client,transport:t.transportInstance,status:t.status,lastError:t.lastError,startTime:t.startTime,lastHealthCheck:t.lastHealthCheck,reconnectAttempts:t.reconnectAttempts,maxReconnectAttempts:t.maxReconnectAttempts,tools:t.toolsMap,toolsArray:t.toolsArray,capabilities:t.capabilities,healthTimer:t.healthTimer,restartTimer:t.restartTimer,metrics:t.metrics}}getAllServers(){const e=new Map;for(const[t,r]of this.servers.entries())e.set(t,{config:r.config,process:r.process,pid:r.pid,client:r.client,transport:r.transportInstance,status:r.status,lastError:r.lastError,startTime:r.startTime,lastHealthCheck:r.lastHealthCheck,reconnectAttempts:r.reconnectAttempts,maxReconnectAttempts:r.maxReconnectAttempts,tools:r.toolsMap,toolsArray:r.toolsArray,capabilities:r.capabilities,healthTimer:r.healthTimer,restartTimer:r.restartTimer,metrics:r.metrics});return e}listServers(){return Array.from(this.servers.values())}getServerStatuses(){const e=[];for(const[t,r]of Array.from(this.servers.entries())){const n=r.startTime?Date.now()-r.startTime.getTime():0;e.push({serverId:t,isHealthy:r.status==="connected"&&(this.lastHealth.get(t)?.isHealthy??!0),status:this.lifecycleStates.get(t)??r.status,checkedAt:r.lastHealthCheck||new Date,toolCount:r.toolsMap.size,issues:r.lastError?[r.lastError]:[],consecutiveFailures:this.consecutiveFailures.get(t)??0,lastError:r.lastError,nextRetryAt:this.retryDeadlines.get(t),performance:{uptime:n,averageResponseTime:r.metrics.averageResponseTime}})}return e}async shutdown(){if(this.isShuttingDown)return;this.isShuttingDown=!0,T9.delete(this),le.info("[ExternalServerManager] Shutting down all servers...");const e=Array.from(this.servers.keys()).map(t=>this.stopServer(t).catch(r=>{le.error(`[ExternalServerManager] Error shutting down ${t}:`,r)}));await Promise.all(e),this.servers.clear(),this.toolDiscovery.destroy(),this.removeAllListeners(),le.info("[ExternalServerManager] All servers shut down and resources cleaned up")}async destroy(){return this.shutdown()}getStatistics(){let e=0,t=0,r=0,n=0,o=0;for(const i of Array.from(this.servers.values()))i.status==="connected"?e++:i.status==="failed"&&t++,r+=i.toolsMap.size,n+=i.metrics.totalConnections,o+=i.metrics.totalErrors;return{totalServers:this.servers.size,connectedServers:e,failedServers:t,totalTools:r,totalConnections:n,totalErrors:o}}async discoverServerTools(e){const t=this.servers.get(e);if(!t||!t.client)throw new Error(`Server '${e}' not found or not connected`);if(t.client.getServerCapabilities()?.tools!==void 0)try{le.debug(`[ExternalServerManager] Discovering tools for server: ${e}`);const r=t.client,n=()=>this.servers.get(e)===t&&t.client===r&&t.status==="initializing"&&r.transport===t.transportInstance&&!this.closedClients.has(r)&&!this.isShuttingDown,o=await this.toolDiscovery.discoverTools(e,r,t.config.timeout||this.config.defaultTimeout,n,!0);if(!n())throw new Error(`MCP discovery for '${e}' was superseded`);if(o.success){t.toolsMap.clear(),t.toolsArray=void 0,t.tools=[];const i=t.blockedTools||[];let s=0;for(const a of o.tools){if(i.includes(a.name)){le.info(`[ExternalServerManager] Blocking tool '${a.name}' from server '${e}' (configured in blockedTools)`),s++;continue}t.toolsMap.set(a.name,a),t.tools.push({name:a.name,description:a.description,inputSchema:a.inputSchema})}le.info(`[ExternalServerManager] Discovered ${o.toolCount} tools for ${e} (${s} blocked, ${t.toolsMap.size} available)`)}else throw new Error(`Tool discovery failed for ${e}: ${o.error??"unknown failure"}`)}catch(r){throw le.error(`[ExternalServerManager] Tool discovery error for ${e}:`,r),r}}async registerServerToolsWithMainRegistry(e){const t=this.servers.get(e);if(!t)throw new Error(`Server '${e}' not found`);try{le.debug(`[ExternalServerManager] Registering ${t.toolsMap.size} tools with main registry for server: ${e}`);const r=[];for(const[s,a]of t.toolsMap.entries()){const c=`${e}.${s}`,l={name:s,description:a.description||s,inputSchema:a.inputSchema||{},serverId:e,category:oc({isExternal:!0,serverId:e})};try{r.push(jye.registerTool(c,l,{execute:async(u,d)=>await this.executeTool(e,s,u,{timeout:t.config.timeout||this.config.defaultTimeout})})),le.debug(`[ExternalServerManager] Registered tool with main registry: ${c}`)}catch(u){le.warn(`[ExternalServerManager] Failed to register tool ${c} with main registry:`,u)}}const n=await Promise.allSettled(r),o=n.filter(s=>s.status==="fulfilled").length,i=n.length-o;le.info(`[ExternalServerManager] Registered ${o}/${n.length} tools with main registry for ${e}${i?` (${i} failed)`:""}`)}catch(r){le.error(`[ExternalServerManager] Failed to register tools with main registry for ${e}:`,r)}}unregisterServerToolsFromMainRegistry(e){const t=this.servers.get(e);if(!(!t||!this.enableMainRegistryIntegration))try{le.debug(`[ExternalServerManager] Unregistering tools from main registry for server: ${e}`);for(const[r]of t.toolsMap.entries()){const n=`${e}.${r}`;try{jye.removeTool(n),le.debug(`[ExternalServerManager] Unregistered tool from main registry: ${n}`)}catch(o){le.debug(`[ExternalServerManager] Failed to unregister tool ${n}:`,o)}}le.debug(`[ExternalServerManager] Completed unregistering tools from main registry for ${e}`)}catch(r){le.error(`[ExternalServerManager] Error unregistering tools from main registry for ${e}:`,r)}}async executeTool(e,t,r,n){const o=this.servers.get(e);if(!o)throw new Error(`Server '${e}' not found`);const i=o.client;if(!i)throw new Error(`Server '${e}' is not connected`);if(o.status!=="connected")throw new Error(`Server '${e}' is not in connected state: ${o.status}`);if((o.blockedTools||[]).includes(t))throw new Error(`Tool '${t}' is blocked on server '${e}' by configuration`);G0(n?.signal);const a=Date.now();try{const c=await this.confirmExternalToolCall(e,t,r,n);G0(n?.signal),this.trackToolCall(e,1);let l;try{l=await this.toolDiscovery.executeTool(t,e,i,c,{timeout:n?.timeout||o.config.timeout||this.config.defaultTimeout,signal:n?.signal})}finally{this.trackToolCall(e,-1)}const u=Date.now()-a;o.metrics.totalToolCalls++,o.metrics.lastResponseTime=u;const d=o.metrics.averageResponseTime*(o.metrics.totalToolCalls-1)+u;if(o.metrics.averageResponseTime=d/o.metrics.totalToolCalls,l.success){const p=l.isErrorResult===!0;return p&&o.metrics.totalErrors++,le.debug(p?`[ExternalServerManager] Tool returned a resolved MCP error: ${t} on ${e}`:`[ExternalServerManager] Tool executed successfully: ${t} on ${e}`,{duration:u}),syr(t,u,!p),l.data}else throw new Error(l.error||"Tool execution failed")}catch(c){throw c instanceof nu||n?.signal?.aborted===!0?le.info(`[ExternalServerManager] External tool '${t}' on ${e} refused or cancelled before it ran: ${c instanceof Error?c.message:String(c)}`):(o.metrics.totalErrors++,syr(t,Date.now()-a,!1),le.error(`[ExternalServerManager] Tool execution failed: ${t} on ${e}`,c)),mkr(c)&&this.handleConnectionLost(e,i,`Connection lost during tool call '${t}': ${c instanceof Error?c.message:String(c)}`),c}}async confirmExternalToolCall(e,t,r,n){const o=await K6(this.getHITLManager(),t,r,n?.hitlState,{serverId:e,sessionId:`external-${e}-${Date.now()}`,userId:void 0,signal:n?.signal},{log:i=>le.info(`[ExternalServerManager] ${i}`),subject:"External tool",pauseDeadline:n?.pauseDeadline});if(!o.run)throw o.error;return o.args}getAllTools(){return this.toolDiscovery.getAllTools()}getServerTools(e){return this.toolDiscovery.getServerTools(e)}getToolDiscovery(){return this.toolDiscovery}}}});function k5n(e,t,r,n){return{content:[{type:"text",text:`[MCP Tool Output \u2014 ${r.toolName} | ${r.serverId}]
1257
1257
  Original size: ${J4(n)} | Externalized \u2014 use retrieve_context with artifactId="${t}" to read the full output (supports offset + limit pagination)
1258
1258
 
1259
1259
  --- Preview (head + tail) ---