@whoz-oss/coday-server 0.115.2 → 0.115.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.
- package/package.json +1 -1
- package/server.js +2 -2
package/package.json
CHANGED
package/server.js
CHANGED
|
@@ -812,7 +812,7 @@ ${Eg(p)}
|
|
|
812
812
|
**Name:** \`${t.name}\` (fixed)
|
|
813
813
|
|
|
814
814
|
These values are fixed for new configurations. Continuing with other settings...
|
|
815
|
-
`;this.interactor.displayText(u)}else t.id=await this.editPropertyWithContext("ID","id",t.id,i,n),t.name=await this.editPropertyWithContext("Name","name",t.name,i,n);let o=t.url||i?.url,s=t.command||i?.command;return!o&&!s?await this.interactor.chooseOption(["command","url"],"Select transport type:","command")==="url"?t.url=await this.editPropertyWithContext("URL","url",t.url,i,n):t.command=await this.editPropertyWithContext("Command","command",t.command,i,n):(t.url=await this.editPropertyWithContext("URL","url",t.url,i,n),t.command=await this.editPropertyWithContext("Command","command",t.command,i,n)),t.args=await this.editArgsWithContext(t.args,i,n),t.env=await this.editEnvWithContext(t.env,i,n),t.cwd=await this.editPropertyWithContext("Working Directory","cwd",t.cwd,i,n),t.authToken=await this.editAuthTokenWithContext(t.authToken,i,n),(t.url||i?.url)&&(t.oauth2=await this.editBooleanWithContext("OAuth 2.1","oauth2",t.oauth2,i,n),t.oauth2?(t.oauthClientId=await this.editPropertyWithContext("OAuth Client ID","oauthClientId",t.oauthClientId,i,n),t.oauthClientSecret=await this.editOAuthClientSecretWithContext(t.oauthClientSecret,i,n),t.oauthScope=await this.editPropertyWithContext("OAuth Scope","oauthScope",t.oauthScope,i,n)):(t.oauthClientId=void 0,t.oauthClientSecret=void 0,t.oauthScope=void 0)),t.enabled=await this.editBooleanWithContext("Enabled","enabled",t.enabled,i,n),t.debug=await this.editBooleanWithContext("Debug","debug",t.debug,i,n),t.allowedTools=await this.editAllowedToolsWithContext(t.allowedTools,i,n),Mpe(t),t}async editPropertyWithContext(t,n,i,a,o){let s=this.buildPropertyContext(n,a,o),c=`## ${t}
|
|
815
|
+
`;this.interactor.displayText(u)}else t.id=await this.editPropertyWithContext("ID","id",t.id,i,n),t.name=await this.editPropertyWithContext("Name","name",t.name,i,n);let o=t.url||i?.url,s=t.command||i?.command;return!o&&!s?await this.interactor.chooseOption(["command","url"],"Select transport type:","command")==="url"?t.url=await this.editPropertyWithContext("URL","url",t.url,i,n):t.command=await this.editPropertyWithContext("Command","command",t.command,i,n):(t.url=await this.editPropertyWithContext("URL","url",t.url,i,n),t.command=await this.editPropertyWithContext("Command","command",t.command,i,n)),t.args=await this.editArgsWithContext(t.args,i,n),t.env=await this.editEnvWithContext(t.env,i,n),t.cwd=await this.editPropertyWithContext("Working Directory","cwd",t.cwd,i,n),t.authToken=await this.editAuthTokenWithContext(t.authToken,i,n),(t.url||i?.url)&&(t.oauth2=await this.editBooleanWithContext("OAuth 2.1","oauth2",t.oauth2,i,n),t.oauth2?(t.oauthClientId=await this.editPropertyWithContext("OAuth Client ID","oauthClientId",t.oauthClientId,i,n),t.oauthClientSecret=await this.editOAuthClientSecretWithContext(t.oauthClientSecret,i,n),t.oauthScope=await this.editPropertyWithContext("OAuth Scope","oauthScope",t.oauthScope,i,n),t.oauthRedirectUri=await this.editPropertyWithContext("OAuth Redirect URI","oauthRedirectUri",t.oauthRedirectUri,i,n)):(t.oauthClientId=void 0,t.oauthClientSecret=void 0,t.oauthScope=void 0,t.oauthRedirectUri=void 0)),t.enabled=await this.editBooleanWithContext("Enabled","enabled",t.enabled,i,n),t.debug=await this.editBooleanWithContext("Debug","debug",t.debug,i,n),t.allowedTools=await this.editAllowedToolsWithContext(t.allowedTools,i,n),Mpe(t),t}async editPropertyWithContext(t,n,i,a,o){let s=this.buildPropertyContext(n,a,o),c=`## ${t}
|
|
816
816
|
|
|
817
817
|
${s}
|
|
818
818
|
|
|
@@ -1145,7 +1145,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
1145
1145
|
`;break;case"id":s=g.includes("\0")?void 0:g;break;case"retry":/^\d+$/.test(g)?n(parseInt(g,10)):t(new zC(`Invalid \`retry\` value: "${g}"`,{type:"invalid-retry",value:g,line:v}));break;default:t(new zC(`Unknown field "${h.length>20?`${h.slice(0,20)}\u2026`:h}"`,{type:"unknown-field",field:h,value:g,line:v}));break}}function d(){c.length>0&&e({id:s,event:u||void 0,data:c.endsWith(`
|
|
1146
1146
|
`)?c.slice(0,-1):c}),s=void 0,c="",u=""}function m(h={}){a&&h.consume&&f(a),o=!0,s=void 0,c="",u="",a=""}return{feed:l,reset:m}}function V4t(r){let e=[],t="",n=0;for(;n<r.length;){let i=r.indexOf("\r",n),a=r.indexOf(`
|
|
1147
1147
|
`,n),o=-1;if(i!==-1&&a!==-1?o=Math.min(i,a):i!==-1?i===r.length-1?o=-1:o=i:a!==-1&&(o=a),o===-1){t=r.slice(n);break}else{let s=r.slice(n,o);e.push(s),n=o+1,r[n-1]==="\r"&&r[n]===`
|
|
1148
|
-
`&&n++}}return[e,t]}var HC=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let i;super({start(a){i=BC({onEvent:o=>{a.enqueue(o)},onError(o){e==="terminate"?a.error(o):typeof e=="function"&&e(o)},onRetry:t,onComment:n})},transform(a){i.feed(a)}})}};var G4t={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Md=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},B1=class{constructor(e,t){var n;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=UC(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=(n=t?.reconnectionOptions)!==null&&n!==void 0?n:G4t}async _authThenStart(){var e;if(!this._authProvider)throw new ja("No auth provider");let t;try{t=await Sl(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(t!=="AUTHORIZED")throw new ja;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let t={};if(this._authProvider){let i=await this._authProvider.tokens();i&&(t.Authorization=`Bearer ${i.access_token}`)}this._sessionId&&(t["mcp-session-id"]=this._sessionId),this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);let n=qC((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...t,...n})}async _startOrAuthSse(e){var t,n,i;let{resumptionToken:a}=e;try{let o=await this._commonHeaders();o.set("Accept","text/event-stream"),a&&o.set("last-event-id",a);let s=await((t=this._fetch)!==null&&t!==void 0?t:fetch)(this._url,{method:"GET",headers:o,signal:(n=this._abortController)===null||n===void 0?void 0:n.signal});if(!s.ok){if(s.status===401&&this._authProvider)return await this._authThenStart();if(s.status===405)return;throw new Md(s.status,`Failed to open SSE stream: ${s.statusText}`)}this._handleSseStream(s.body,e,!0)}catch(o){throw(i=this.onerror)===null||i===void 0||i.call(this,o),o}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,i=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(n,e),i)}_scheduleReconnection(e,t=0){var n;let i=this._reconnectionOptions.maxRetries;if(i>0&&t>=i){(n=this.onerror)===null||n===void 0||n.call(this,new Error(`Maximum reconnection attempts (${i}) exceeded.`));return}let a=this._getNextReconnectionDelay(t);setTimeout(()=>{this._startOrAuthSse(e).catch(o=>{var s;(s=this.onerror)===null||s===void 0||s.call(this,new Error(`Failed to reconnect SSE stream: ${o instanceof Error?o.message:String(o)}`)),this._scheduleReconnection(e,t+1)})},a)}_handleSseStream(e,t,n){if(!e)return;let{onresumptiontoken:i,replayMessageId:a}=t,o,s=!1;(async()=>{var u,l,f,p;try{let d=e.pipeThrough(new TextDecoderStream).pipeThrough(new HC({onRetry:h=>{this._serverRetryMs=h}})).getReader();for(;;){let{value:h,done:g}=await d.read();if(g)break;if(h.id&&(o=h.id,s=!0,i?.(h.id)),!h.event||h.event==="message")try{let v=vf.parse(JSON.parse(h.data));a!==void 0&&O8(v)&&(v.id=a),(u=this.onmessage)===null||u===void 0||u.call(this,v)}catch(v){(l=this.onerror)===null||l===void 0||l.call(this,v)}}(n||s)&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:o,onresumptiontoken:i,replayMessageId:a},0)}catch(d){if((f=this.onerror)===null||f===void 0||f.call(this,new Error(`SSE stream disconnected: ${d}`)),(n||s)&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:o,onresumptiontoken:i,replayMessageId:a},0)}catch(h){(p=this.onerror)===null||p===void 0||p.call(this,new Error(`Failed to reconnect: ${h instanceof Error?h.message:String(h)}`))}}})()}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 ja("No auth provider");if(await Sl(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ja("Failed to authorize")}async close(){var e,t;(e=this._abortController)===null||e===void 0||e.abort(),(t=this.onclose)===null||t===void 0||t.call(this)}async send(e,t){var n,i,a,o;try{let{resumptionToken:s,onresumptiontoken:c}=t||{};if(s){this._startOrAuthSse({resumptionToken:s,replayMessageId:HA(e)?e.id:void 0}).catch(g=>{var v;return(v=this.onerror)===null||v===void 0?void 0:v.call(this,g)});return}let u=await this._commonHeaders();u.set("content-type","application/json"),u.set("accept","application/json, text/event-stream");let l={...this._requestInit,method:"POST",headers:u,body:JSON.stringify(e),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},f=await((i=this._fetch)!==null&&i!==void 0?i:fetch)(this._url,l),p=f.headers.get("mcp-session-id");if(p&&(this._sessionId=p),!f.ok){if(f.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Md(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:v,scope:y}=z1(f);if(this._resourceMetadataUrl=v,this._scope=y,await Sl(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ja;return this._hasCompletedAuthFlow=!0,this.send(e)}if(f.status===403&&this._authProvider){let{resourceMetadataUrl:v,scope:y,error:x}=z1(f);if(x==="insufficient_scope"){let _=f.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===_)throw new Md(403,"Server returned 403 after trying upscoping");if(y&&(this._scope=y),v&&(this._resourceMetadataUrl=v),this._lastUpscopingHeader=_??void 0,await Sl(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new ja;return this.send(e)}}let g=await f.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${f.status}): ${g}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,f.status===202){eme(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(g=>{var v;return(v=this.onerror)===null||v===void 0?void 0:v.call(this,g)});return}let m=(Array.isArray(e)?e:[e]).filter(g=>"method"in g&&"id"in g&&g.id!==void 0).length>0,h=f.headers.get("content-type");if(m)if(h?.includes("text/event-stream"))this._handleSseStream(f.body,{onresumptiontoken:c},!1);else if(h?.includes("application/json")){let g=await f.json(),v=Array.isArray(g)?g.map(y=>vf.parse(y)):[vf.parse(g)];for(let y of v)(a=this.onmessage)===null||a===void 0||a.call(this,y)}else throw new Md(-1,`Unexpected content type: ${h}`)}catch(s){throw(o=this.onerror)===null||o===void 0||o.call(this,s),s}}get sessionId(){return this._sessionId}async terminateSession(){var e,t,n;if(this._sessionId)try{let i=await this._commonHeaders(),a={...this._requestInit,method:"DELETE",headers:i,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},o=await((t=this._fetch)!==null&&t!==void 0?t:fetch)(this._url,a);if(!o.ok&&o.status!==405)throw new Md(o.status,`Failed to terminate session: ${o.statusText}`);this._sessionId=void 0}catch(i){throw(n=this.onerror)===null||n===void 0||n.call(this,i),i}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}};var VC=class extends Event{constructor(e,t){var n,i;super(e),this.code=(n=t?.code)!=null?n:void 0,this.message=(i=t?.message)!=null?i:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,t,n){return n(J5e(this),t)}[Symbol.for("Deno.customInspect")](e,t){return e(J5e(this),t)}};function Z4t(r){let e=globalThis.DOMException;return typeof e=="function"?new e(r,"SyntaxError"):new SyntaxError(r)}function UW(r){return r instanceof Error?"errors"in r&&Array.isArray(r.errors)?r.errors.map(UW).join(", "):"cause"in r&&r.cause instanceof Error?`${r}: ${UW(r.cause)}`:r.message:`${r}`}function J5e(r){return{type:r.type,message:r.message,code:r.code,defaultPrevented:r.defaultPrevented,cancelable:r.cancelable,timeStamp:r.timeStamp}}var Y5e=r=>{throw TypeError(r)},JW=(r,e,t)=>e.has(r)||Y5e("Cannot "+t),nr=(r,e,t)=>(JW(r,e,"read from private field"),t?t.call(r):e.get(r)),fi=(r,e,t)=>e.has(r)?Y5e("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),gn=(r,e,t,n)=>(JW(r,e,"write to private field"),e.set(r,t),t),El=(r,e,t)=>(JW(r,e,"access private method"),t),co,Ld,H1,WC,GC,S9,G1,E9,Af,W1,Z1,V1,w9,ec,zW,BW,HW,K5e,WW,VW,_9,GW,ZW,qd=class extends EventTarget{constructor(e,t){var n,i;super(),fi(this,ec),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,fi(this,co),fi(this,Ld),fi(this,H1),fi(this,WC),fi(this,GC),fi(this,S9),fi(this,G1),fi(this,E9,null),fi(this,Af),fi(this,W1),fi(this,Z1,null),fi(this,V1,null),fi(this,w9,null),fi(this,BW,async a=>{var o;nr(this,W1).reset();let{body:s,redirected:c,status:u,headers:l}=a;if(u===204){El(this,ec,_9).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(c?gn(this,H1,new URL(a.url)):gn(this,H1,void 0),u!==200){El(this,ec,_9).call(this,`Non-200 status code (${u})`,u);return}if(!(l.get("content-type")||"").startsWith("text/event-stream")){El(this,ec,_9).call(this,'Invalid content type, expected "text/event-stream"',u);return}if(nr(this,co)===this.CLOSED)return;gn(this,co,this.OPEN);let f=new Event("open");if((o=nr(this,w9))==null||o.call(this,f),this.dispatchEvent(f),typeof s!="object"||!s||!("getReader"in s)){El(this,ec,_9).call(this,"Invalid response body, expected a web ReadableStream",u),this.close();return}let p=new TextDecoder,d=s.getReader(),m=!0;do{let{done:h,value:g}=await d.read();g&&nr(this,W1).feed(p.decode(g,{stream:!h})),h&&(m=!1,nr(this,W1).reset(),El(this,ec,GW).call(this))}while(m)}),fi(this,HW,a=>{gn(this,Af,void 0),!(a.name==="AbortError"||a.type==="aborted")&&El(this,ec,GW).call(this,UW(a))}),fi(this,WW,a=>{typeof a.id=="string"&&gn(this,E9,a.id);let o=new MessageEvent(a.event||"message",{data:a.data,origin:nr(this,H1)?nr(this,H1).origin:nr(this,Ld).origin,lastEventId:a.id||""});nr(this,V1)&&(!a.event||a.event==="message")&&nr(this,V1).call(this,o),this.dispatchEvent(o)}),fi(this,VW,a=>{gn(this,S9,a)}),fi(this,ZW,()=>{gn(this,G1,void 0),nr(this,co)===this.CONNECTING&&El(this,ec,zW).call(this)});try{if(e instanceof URL)gn(this,Ld,e);else if(typeof e=="string")gn(this,Ld,new URL(e,J4t()));else throw new Error("Invalid URL")}catch{throw Z4t("An invalid or illegal string was specified")}gn(this,W1,BC({onEvent:nr(this,WW),onRetry:nr(this,VW)})),gn(this,co,this.CONNECTING),gn(this,S9,3e3),gn(this,GC,(n=t?.fetch)!=null?n:globalThis.fetch),gn(this,WC,(i=t?.withCredentials)!=null?i:!1),El(this,ec,zW).call(this)}get readyState(){return nr(this,co)}get url(){return nr(this,Ld).href}get withCredentials(){return nr(this,WC)}get onerror(){return nr(this,Z1)}set onerror(e){gn(this,Z1,e)}get onmessage(){return nr(this,V1)}set onmessage(e){gn(this,V1,e)}get onopen(){return nr(this,w9)}set onopen(e){gn(this,w9,e)}addEventListener(e,t,n){let i=t;super.addEventListener(e,i,n)}removeEventListener(e,t,n){let i=t;super.removeEventListener(e,i,n)}close(){nr(this,G1)&&clearTimeout(nr(this,G1)),nr(this,co)!==this.CLOSED&&(nr(this,Af)&&nr(this,Af).abort(),gn(this,co,this.CLOSED),gn(this,Af,void 0))}};co=new WeakMap,Ld=new WeakMap,H1=new WeakMap,WC=new WeakMap,GC=new WeakMap,S9=new WeakMap,G1=new WeakMap,E9=new WeakMap,Af=new WeakMap,W1=new WeakMap,Z1=new WeakMap,V1=new WeakMap,w9=new WeakMap,ec=new WeakSet,zW=function(){gn(this,co,this.CONNECTING),gn(this,Af,new AbortController),nr(this,GC)(nr(this,Ld),El(this,ec,K5e).call(this)).then(nr(this,BW)).catch(nr(this,HW))},BW=new WeakMap,HW=new WeakMap,K5e=function(){var r;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...nr(this,E9)?{"Last-Event-ID":nr(this,E9)}:void 0},cache:"no-store",signal:(r=nr(this,Af))==null?void 0:r.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},WW=new WeakMap,VW=new WeakMap,_9=function(r,e){var t;nr(this,co)!==this.CLOSED&&gn(this,co,this.CLOSED);let n=new VC("error",{code:e,message:r});(t=nr(this,Z1))==null||t.call(this,n),this.dispatchEvent(n)},GW=function(r,e){var t;if(nr(this,co)===this.CLOSED)return;gn(this,co,this.CONNECTING);let n=new VC("error",{code:e,message:r});(t=nr(this,Z1))==null||t.call(this,n),this.dispatchEvent(n),gn(this,G1,setTimeout(nr(this,ZW),nr(this,S9)))},ZW=new WeakMap,qd.CONNECTING=0,qd.OPEN=1,qd.CLOSED=2;function J4t(){let r="document"in globalThis?globalThis.document:void 0;return r&&typeof r=="object"&&"baseURI"in r&&typeof r.baseURI=="string"?r.baseURI:void 0}var KW=class extends Error{constructor(e,t,n){super(`SSE error: ${t}`),this.code=e,this.event=n}},J1=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=UC(t?.fetch,t?.requestInit)}async _authThenStart(){var e;if(!this._authProvider)throw new ja("No auth provider");let t;try{t=await Sl(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(t!=="AUTHORIZED")throw new ja;return await this._startOrAuth()}async _commonHeaders(){var e;let t={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(t.Authorization=`Bearer ${n.access_token}`)}return this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion),new Headers({...t,...(e=this._requestInit)===null||e===void 0?void 0:e.headers})}_startOrAuth(){var e,t,n;let i=(n=(t=(e=this===null||this===void 0?void 0:this._eventSourceInit)===null||e===void 0?void 0:e.fetch)!==null&&t!==void 0?t:this._fetch)!==null&&n!==void 0?n:fetch;return new Promise((a,o)=>{this._eventSource=new qd(this._url.href,{...this._eventSourceInit,fetch:async(s,c)=>{let u=await this._commonHeaders();u.set("Accept","text/event-stream");let l=await i(s,{...c,headers:u});if(l.status===401&&l.headers.has("www-authenticate")){let{resourceMetadataUrl:f,scope:p}=z1(l);this._resourceMetadataUrl=f,this._scope=p}return l}}),this._abortController=new AbortController,this._eventSource.onerror=s=>{var c;if(s.code===401&&this._authProvider){this._authThenStart().then(a,o);return}let u=new KW(s.code,s.message,s);o(u),(c=this.onerror)===null||c===void 0||c.call(this,u)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",s=>{var c;let u=s;try{if(this._endpoint=new URL(u.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(l){o(l),(c=this.onerror)===null||c===void 0||c.call(this,l),this.close();return}a()}),this._eventSource.onmessage=s=>{var c,u;let l=s,f;try{f=vf.parse(JSON.parse(l.data))}catch(p){(c=this.onerror)===null||c===void 0||c.call(this,p);return}(u=this.onmessage)===null||u===void 0||u.call(this,f)}})}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 ja("No auth provider");if(await Sl(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ja("Failed to authorize")}async close(){var e,t,n;(e=this._abortController)===null||e===void 0||e.abort(),(t=this._eventSource)===null||t===void 0||t.close(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(e){var t,n,i;if(!this._endpoint)throw new Error("Not connected");try{let a=await this._commonHeaders();a.set("content-type","application/json");let o={...this._requestInit,method:"POST",headers:a,body:JSON.stringify(e),signal:(t=this._abortController)===null||t===void 0?void 0:t.signal},s=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._endpoint,o);if(!s.ok){if(s.status===401&&this._authProvider){let{resourceMetadataUrl:u,scope:l}=z1(s);if(this._resourceMetadataUrl=u,this._scope=l,await Sl(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ja;return this.send(e)}let c=await s.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${s.status}): ${c}`)}}catch(a){throw(i=this.onerror)===null||i===void 0||i.call(this,a),a}}setProtocolVersion(e){this._protocolVersion=e}};import{spawn as K4t}from"child_process";var X5e=15e3,Y4t=300*1e3,ZC=class extends Gt{constructor(t,n,i,a,o){super(new Pc("not used"),t.name);this.serverConfig=t;this.name=t.name,this.mcpInteractor=n,this.mcpUserService=i,this.mcpProjectName=a,this.mcpBaseUrl=o}clientPromise;toolsPromise;inspectorProcess;transport;serverProcessPid=null;name="Not defined yet";errorLogged=!1;lastUsed=Date.now();oauthProvider;_killed=!1;_usingLegacySSE=!1;_reconnectAttempts=0;_reconnectDelay=2e3;mcpInteractor;mcpUserService;mcpProjectName;mcpBaseUrl;async handleOAuthCallback(t){await this.oauthProvider?.handleCallback(t)}async kill(){if(this._killed=!0,this._reconnectAttempts=0,this._reconnectDelay=2e3,this.tools=[],console.log(`Closing mcp client ${this.serverConfig.name}`),this.inspectorProcess){console.log(`Stopping MCP Inspector process for ${this.serverConfig.name}`);try{this.inspectorProcess.kill("SIGTERM"),await new Promise(t=>setTimeout(t,100)),this.inspectorProcess.killed||this.inspectorProcess.kill("SIGKILL")}catch(t){console.log(`Error killing inspector process: ${t}`)}this.inspectorProcess=void 0}try{await(await this.clientPromise)?.close()}catch{console.log(`MCP client ${this.serverConfig.name} was already failed/closed`)}if(this.transport){try{await this.transport.close(),console.log(`Transport closed for ${this.serverConfig.name}`),this.serverProcessPid=null}catch(t){console.log(`Error closing transport for ${this.serverConfig.name}: ${t}`)}this.transport=void 0}if(this.serverProcessPid){try{process.kill(this.serverProcessPid,0),console.log(`Force killing MCP server process ${this.serverProcessPid} for ${this.serverConfig.name}`),process.kill(this.serverProcessPid,"SIGTERM"),await new Promise(t=>setTimeout(t,100));try{process.kill(this.serverProcessPid,0),process.kill(this.serverProcessPid,"SIGKILL"),console.log(`Force killed with SIGKILL: ${this.serverProcessPid}`)}catch{}}catch(t){t.code!=="ESRCH"&&console.log(`Error killing MCP server process ${this.serverProcessPid}: ${t}`)}this.serverProcessPid=null}console.log(`Closed mcp client ${this.serverConfig.name}`)}async buildTools(t,n){if(this.tools.length)return this.tools;if(!this.serverConfig.enabled)return console.debug(`[MCP] Server ${this.serverConfig.name} is disabled, skipping`),[];try{this.clientPromise||(console.log(`Initializing MCP server ${this.serverConfig.name}...`),this.clientPromise=this.buildClient());let i=await this.clientPromise;this.toolsPromise||(this.toolsPromise=this.buildInternalTools(i));let a=await this.toolsPromise;return console.log(`[MCP] Server ${this.serverConfig.name} loaded ${a.length} tools successfully`),a}catch(i){let a=i instanceof Error?i.message:String(i);return this.errorLogged||(this.errorLogged=!0,console.error(`[MCP] Server ${this.serverConfig.name} failed to initialize: ${a}`),console.warn(`[MCP] Server '${this.serverConfig.name}' is unavailable and will be skipped: ${a}`)),[]}}async buildClient(){let t=new jC({name:"Coday MCP Client",version:"1.0.0"},{capabilities:{}});if(this.serverConfig.url)console.log(`[MCP] ${this.serverConfig.name}: building remote transport for ${this.serverConfig.url}`),this.transport=this.buildRemoteTransport();else if(this.serverConfig.command){let n={};if(this.serverConfig.debug&&!this.inspectorProcess){let a=["@modelcontextprotocol/inspector",this.serverConfig.command,...this.serverConfig.args||[]],o={};this.serverConfig.env&&Object.keys(this.serverConfig.env).length>0&&(o.env=this.serverConfig.env),this.serverConfig.cwd&&(o.cwd=this.serverConfig.cwd),console.log(`Starting MCP Inspector process for ${this.serverConfig.name}}`),this.inspectorProcess=K4t("npx",a,{stdio:"inherit",...o}),this.inspectorProcess.on("exit",(s,c)=>{console.log(`MCP Inspector process for ${this.serverConfig.name} exited (code: ${s}, signal: ${c})`)})}n.command=this.serverConfig.command,n.args=this.serverConfig.args||[],this.serverConfig.env&&Object.keys(this.serverConfig.env).length>0&&(n.env=this.serverConfig.env,console.log(`Using custom environment variables for MCP server ${this.serverConfig.name}`)),this.serverConfig.cwd&&(n.cwd=this.serverConfig.cwd,console.log(`Using working directory: ${this.serverConfig.cwd}`)),this.transport=new MC(n),console.log(`Starting MCP server ${this.serverConfig.name} with command: ${n.command}`),this.transport.onerror=i=>{console.error(`MCP server ${this.serverConfig.name} transport error:`,i)},this.transport.onclose=()=>{console.log(`MCP server ${this.serverConfig.name} transport closed`),this.serverProcessPid=null}}else throw new Error(`MCP server ${this.serverConfig.name} has neither url nor command configured.`);try{return await this.connectWithTimeout(t),this.serverConfig.url&&this.wireRemoteReconnect(t),this.transport&&"pid"in this.transport?(this.serverProcessPid=this.transport.pid,console.log(`Successfully connected to MCP server ${this.serverConfig.name} (PID: ${this.serverProcessPid})`)):console.log(`Successfully connected to MCP server ${this.serverConfig.name}${this._usingLegacySSE?" (legacy SSE transport)":""}`),this._reconnectAttempts=0,this._reconnectDelay=2e3,t}catch(n){await this.cleanupOnError();let i=n instanceof Error?n.message:String(n);throw console.error(`Failed to connect to MCP server ${this.serverConfig.name}: ${i}`),i.includes("docker")||i.includes("Docker")||i.includes("container")||i.includes("Container")?new Error(`MCP server ${this.serverConfig.name} failed to start. This may be because Docker is not available or the Docker container failed to start. Original error: ${i}`):i.includes("timeout")||i.includes("Connection timeout")?new Error(`MCP server ${this.serverConfig.name} did not respond within ${X5e}ms. Check if the server command is correct and the server starts quickly. Original error: ${i}`):i.includes("ENOENT")||i.includes("command not found")?new Error(`MCP server ${this.serverConfig.name} command not found. Check that the command '${this.serverConfig.command}' is available in your PATH. Original error: ${i}`):new Error(`MCP server ${this.serverConfig.name} connection failed: ${i}`)}}async connectWithTimeout(t){let n=!!this.serverConfig.url,i=this.serverConfig.oauth2?Y4t:X5e,a=async()=>{console.log(`[MCP] ${this.serverConfig.name}: connecting (timeout=${i}ms)...`);let o=t.connect(this.transport),s,c=new Promise((u,l)=>{s=setTimeout(()=>l(new Error(`Connection timeout after ${i}ms`)),i)});try{await Promise.race([o,c])}finally{clearTimeout(s)}};if(!n){await a();return}try{await a(),this._usingLegacySSE=!1}catch(o){let s=o instanceof Error?o.message:String(o),c=this.oauthProvider?.waitForAuth();if(c){console.log(`[MCP] ${this.serverConfig.name}: waiting for OAuth authorization to complete...`),await c;try{await this.transport.close()}catch{}this.transport=this.buildRemoteTransport(),this._usingLegacySSE=!1,console.log(`[MCP] ${this.serverConfig.name}: OAuth complete, retrying connection`),await a();return}if(!this.shouldFallbackToSSE(s))throw o;console.warn(`[MCP] ${this.serverConfig.name}: StreamableHTTP connection failed (${s}), falling back to legacy SSEClientTransport`);try{await this.transport.close()}catch{}let u=new URL(this.serverConfig.url);this.oauthProvider?this.transport=new J1(u,{authProvider:this.oauthProvider}):this.serverConfig.authToken?this.transport=new J1(u,{requestInit:{headers:{Authorization:`Bearer ${this.serverConfig.authToken}`}}}):this.transport=new J1(u),this._usingLegacySSE=!0,console.log(`[MCP] ${this.serverConfig.name}: retrying with legacy SSE transport`),await a()}}shouldFallbackToSSE(t){return!!(/\b4\d{2}\b/.test(t)||/not supported|method not allowed|unsupported/i.test(t))}wireRemoteReconnect(t){if(!this.transport)return;let n=5,i=3e4;this.transport.onclose=()=>{if(this._killed){console.log(`[MCP] ${this.serverConfig.name}: transport closed (killed, no reconnect)`);return}if(this._reconnectAttempts>=n){console.error(`[MCP] ${this.serverConfig.name}: transport closed after ${n} reconnect attempts \u2014 giving up`);return}let a=++this._reconnectAttempts,o=this._reconnectDelay;this._reconnectDelay=Math.min(this._reconnectDelay*2,i),console.warn(`[MCP] ${this.serverConfig.name}: transport closed unexpectedly \u2014 reconnecting in ${o}ms (attempt ${a}/${n})`),setTimeout(async()=>{if(this._killed){console.log(`[MCP] ${this.serverConfig.name}: reconnect cancelled (killed)`);return}console.log(`[MCP] ${this.serverConfig.name}: attempting reconnect #${a}...`),this.clientPromise=void 0,this.toolsPromise=void 0,this.tools=[],this.errorLogged=!1,this._usingLegacySSE=!1,this.transport=this.buildRemoteTransport();try{await this.connectWithTimeout(t),this.wireRemoteReconnect(t),this.clientPromise=Promise.resolve(t),console.log(`[MCP] ${this.serverConfig.name}: reconnected successfully (attempt ${a})`),this._reconnectAttempts=0,this._reconnectDelay=2e3}catch(s){let c=s instanceof Error?s.message:String(s);console.error(`[MCP] ${this.serverConfig.name}: reconnect #${a} failed: ${c}`)}},o)}}buildRemoteTransport(){let t=new URL(this.serverConfig.url);if(this.serverConfig.oauth2){if(!this.mcpInteractor||!this.mcpUserService||!this.mcpProjectName)throw new Error(`MCP server ${this.serverConfig.name}: oauth2 requires interactor, userService and projectName \u2014 pass them to McpToolsFactory constructor`);let n=`${this.mcpBaseUrl??"http://localhost:3000"}/oauth/callback`;console.log(`[MCP] ${this.serverConfig.name}: using OAuth 2.1 transport (redirectUri=${n})`),this.oauthProvider=new NA(this.mcpInteractor,this.mcpUserService,this.mcpProjectName,this.serverConfig.id,n,this.serverConfig.oauthClientId,this.serverConfig.oauthClientSecret,this.serverConfig.oauthScope),console.log(`[MCP] ${this.serverConfig.name}: McpOAuthProvider created for mcpId=${this.serverConfig.id}${this.serverConfig.oauthClientId?` (static client_id=${this.serverConfig.oauthClientId})`:" (dynamic registration)"}`);let i=new B1(t,{authProvider:this.oauthProvider});return this.oauthProvider.setFinishAuth(a=>i.finishAuth(a)),console.log(`[MCP] ${this.serverConfig.name}: OAuth transport ready`),i}if(this.serverConfig.authToken){let n={headers:{Authorization:`Bearer ${this.serverConfig.authToken}`}};return console.log(`[MCP] ${this.serverConfig.name}: using static Bearer token`),new B1(t,{requestInit:n})}return console.log(`[MCP] ${this.serverConfig.name}: connecting without authentication`),new B1(t)}async cleanupOnError(){if(console.log(`Cleaning up failed MCP connection for ${this.serverConfig.name}`),this.inspectorProcess){try{this.inspectorProcess.kill("SIGTERM"),await new Promise(t=>setTimeout(t,100)),this.inspectorProcess.killed||this.inspectorProcess.kill("SIGKILL")}catch(t){console.log(`Error killing inspector during cleanup: ${t}`)}this.inspectorProcess=void 0}if(this.transport){try{await this.transport.close()}catch(t){console.log(`Error closing transport during cleanup: ${t}`)}this.transport=void 0}if(this.serverProcessPid){try{process.kill(this.serverProcessPid,0),console.log(`Force killing MCP server process ${this.serverProcessPid} for ${this.serverConfig.name}`),process.kill(this.serverProcessPid,"SIGTERM"),await new Promise(t=>setTimeout(t,100));try{process.kill(this.serverProcessPid,0),process.kill(this.serverProcessPid,"SIGKILL"),console.log(`Force killed with SIGKILL: ${this.serverProcessPid}`)}catch{}}catch(t){t.code!=="ESRCH"&&console.log(`Error killing MCP server process ${this.serverProcessPid}: ${t}`)}this.serverProcessPid=null}}async buildInternalTools(t){let n=[];console.log(`[MCP] ${this.serverConfig.name}: listing resource templates...`);try{let i=await t.listResourceTemplates();if(i&&i.templates&&Array.isArray(i.templates)){console.log(`[MCP] ${this.serverConfig.name}: found ${i.templates.length} resource template(s)`);for(let a of i.templates)n.push(this.createResourceTool(this.serverConfig,t,a))}}catch(i){i instanceof Error&&!i.message.includes("-32601: Method not found")?console.warn(`[MCP] Error listing resource templates from server ${this.serverConfig.name}: ${i}`):console.debug(`[MCP] Server ${this.serverConfig.name} doesn't support resource templates, continuing with tools only.`)}console.log(`[MCP] ${this.serverConfig.name}: listing tools...`);try{let i=await t.listTools();if(i&&i.tools&&Array.isArray(i.tools)){console.log(`[MCP] ${this.serverConfig.name}: found ${i.tools.length} tool(s): ${i.tools.map(a=>a.name).join(", ")}`);for(let a of i.tools)n.push(this.createFunctionTool(this.serverConfig,t,a))}}catch(i){console.warn(`[MCP] Error listing tools from server ${this.serverConfig.name}: ${i}`)}if(this.serverConfig.debug){let i=n.map(a=>`- ${a.function.name}
|
|
1148
|
+
`&&n++}}return[e,t]}var HC=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let i;super({start(a){i=BC({onEvent:o=>{a.enqueue(o)},onError(o){e==="terminate"?a.error(o):typeof e=="function"&&e(o)},onRetry:t,onComment:n})},transform(a){i.feed(a)}})}};var G4t={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Md=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},B1=class{constructor(e,t){var n;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=UC(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=(n=t?.reconnectionOptions)!==null&&n!==void 0?n:G4t}async _authThenStart(){var e;if(!this._authProvider)throw new ja("No auth provider");let t;try{t=await Sl(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(t!=="AUTHORIZED")throw new ja;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let t={};if(this._authProvider){let i=await this._authProvider.tokens();i&&(t.Authorization=`Bearer ${i.access_token}`)}this._sessionId&&(t["mcp-session-id"]=this._sessionId),this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);let n=qC((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...t,...n})}async _startOrAuthSse(e){var t,n,i;let{resumptionToken:a}=e;try{let o=await this._commonHeaders();o.set("Accept","text/event-stream"),a&&o.set("last-event-id",a);let s=await((t=this._fetch)!==null&&t!==void 0?t:fetch)(this._url,{method:"GET",headers:o,signal:(n=this._abortController)===null||n===void 0?void 0:n.signal});if(!s.ok){if(s.status===401&&this._authProvider)return await this._authThenStart();if(s.status===405)return;throw new Md(s.status,`Failed to open SSE stream: ${s.statusText}`)}this._handleSseStream(s.body,e,!0)}catch(o){throw(i=this.onerror)===null||i===void 0||i.call(this,o),o}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,i=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(n,e),i)}_scheduleReconnection(e,t=0){var n;let i=this._reconnectionOptions.maxRetries;if(i>0&&t>=i){(n=this.onerror)===null||n===void 0||n.call(this,new Error(`Maximum reconnection attempts (${i}) exceeded.`));return}let a=this._getNextReconnectionDelay(t);setTimeout(()=>{this._startOrAuthSse(e).catch(o=>{var s;(s=this.onerror)===null||s===void 0||s.call(this,new Error(`Failed to reconnect SSE stream: ${o instanceof Error?o.message:String(o)}`)),this._scheduleReconnection(e,t+1)})},a)}_handleSseStream(e,t,n){if(!e)return;let{onresumptiontoken:i,replayMessageId:a}=t,o,s=!1;(async()=>{var u,l,f,p;try{let d=e.pipeThrough(new TextDecoderStream).pipeThrough(new HC({onRetry:h=>{this._serverRetryMs=h}})).getReader();for(;;){let{value:h,done:g}=await d.read();if(g)break;if(h.id&&(o=h.id,s=!0,i?.(h.id)),!h.event||h.event==="message")try{let v=vf.parse(JSON.parse(h.data));a!==void 0&&O8(v)&&(v.id=a),(u=this.onmessage)===null||u===void 0||u.call(this,v)}catch(v){(l=this.onerror)===null||l===void 0||l.call(this,v)}}(n||s)&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:o,onresumptiontoken:i,replayMessageId:a},0)}catch(d){if((f=this.onerror)===null||f===void 0||f.call(this,new Error(`SSE stream disconnected: ${d}`)),(n||s)&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:o,onresumptiontoken:i,replayMessageId:a},0)}catch(h){(p=this.onerror)===null||p===void 0||p.call(this,new Error(`Failed to reconnect: ${h instanceof Error?h.message:String(h)}`))}}})()}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 ja("No auth provider");if(await Sl(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ja("Failed to authorize")}async close(){var e,t;(e=this._abortController)===null||e===void 0||e.abort(),(t=this.onclose)===null||t===void 0||t.call(this)}async send(e,t){var n,i,a,o;try{let{resumptionToken:s,onresumptiontoken:c}=t||{};if(s){this._startOrAuthSse({resumptionToken:s,replayMessageId:HA(e)?e.id:void 0}).catch(g=>{var v;return(v=this.onerror)===null||v===void 0?void 0:v.call(this,g)});return}let u=await this._commonHeaders();u.set("content-type","application/json"),u.set("accept","application/json, text/event-stream");let l={...this._requestInit,method:"POST",headers:u,body:JSON.stringify(e),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},f=await((i=this._fetch)!==null&&i!==void 0?i:fetch)(this._url,l),p=f.headers.get("mcp-session-id");if(p&&(this._sessionId=p),!f.ok){if(f.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Md(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:v,scope:y}=z1(f);if(this._resourceMetadataUrl=v,this._scope=y,await Sl(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ja;return this._hasCompletedAuthFlow=!0,this.send(e)}if(f.status===403&&this._authProvider){let{resourceMetadataUrl:v,scope:y,error:x}=z1(f);if(x==="insufficient_scope"){let _=f.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===_)throw new Md(403,"Server returned 403 after trying upscoping");if(y&&(this._scope=y),v&&(this._resourceMetadataUrl=v),this._lastUpscopingHeader=_??void 0,await Sl(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new ja;return this.send(e)}}let g=await f.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${f.status}): ${g}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,f.status===202){eme(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(g=>{var v;return(v=this.onerror)===null||v===void 0?void 0:v.call(this,g)});return}let m=(Array.isArray(e)?e:[e]).filter(g=>"method"in g&&"id"in g&&g.id!==void 0).length>0,h=f.headers.get("content-type");if(m)if(h?.includes("text/event-stream"))this._handleSseStream(f.body,{onresumptiontoken:c},!1);else if(h?.includes("application/json")){let g=await f.json(),v=Array.isArray(g)?g.map(y=>vf.parse(y)):[vf.parse(g)];for(let y of v)(a=this.onmessage)===null||a===void 0||a.call(this,y)}else throw new Md(-1,`Unexpected content type: ${h}`)}catch(s){throw(o=this.onerror)===null||o===void 0||o.call(this,s),s}}get sessionId(){return this._sessionId}async terminateSession(){var e,t,n;if(this._sessionId)try{let i=await this._commonHeaders(),a={...this._requestInit,method:"DELETE",headers:i,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},o=await((t=this._fetch)!==null&&t!==void 0?t:fetch)(this._url,a);if(!o.ok&&o.status!==405)throw new Md(o.status,`Failed to terminate session: ${o.statusText}`);this._sessionId=void 0}catch(i){throw(n=this.onerror)===null||n===void 0||n.call(this,i),i}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}};var VC=class extends Event{constructor(e,t){var n,i;super(e),this.code=(n=t?.code)!=null?n:void 0,this.message=(i=t?.message)!=null?i:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,t,n){return n(J5e(this),t)}[Symbol.for("Deno.customInspect")](e,t){return e(J5e(this),t)}};function Z4t(r){let e=globalThis.DOMException;return typeof e=="function"?new e(r,"SyntaxError"):new SyntaxError(r)}function UW(r){return r instanceof Error?"errors"in r&&Array.isArray(r.errors)?r.errors.map(UW).join(", "):"cause"in r&&r.cause instanceof Error?`${r}: ${UW(r.cause)}`:r.message:`${r}`}function J5e(r){return{type:r.type,message:r.message,code:r.code,defaultPrevented:r.defaultPrevented,cancelable:r.cancelable,timeStamp:r.timeStamp}}var Y5e=r=>{throw TypeError(r)},JW=(r,e,t)=>e.has(r)||Y5e("Cannot "+t),nr=(r,e,t)=>(JW(r,e,"read from private field"),t?t.call(r):e.get(r)),fi=(r,e,t)=>e.has(r)?Y5e("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),gn=(r,e,t,n)=>(JW(r,e,"write to private field"),e.set(r,t),t),El=(r,e,t)=>(JW(r,e,"access private method"),t),co,Ld,H1,WC,GC,S9,G1,E9,Af,W1,Z1,V1,w9,ec,zW,BW,HW,K5e,WW,VW,_9,GW,ZW,qd=class extends EventTarget{constructor(e,t){var n,i;super(),fi(this,ec),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,fi(this,co),fi(this,Ld),fi(this,H1),fi(this,WC),fi(this,GC),fi(this,S9),fi(this,G1),fi(this,E9,null),fi(this,Af),fi(this,W1),fi(this,Z1,null),fi(this,V1,null),fi(this,w9,null),fi(this,BW,async a=>{var o;nr(this,W1).reset();let{body:s,redirected:c,status:u,headers:l}=a;if(u===204){El(this,ec,_9).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(c?gn(this,H1,new URL(a.url)):gn(this,H1,void 0),u!==200){El(this,ec,_9).call(this,`Non-200 status code (${u})`,u);return}if(!(l.get("content-type")||"").startsWith("text/event-stream")){El(this,ec,_9).call(this,'Invalid content type, expected "text/event-stream"',u);return}if(nr(this,co)===this.CLOSED)return;gn(this,co,this.OPEN);let f=new Event("open");if((o=nr(this,w9))==null||o.call(this,f),this.dispatchEvent(f),typeof s!="object"||!s||!("getReader"in s)){El(this,ec,_9).call(this,"Invalid response body, expected a web ReadableStream",u),this.close();return}let p=new TextDecoder,d=s.getReader(),m=!0;do{let{done:h,value:g}=await d.read();g&&nr(this,W1).feed(p.decode(g,{stream:!h})),h&&(m=!1,nr(this,W1).reset(),El(this,ec,GW).call(this))}while(m)}),fi(this,HW,a=>{gn(this,Af,void 0),!(a.name==="AbortError"||a.type==="aborted")&&El(this,ec,GW).call(this,UW(a))}),fi(this,WW,a=>{typeof a.id=="string"&&gn(this,E9,a.id);let o=new MessageEvent(a.event||"message",{data:a.data,origin:nr(this,H1)?nr(this,H1).origin:nr(this,Ld).origin,lastEventId:a.id||""});nr(this,V1)&&(!a.event||a.event==="message")&&nr(this,V1).call(this,o),this.dispatchEvent(o)}),fi(this,VW,a=>{gn(this,S9,a)}),fi(this,ZW,()=>{gn(this,G1,void 0),nr(this,co)===this.CONNECTING&&El(this,ec,zW).call(this)});try{if(e instanceof URL)gn(this,Ld,e);else if(typeof e=="string")gn(this,Ld,new URL(e,J4t()));else throw new Error("Invalid URL")}catch{throw Z4t("An invalid or illegal string was specified")}gn(this,W1,BC({onEvent:nr(this,WW),onRetry:nr(this,VW)})),gn(this,co,this.CONNECTING),gn(this,S9,3e3),gn(this,GC,(n=t?.fetch)!=null?n:globalThis.fetch),gn(this,WC,(i=t?.withCredentials)!=null?i:!1),El(this,ec,zW).call(this)}get readyState(){return nr(this,co)}get url(){return nr(this,Ld).href}get withCredentials(){return nr(this,WC)}get onerror(){return nr(this,Z1)}set onerror(e){gn(this,Z1,e)}get onmessage(){return nr(this,V1)}set onmessage(e){gn(this,V1,e)}get onopen(){return nr(this,w9)}set onopen(e){gn(this,w9,e)}addEventListener(e,t,n){let i=t;super.addEventListener(e,i,n)}removeEventListener(e,t,n){let i=t;super.removeEventListener(e,i,n)}close(){nr(this,G1)&&clearTimeout(nr(this,G1)),nr(this,co)!==this.CLOSED&&(nr(this,Af)&&nr(this,Af).abort(),gn(this,co,this.CLOSED),gn(this,Af,void 0))}};co=new WeakMap,Ld=new WeakMap,H1=new WeakMap,WC=new WeakMap,GC=new WeakMap,S9=new WeakMap,G1=new WeakMap,E9=new WeakMap,Af=new WeakMap,W1=new WeakMap,Z1=new WeakMap,V1=new WeakMap,w9=new WeakMap,ec=new WeakSet,zW=function(){gn(this,co,this.CONNECTING),gn(this,Af,new AbortController),nr(this,GC)(nr(this,Ld),El(this,ec,K5e).call(this)).then(nr(this,BW)).catch(nr(this,HW))},BW=new WeakMap,HW=new WeakMap,K5e=function(){var r;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...nr(this,E9)?{"Last-Event-ID":nr(this,E9)}:void 0},cache:"no-store",signal:(r=nr(this,Af))==null?void 0:r.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},WW=new WeakMap,VW=new WeakMap,_9=function(r,e){var t;nr(this,co)!==this.CLOSED&&gn(this,co,this.CLOSED);let n=new VC("error",{code:e,message:r});(t=nr(this,Z1))==null||t.call(this,n),this.dispatchEvent(n)},GW=function(r,e){var t;if(nr(this,co)===this.CLOSED)return;gn(this,co,this.CONNECTING);let n=new VC("error",{code:e,message:r});(t=nr(this,Z1))==null||t.call(this,n),this.dispatchEvent(n),gn(this,G1,setTimeout(nr(this,ZW),nr(this,S9)))},ZW=new WeakMap,qd.CONNECTING=0,qd.OPEN=1,qd.CLOSED=2;function J4t(){let r="document"in globalThis?globalThis.document:void 0;return r&&typeof r=="object"&&"baseURI"in r&&typeof r.baseURI=="string"?r.baseURI:void 0}var KW=class extends Error{constructor(e,t,n){super(`SSE error: ${t}`),this.code=e,this.event=n}},J1=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=UC(t?.fetch,t?.requestInit)}async _authThenStart(){var e;if(!this._authProvider)throw new ja("No auth provider");let t;try{t=await Sl(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(t!=="AUTHORIZED")throw new ja;return await this._startOrAuth()}async _commonHeaders(){var e;let t={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(t.Authorization=`Bearer ${n.access_token}`)}return this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion),new Headers({...t,...(e=this._requestInit)===null||e===void 0?void 0:e.headers})}_startOrAuth(){var e,t,n;let i=(n=(t=(e=this===null||this===void 0?void 0:this._eventSourceInit)===null||e===void 0?void 0:e.fetch)!==null&&t!==void 0?t:this._fetch)!==null&&n!==void 0?n:fetch;return new Promise((a,o)=>{this._eventSource=new qd(this._url.href,{...this._eventSourceInit,fetch:async(s,c)=>{let u=await this._commonHeaders();u.set("Accept","text/event-stream");let l=await i(s,{...c,headers:u});if(l.status===401&&l.headers.has("www-authenticate")){let{resourceMetadataUrl:f,scope:p}=z1(l);this._resourceMetadataUrl=f,this._scope=p}return l}}),this._abortController=new AbortController,this._eventSource.onerror=s=>{var c;if(s.code===401&&this._authProvider){this._authThenStart().then(a,o);return}let u=new KW(s.code,s.message,s);o(u),(c=this.onerror)===null||c===void 0||c.call(this,u)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",s=>{var c;let u=s;try{if(this._endpoint=new URL(u.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(l){o(l),(c=this.onerror)===null||c===void 0||c.call(this,l),this.close();return}a()}),this._eventSource.onmessage=s=>{var c,u;let l=s,f;try{f=vf.parse(JSON.parse(l.data))}catch(p){(c=this.onerror)===null||c===void 0||c.call(this,p);return}(u=this.onmessage)===null||u===void 0||u.call(this,f)}})}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 ja("No auth provider");if(await Sl(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ja("Failed to authorize")}async close(){var e,t,n;(e=this._abortController)===null||e===void 0||e.abort(),(t=this._eventSource)===null||t===void 0||t.close(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(e){var t,n,i;if(!this._endpoint)throw new Error("Not connected");try{let a=await this._commonHeaders();a.set("content-type","application/json");let o={...this._requestInit,method:"POST",headers:a,body:JSON.stringify(e),signal:(t=this._abortController)===null||t===void 0?void 0:t.signal},s=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._endpoint,o);if(!s.ok){if(s.status===401&&this._authProvider){let{resourceMetadataUrl:u,scope:l}=z1(s);if(this._resourceMetadataUrl=u,this._scope=l,await Sl(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ja;return this.send(e)}let c=await s.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${s.status}): ${c}`)}}catch(a){throw(i=this.onerror)===null||i===void 0||i.call(this,a),a}}setProtocolVersion(e){this._protocolVersion=e}};import{spawn as K4t}from"child_process";var X5e=15e3,Y4t=300*1e3,ZC=class extends Gt{constructor(t,n,i,a,o){super(new Pc("not used"),t.name);this.serverConfig=t;this.name=t.name,this.mcpInteractor=n,this.mcpUserService=i,this.mcpProjectName=a,this.mcpBaseUrl=o}clientPromise;toolsPromise;inspectorProcess;transport;serverProcessPid=null;name="Not defined yet";errorLogged=!1;lastUsed=Date.now();oauthProvider;_killed=!1;_usingLegacySSE=!1;_reconnectAttempts=0;_reconnectDelay=2e3;mcpInteractor;mcpUserService;mcpProjectName;mcpBaseUrl;async handleOAuthCallback(t){await this.oauthProvider?.handleCallback(t)}async kill(){if(this._killed=!0,this._reconnectAttempts=0,this._reconnectDelay=2e3,this.tools=[],console.log(`Closing mcp client ${this.serverConfig.name}`),this.inspectorProcess){console.log(`Stopping MCP Inspector process for ${this.serverConfig.name}`);try{this.inspectorProcess.kill("SIGTERM"),await new Promise(t=>setTimeout(t,100)),this.inspectorProcess.killed||this.inspectorProcess.kill("SIGKILL")}catch(t){console.log(`Error killing inspector process: ${t}`)}this.inspectorProcess=void 0}try{await(await this.clientPromise)?.close()}catch{console.log(`MCP client ${this.serverConfig.name} was already failed/closed`)}if(this.transport){try{await this.transport.close(),console.log(`Transport closed for ${this.serverConfig.name}`),this.serverProcessPid=null}catch(t){console.log(`Error closing transport for ${this.serverConfig.name}: ${t}`)}this.transport=void 0}if(this.serverProcessPid){try{process.kill(this.serverProcessPid,0),console.log(`Force killing MCP server process ${this.serverProcessPid} for ${this.serverConfig.name}`),process.kill(this.serverProcessPid,"SIGTERM"),await new Promise(t=>setTimeout(t,100));try{process.kill(this.serverProcessPid,0),process.kill(this.serverProcessPid,"SIGKILL"),console.log(`Force killed with SIGKILL: ${this.serverProcessPid}`)}catch{}}catch(t){t.code!=="ESRCH"&&console.log(`Error killing MCP server process ${this.serverProcessPid}: ${t}`)}this.serverProcessPid=null}console.log(`Closed mcp client ${this.serverConfig.name}`)}async buildTools(t,n){if(this.tools.length)return this.tools;if(!this.serverConfig.enabled)return console.debug(`[MCP] Server ${this.serverConfig.name} is disabled, skipping`),[];try{this.clientPromise||(console.log(`Initializing MCP server ${this.serverConfig.name}...`),this.clientPromise=this.buildClient());let i=await this.clientPromise;this.toolsPromise||(this.toolsPromise=this.buildInternalTools(i));let a=await this.toolsPromise;return console.log(`[MCP] Server ${this.serverConfig.name} loaded ${a.length} tools successfully`),a}catch(i){let a=i instanceof Error?i.message:String(i);return this.errorLogged||(this.errorLogged=!0,console.error(`[MCP] Server ${this.serverConfig.name} failed to initialize: ${a}`),console.warn(`[MCP] Server '${this.serverConfig.name}' is unavailable and will be skipped: ${a}`)),[]}}async buildClient(){let t=new jC({name:"Coday MCP Client",version:"1.0.0"},{capabilities:{}});if(this.serverConfig.url)console.log(`[MCP] ${this.serverConfig.name}: building remote transport for ${this.serverConfig.url}`),this.transport=this.buildRemoteTransport();else if(this.serverConfig.command){let n={};if(this.serverConfig.debug&&!this.inspectorProcess){let a=["@modelcontextprotocol/inspector",this.serverConfig.command,...this.serverConfig.args||[]],o={};this.serverConfig.env&&Object.keys(this.serverConfig.env).length>0&&(o.env=this.serverConfig.env),this.serverConfig.cwd&&(o.cwd=this.serverConfig.cwd),console.log(`Starting MCP Inspector process for ${this.serverConfig.name}}`),this.inspectorProcess=K4t("npx",a,{stdio:"inherit",...o}),this.inspectorProcess.on("exit",(s,c)=>{console.log(`MCP Inspector process for ${this.serverConfig.name} exited (code: ${s}, signal: ${c})`)})}n.command=this.serverConfig.command,n.args=this.serverConfig.args||[],this.serverConfig.env&&Object.keys(this.serverConfig.env).length>0&&(n.env=this.serverConfig.env,console.log(`Using custom environment variables for MCP server ${this.serverConfig.name}`)),this.serverConfig.cwd&&(n.cwd=this.serverConfig.cwd,console.log(`Using working directory: ${this.serverConfig.cwd}`)),this.transport=new MC(n),console.log(`Starting MCP server ${this.serverConfig.name} with command: ${n.command}`),this.transport.onerror=i=>{console.error(`MCP server ${this.serverConfig.name} transport error:`,i)},this.transport.onclose=()=>{console.log(`MCP server ${this.serverConfig.name} transport closed`),this.serverProcessPid=null}}else throw new Error(`MCP server ${this.serverConfig.name} has neither url nor command configured.`);try{return await this.connectWithTimeout(t),this.serverConfig.url&&this.wireRemoteReconnect(t),this.transport&&"pid"in this.transport?(this.serverProcessPid=this.transport.pid,console.log(`Successfully connected to MCP server ${this.serverConfig.name} (PID: ${this.serverProcessPid})`)):console.log(`Successfully connected to MCP server ${this.serverConfig.name}${this._usingLegacySSE?" (legacy SSE transport)":""}`),this._reconnectAttempts=0,this._reconnectDelay=2e3,t}catch(n){await this.cleanupOnError();let i=n instanceof Error?n.message:String(n);throw console.error(`Failed to connect to MCP server ${this.serverConfig.name}: ${i}`),i.includes("docker")||i.includes("Docker")||i.includes("container")||i.includes("Container")?new Error(`MCP server ${this.serverConfig.name} failed to start. This may be because Docker is not available or the Docker container failed to start. Original error: ${i}`):i.includes("timeout")||i.includes("Connection timeout")?new Error(`MCP server ${this.serverConfig.name} did not respond within ${X5e}ms. Check if the server command is correct and the server starts quickly. Original error: ${i}`):i.includes("ENOENT")||i.includes("command not found")?new Error(`MCP server ${this.serverConfig.name} command not found. Check that the command '${this.serverConfig.command}' is available in your PATH. Original error: ${i}`):new Error(`MCP server ${this.serverConfig.name} connection failed: ${i}`)}}async connectWithTimeout(t){let n=!!this.serverConfig.url,i=this.serverConfig.oauth2?Y4t:X5e,a=async()=>{console.log(`[MCP] ${this.serverConfig.name}: connecting (timeout=${i}ms)...`);let o=t.connect(this.transport),s,c=new Promise((u,l)=>{s=setTimeout(()=>l(new Error(`Connection timeout after ${i}ms`)),i)});try{await Promise.race([o,c])}finally{clearTimeout(s)}};if(!n){await a();return}try{await a(),this._usingLegacySSE=!1}catch(o){let s=o instanceof Error?o.message:String(o),c=this.oauthProvider?.waitForAuth();if(c){console.log(`[MCP] ${this.serverConfig.name}: waiting for OAuth authorization to complete...`),await c;try{await this.transport.close()}catch{}this.transport=this.buildRemoteTransport(),this._usingLegacySSE=!1,console.log(`[MCP] ${this.serverConfig.name}: OAuth complete, retrying connection`),await a();return}if(!this.shouldFallbackToSSE(s))throw o;console.warn(`[MCP] ${this.serverConfig.name}: StreamableHTTP connection failed (${s}), falling back to legacy SSEClientTransport`);try{await this.transport.close()}catch{}let u=new URL(this.serverConfig.url);this.oauthProvider?this.transport=new J1(u,{authProvider:this.oauthProvider}):this.serverConfig.authToken?this.transport=new J1(u,{requestInit:{headers:{Authorization:`Bearer ${this.serverConfig.authToken}`}}}):this.transport=new J1(u),this._usingLegacySSE=!0,console.log(`[MCP] ${this.serverConfig.name}: retrying with legacy SSE transport`),await a()}}shouldFallbackToSSE(t){return!!(/\b4\d{2}\b/.test(t)||/not supported|method not allowed|unsupported/i.test(t))}wireRemoteReconnect(t){if(!this.transport)return;let n=5,i=3e4;this.transport.onclose=()=>{if(this._killed){console.log(`[MCP] ${this.serverConfig.name}: transport closed (killed, no reconnect)`);return}if(this._reconnectAttempts>=n){console.error(`[MCP] ${this.serverConfig.name}: transport closed after ${n} reconnect attempts \u2014 giving up`);return}let a=++this._reconnectAttempts,o=this._reconnectDelay;this._reconnectDelay=Math.min(this._reconnectDelay*2,i),console.warn(`[MCP] ${this.serverConfig.name}: transport closed unexpectedly \u2014 reconnecting in ${o}ms (attempt ${a}/${n})`),setTimeout(async()=>{if(this._killed){console.log(`[MCP] ${this.serverConfig.name}: reconnect cancelled (killed)`);return}console.log(`[MCP] ${this.serverConfig.name}: attempting reconnect #${a}...`),this.clientPromise=void 0,this.toolsPromise=void 0,this.tools=[],this.errorLogged=!1,this._usingLegacySSE=!1,this.transport=this.buildRemoteTransport();try{await this.connectWithTimeout(t),this.wireRemoteReconnect(t),this.clientPromise=Promise.resolve(t),console.log(`[MCP] ${this.serverConfig.name}: reconnected successfully (attempt ${a})`),this._reconnectAttempts=0,this._reconnectDelay=2e3}catch(s){let c=s instanceof Error?s.message:String(s);console.error(`[MCP] ${this.serverConfig.name}: reconnect #${a} failed: ${c}`)}},o)}}buildRemoteTransport(){let t=new URL(this.serverConfig.url);if(this.serverConfig.oauth2){if(!this.mcpInteractor||!this.mcpUserService||!this.mcpProjectName)throw new Error(`MCP server ${this.serverConfig.name}: oauth2 requires interactor, userService and projectName \u2014 pass them to McpToolsFactory constructor`);let n=this.serverConfig.oauthRedirectUri??(this.mcpBaseUrl?`${this.mcpBaseUrl}/oauth/callback`:void 0);if(!n)throw new Error(`MCP server ${this.serverConfig.name}: oauth2 requires a redirect URI \u2014 set oauthRedirectUri in the server config or ensure mcpBaseUrl is provided`);console.log(`[MCP] ${this.serverConfig.name}: using OAuth 2.1 transport (redirectUri=${n})`),this.oauthProvider=new NA(this.mcpInteractor,this.mcpUserService,this.mcpProjectName,this.serverConfig.id,n,this.serverConfig.oauthClientId,this.serverConfig.oauthClientSecret,this.serverConfig.oauthScope),console.log(`[MCP] ${this.serverConfig.name}: McpOAuthProvider created for mcpId=${this.serverConfig.id}${this.serverConfig.oauthClientId?` (static client_id=${this.serverConfig.oauthClientId})`:" (dynamic registration)"}`);let i=new B1(t,{authProvider:this.oauthProvider});return this.oauthProvider.setFinishAuth(a=>i.finishAuth(a)),console.log(`[MCP] ${this.serverConfig.name}: OAuth transport ready`),i}if(this.serverConfig.authToken){let n={headers:{Authorization:`Bearer ${this.serverConfig.authToken}`}};return console.log(`[MCP] ${this.serverConfig.name}: using static Bearer token`),new B1(t,{requestInit:n})}return console.log(`[MCP] ${this.serverConfig.name}: connecting without authentication`),new B1(t)}async cleanupOnError(){if(console.log(`Cleaning up failed MCP connection for ${this.serverConfig.name}`),this.inspectorProcess){try{this.inspectorProcess.kill("SIGTERM"),await new Promise(t=>setTimeout(t,100)),this.inspectorProcess.killed||this.inspectorProcess.kill("SIGKILL")}catch(t){console.log(`Error killing inspector during cleanup: ${t}`)}this.inspectorProcess=void 0}if(this.transport){try{await this.transport.close()}catch(t){console.log(`Error closing transport during cleanup: ${t}`)}this.transport=void 0}if(this.serverProcessPid){try{process.kill(this.serverProcessPid,0),console.log(`Force killing MCP server process ${this.serverProcessPid} for ${this.serverConfig.name}`),process.kill(this.serverProcessPid,"SIGTERM"),await new Promise(t=>setTimeout(t,100));try{process.kill(this.serverProcessPid,0),process.kill(this.serverProcessPid,"SIGKILL"),console.log(`Force killed with SIGKILL: ${this.serverProcessPid}`)}catch{}}catch(t){t.code!=="ESRCH"&&console.log(`Error killing MCP server process ${this.serverProcessPid}: ${t}`)}this.serverProcessPid=null}}async buildInternalTools(t){let n=[];console.log(`[MCP] ${this.serverConfig.name}: listing resource templates...`);try{let i=await t.listResourceTemplates();if(i&&i.templates&&Array.isArray(i.templates)){console.log(`[MCP] ${this.serverConfig.name}: found ${i.templates.length} resource template(s)`);for(let a of i.templates)n.push(this.createResourceTool(this.serverConfig,t,a))}}catch(i){i instanceof Error&&!i.message.includes("-32601: Method not found")?console.warn(`[MCP] Error listing resource templates from server ${this.serverConfig.name}: ${i}`):console.debug(`[MCP] Server ${this.serverConfig.name} doesn't support resource templates, continuing with tools only.`)}console.log(`[MCP] ${this.serverConfig.name}: listing tools...`);try{let i=await t.listTools();if(i&&i.tools&&Array.isArray(i.tools)){console.log(`[MCP] ${this.serverConfig.name}: found ${i.tools.length} tool(s): ${i.tools.map(a=>a.name).join(", ")}`);for(let a of i.tools)n.push(this.createFunctionTool(this.serverConfig,t,a))}}catch(i){console.warn(`[MCP] Error listing tools from server ${this.serverConfig.name}: ${i}`)}if(this.serverConfig.debug){let i=n.map(a=>`- ${a.function.name}
|
|
1149
1149
|
`).join();console.debug(`[MCP] ${this.serverConfig.name}:
|
|
1150
1150
|
${i}`)}return n}createResourceTool(t,n,i){let a=`mcp__${t.id}__${i.name}`,o=async u=>{try{this.lastUsed=Date.now();let l=i.uriTemplate.replace(/\{([^}]+)\}/g,(p,d)=>encodeURIComponent(u[d]||"")),f=await n.readResource({uri:l});if(!f||!f.contents)throw new Error(`No content returned from resource ${i.name}`);return f.contents.map(p=>"text"in p?{uri:p.uri,text:p.text,mimeType:p.mimeType||"text/plain"}:"blob"in p?{uri:p.uri,blob:p.blob,mimeType:p.mimeType||"application/octet-stream"}:p)}catch(l){throw console.error(`[MCP] Error retrieving resource ${i.name}: ${l}`),new Error(`Failed to retrieve resource: ${l}`)}},s={},c=i.uriTemplate.match(/\{([^}]+)\}/g)||[];for(let u of c){let l=u.slice(1,-1);s[l]={type:"string",description:`Parameter ${l} for resource ${i.name}`}}return{type:"function",function:{name:a,description:i.description||`Resource from MCP server ${t.name}`,parameters:{type:"object",properties:s},parse:JSON.parse,function:o}}}createFunctionTool(t,n,i){let a=`${t.name}__${i.name}`,o=async s=>{this.lastUsed=Date.now(),this.serverConfig.debug&&console.debug(`[MCP] ${a} input:
|
|
1151
1151
|
|