@whoz-oss/coday-server 0.248.1 → 0.248.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 +1 -1
package/package.json
CHANGED
package/server.js
CHANGED
|
@@ -1408,7 +1408,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
1408
1408
|
`,n),a=-1;if(i!==-1&&s!==-1?a=Math.min(i,s):i!==-1?i===t.length-1?a=-1:a=i:s!==-1&&(a=s),a===-1){r=t.slice(n);break}else{let o=t.slice(n,a);e.push(o),n=a+1,t[n-1]==="\r"&&t[n]===`
|
|
1409
1409
|
`&&n++}}return[e,r]}var IU=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let i;super({start(s){i=OU({onEvent:a=>{s.enqueue(a)},onError(a){e==="terminate"?s.error(a):typeof e=="function"&&e(a)},onRetry:r,onComment:n})},transform(s){i.feed(s)}})}};var f0r={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},p4=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},H7=class{constructor(e,r){var n;this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=TU(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=(n=r?.reconnectionOptions)!==null&&n!==void 0?n:f0r}async _authThenStart(){var e;if(!this._authProvider)throw new Xo("No auth provider");let r;try{r=await Fh(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(r!=="AUTHORIZED")throw new Xo;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let r={};if(this._authProvider){let i=await this._authProvider.tokens();i&&(r.Authorization=`Bearer ${i.access_token}`)}this._sessionId&&(r["mcp-session-id"]=this._sessionId),this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);let n=CU((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...n})}async _startOrAuthSse(e){var r,n,i;let{resumptionToken:s}=e;try{let a=await this._commonHeaders();a.set("Accept","text/event-stream"),s&&a.set("last-event-id",s);let o=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,{method:"GET",headers:a,signal:(n=this._abortController)===null||n===void 0?void 0:n.signal});if(!o.ok){if(o.status===401&&this._authProvider)return await this._authThenStart();if(o.status===405)return;throw new p4(o.status,`Failed to open SSE stream: ${o.statusText}`)}this._handleSseStream(o.body,e,!0)}catch(a){throw(i=this.onerror)===null||i===void 0||i.call(this,a),a}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,i=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),i)}_scheduleReconnection(e,r=0){var n;let i=this._reconnectionOptions.maxRetries;if(i>0&&r>=i){(n=this.onerror)===null||n===void 0||n.call(this,new Error(`Maximum reconnection attempts (${i}) exceeded.`));return}let s=this._getNextReconnectionDelay(r);setTimeout(()=>{this._startOrAuthSse(e).catch(a=>{var o;(o=this.onerror)===null||o===void 0||o.call(this,new Error(`Failed to reconnect SSE stream: ${a instanceof Error?a.message:String(a)}`)),this._scheduleReconnection(e,r+1)})},s)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:i,replayMessageId:s}=r,a,o=!1;(async()=>{var u,f,d,p;try{let h=e.pipeThrough(new TextDecoderStream).pipeThrough(new IU({onRetry:g=>{this._serverRetryMs=g}})).getReader();for(;;){let{value:g,done:v}=await h.read();if(v)break;if(g.id&&(a=g.id,o=!0,i?.(g.id)),!g.event||g.event==="message")try{let y=mm.parse(JSON.parse(g.data));s!==void 0&&hA(y)&&(y.id=s),(u=this.onmessage)===null||u===void 0||u.call(this,y)}catch(y){(f=this.onerror)===null||f===void 0||f.call(this,y)}}(n||o)&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:i,replayMessageId:s},0)}catch(h){if((d=this.onerror)===null||d===void 0||d.call(this,new Error(`SSE stream disconnected: ${h}`)),(n||o)&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:i,replayMessageId:s},0)}catch(g){(p=this.onerror)===null||p===void 0||p.call(this,new Error(`Failed to reconnect: ${g instanceof Error?g.message:String(g)}`))}}})()}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 Xo("No auth provider");if(await Fh(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Xo("Failed to authorize")}async close(){var e,r;(e=this._abortController)===null||e===void 0||e.abort(),(r=this.onclose)===null||r===void 0||r.call(this)}async send(e,r){var n,i,s,a;try{let{resumptionToken:o,onresumptiontoken:c}=r||{};if(o){this._startOrAuthSse({resumptionToken:o,replayMessageId:IB(e)?e.id:void 0}).catch(v=>{var y;return(y=this.onerror)===null||y===void 0?void 0:y.call(this,v)});return}let u=await this._commonHeaders();u.set("content-type","application/json"),u.set("accept","application/json, text/event-stream");let f={...this._requestInit,method:"POST",headers:u,body:JSON.stringify(e),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},d=await((i=this._fetch)!==null&&i!==void 0?i:fetch)(this._url,f),p=d.headers.get("mcp-session-id");if(p&&(this._sessionId=p),!d.ok){if(d.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new p4(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:y,scope:b}=z7(d);if(this._resourceMetadataUrl=y,this._scope=b,await Fh(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Xo;return this._hasCompletedAuthFlow=!0,this.send(e)}if(d.status===403&&this._authProvider){let{resourceMetadataUrl:y,scope:b,error:x}=z7(d);if(x==="insufficient_scope"){let k=d.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===k)throw new p4(403,"Server returned 403 after trying upscoping");if(b&&(this._scope=b),y&&(this._resourceMetadataUrl=y),this._lastUpscopingHeader=k??void 0,await Fh(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Xo;return this.send(e)}}let v=await d.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${d.status}): ${v}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,d.status===202){nze(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(v=>{var y;return(y=this.onerror)===null||y===void 0?void 0:y.call(this,v)});return}let m=(Array.isArray(e)?e:[e]).filter(v=>"method"in v&&"id"in v&&v.id!==void 0).length>0,g=d.headers.get("content-type");if(m)if(g?.includes("text/event-stream"))this._handleSseStream(d.body,{onresumptiontoken:c},!1);else if(g?.includes("application/json")){let v=await d.json(),y=Array.isArray(v)?v.map(b=>mm.parse(b)):[mm.parse(v)];for(let b of y)(s=this.onmessage)===null||s===void 0||s.call(this,b)}else throw new p4(-1,`Unexpected content type: ${g}`)}catch(o){throw(a=this.onerror)===null||a===void 0||a.call(this,o),o}}get sessionId(){return this._sessionId}async terminateSession(){var e,r,n;if(this._sessionId)try{let i=await this._commonHeaders(),s={...this._requestInit,method:"DELETE",headers:i,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},a=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,s);if(!a.ok&&a.status!==405)throw new p4(a.status,`Failed to terminate session: ${a.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,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};var RU=class extends Event{constructor(e,r){var n,i;super(e),this.code=(n=r?.code)!=null?n:void 0,this.message=(i=r?.message)!=null?i:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,n){return n(YVe(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(YVe(this),r)}};function d0r(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function ghe(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(ghe).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${ghe(t.cause)}`:t.message:`${t}`}function YVe(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var eGe=t=>{throw TypeError(t)},Ehe=(t,e,r)=>e.has(t)||eGe("Cannot "+r),tn=(t,e,r)=>(Ehe(t,e,"read from private field"),r?r.call(t):e.get(t)),Xs=(t,e,r)=>e.has(t)?eGe("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),$i=(t,e,r,n)=>(Ehe(t,e,"write to private field"),e.set(t,r),r),Mh=(t,e,r)=>(Ehe(t,e,"access private method"),r),Mc,h4,W7,DU,$U,sC,Z7,aC,Em,V7,K7,G7,nC,If,vhe,yhe,bhe,QVe,xhe,_he,iC,whe,She,m4=class extends EventTarget{constructor(e,r){var n,i;super(),Xs(this,If),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Xs(this,Mc),Xs(this,h4),Xs(this,W7),Xs(this,DU),Xs(this,$U),Xs(this,sC),Xs(this,Z7),Xs(this,aC,null),Xs(this,Em),Xs(this,V7),Xs(this,K7,null),Xs(this,G7,null),Xs(this,nC,null),Xs(this,yhe,async s=>{var a;tn(this,V7).reset();let{body:o,redirected:c,status:u,headers:f}=s;if(u===204){Mh(this,If,iC).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(c?$i(this,W7,new URL(s.url)):$i(this,W7,void 0),u!==200){Mh(this,If,iC).call(this,`Non-200 status code (${u})`,u);return}if(!(f.get("content-type")||"").startsWith("text/event-stream")){Mh(this,If,iC).call(this,'Invalid content type, expected "text/event-stream"',u);return}if(tn(this,Mc)===this.CLOSED)return;$i(this,Mc,this.OPEN);let d=new Event("open");if((a=tn(this,nC))==null||a.call(this,d),this.dispatchEvent(d),typeof o!="object"||!o||!("getReader"in o)){Mh(this,If,iC).call(this,"Invalid response body, expected a web ReadableStream",u),this.close();return}let p=new TextDecoder,h=o.getReader(),m=!0;do{let{done:g,value:v}=await h.read();v&&tn(this,V7).feed(p.decode(v,{stream:!g})),g&&(m=!1,tn(this,V7).reset(),Mh(this,If,whe).call(this))}while(m)}),Xs(this,bhe,s=>{$i(this,Em,void 0),!(s.name==="AbortError"||s.type==="aborted")&&Mh(this,If,whe).call(this,ghe(s))}),Xs(this,xhe,s=>{typeof s.id=="string"&&$i(this,aC,s.id);let a=new MessageEvent(s.event||"message",{data:s.data,origin:tn(this,W7)?tn(this,W7).origin:tn(this,h4).origin,lastEventId:s.id||""});tn(this,G7)&&(!s.event||s.event==="message")&&tn(this,G7).call(this,a),this.dispatchEvent(a)}),Xs(this,_he,s=>{$i(this,sC,s)}),Xs(this,She,()=>{$i(this,Z7,void 0),tn(this,Mc)===this.CONNECTING&&Mh(this,If,vhe).call(this)});try{if(e instanceof URL)$i(this,h4,e);else if(typeof e=="string")$i(this,h4,new URL(e,p0r()));else throw new Error("Invalid URL")}catch{throw d0r("An invalid or illegal string was specified")}$i(this,V7,OU({onEvent:tn(this,xhe),onRetry:tn(this,_he)})),$i(this,Mc,this.CONNECTING),$i(this,sC,3e3),$i(this,$U,(n=r?.fetch)!=null?n:globalThis.fetch),$i(this,DU,(i=r?.withCredentials)!=null?i:!1),Mh(this,If,vhe).call(this)}get readyState(){return tn(this,Mc)}get url(){return tn(this,h4).href}get withCredentials(){return tn(this,DU)}get onerror(){return tn(this,K7)}set onerror(e){$i(this,K7,e)}get onmessage(){return tn(this,G7)}set onmessage(e){$i(this,G7,e)}get onopen(){return tn(this,nC)}set onopen(e){$i(this,nC,e)}addEventListener(e,r,n){let i=r;super.addEventListener(e,i,n)}removeEventListener(e,r,n){let i=r;super.removeEventListener(e,i,n)}close(){tn(this,Z7)&&clearTimeout(tn(this,Z7)),tn(this,Mc)!==this.CLOSED&&(tn(this,Em)&&tn(this,Em).abort(),$i(this,Mc,this.CLOSED),$i(this,Em,void 0))}};Mc=new WeakMap,h4=new WeakMap,W7=new WeakMap,DU=new WeakMap,$U=new WeakMap,sC=new WeakMap,Z7=new WeakMap,aC=new WeakMap,Em=new WeakMap,V7=new WeakMap,K7=new WeakMap,G7=new WeakMap,nC=new WeakMap,If=new WeakSet,vhe=function(){$i(this,Mc,this.CONNECTING),$i(this,Em,new AbortController),tn(this,$U)(tn(this,h4),Mh(this,If,QVe).call(this)).then(tn(this,yhe)).catch(tn(this,bhe))},yhe=new WeakMap,bhe=new WeakMap,QVe=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...tn(this,aC)?{"Last-Event-ID":tn(this,aC)}:void 0},cache:"no-store",signal:(t=tn(this,Em))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},xhe=new WeakMap,_he=new WeakMap,iC=function(t,e){var r;tn(this,Mc)!==this.CLOSED&&$i(this,Mc,this.CLOSED);let n=new RU("error",{code:e,message:t});(r=tn(this,K7))==null||r.call(this,n),this.dispatchEvent(n)},whe=function(t,e){var r;if(tn(this,Mc)===this.CLOSED)return;$i(this,Mc,this.CONNECTING);let n=new RU("error",{code:e,message:t});(r=tn(this,K7))==null||r.call(this,n),this.dispatchEvent(n),$i(this,Z7,setTimeout(tn(this,She),tn(this,sC)))},She=new WeakMap,m4.CONNECTING=0,m4.OPEN=1,m4.CLOSED=2;function p0r(){let t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}var khe=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},J7=class{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=TU(r?.fetch,r?.requestInit)}async _authThenStart(){var e;if(!this._authProvider)throw new Xo("No auth provider");let r;try{r=await Fh(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(r!=="AUTHORIZED")throw new Xo;return await this._startOrAuth()}async _commonHeaders(){var e;let r={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(r.Authorization=`Bearer ${n.access_token}`)}return this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion),new Headers({...r,...(e=this._requestInit)===null||e===void 0?void 0:e.headers})}_startOrAuth(){var e,r,n;let i=(n=(r=(e=this===null||this===void 0?void 0:this._eventSourceInit)===null||e===void 0?void 0:e.fetch)!==null&&r!==void 0?r:this._fetch)!==null&&n!==void 0?n:fetch;return new Promise((s,a)=>{this._eventSource=new m4(this._url.href,{...this._eventSourceInit,fetch:async(o,c)=>{let u=await this._commonHeaders();u.set("Accept","text/event-stream");let f=await i(o,{...c,headers:u});if(f.status===401&&f.headers.has("www-authenticate")){let{resourceMetadataUrl:d,scope:p}=z7(f);this._resourceMetadataUrl=d,this._scope=p}return f}}),this._abortController=new AbortController,this._eventSource.onerror=o=>{var c;if(o.code===401&&this._authProvider){this._authThenStart().then(s,a);return}let u=new khe(o.code,o.message,o);a(u),(c=this.onerror)===null||c===void 0||c.call(this,u)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",o=>{var c;let u=o;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(f){a(f),(c=this.onerror)===null||c===void 0||c.call(this,f),this.close();return}s()}),this._eventSource.onmessage=o=>{var c,u;let f=o,d;try{d=mm.parse(JSON.parse(f.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,d)}})}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 Xo("No auth provider");if(await Fh(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Xo("Failed to authorize")}async close(){var e,r,n;(e=this._abortController)===null||e===void 0||e.abort(),(r=this._eventSource)===null||r===void 0||r.close(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(e){var r,n,i;if(!this._endpoint)throw new Error("Not connected");try{let s=await this._commonHeaders();s.set("content-type","application/json");let a={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:(r=this._abortController)===null||r===void 0?void 0:r.signal},o=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._endpoint,a);if(!o.ok){if(o.status===401&&this._authProvider){let{resourceMetadataUrl:u,scope:f}=z7(o);if(this._resourceMetadataUrl=u,this._scope=f,await Fh(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Xo;return this.send(e)}let c=await o.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${o.status}): ${c}`)}}catch(s){throw(i=this.onerror)===null||i===void 0||i.call(this,s),s}}setProtocolVersion(e){this._protocolVersion=e}};import{spawn as h0r}from"child_process";var tGe=15e3,m0r=300*1e3,jU=class extends Tr{constructor(r,n,i,s,a){super(new bd("not used"),r.name);this.serverConfig=r;this.name=r.name,this.mcpInteractor=n,this.mcpUserService=i,this.mcpProjectName=s,this.mcpBaseUrl=a}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(r){await this.oauthProvider?.handleCallback(r)}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(r=>setTimeout(r,100)),this.inspectorProcess.killed||this.inspectorProcess.kill("SIGKILL")}catch(r){console.log(`Error killing inspector process: ${r}`)}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(r){console.log(`Error closing transport for ${this.serverConfig.name}: ${r}`)}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(r=>setTimeout(r,100));try{process.kill(this.serverProcessPid,0),process.kill(this.serverProcessPid,"SIGKILL"),console.log(`Force killed with SIGKILL: ${this.serverProcessPid}`)}catch{}}catch(r){r.code!=="ESRCH"&&console.log(`Error killing MCP server process ${this.serverProcessPid}: ${r}`)}this.serverProcessPid=null}console.log(`Closed mcp client ${this.serverConfig.name}`)}async buildTools(r,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 s=await this.toolsPromise;return console.log(`[MCP] Server ${this.serverConfig.name} loaded ${s.length} tools successfully`),s}catch(i){let s=i instanceof Error?i.message:String(i);return this.errorLogged||(this.errorLogged=!0,console.error(`[MCP] Server ${this.serverConfig.name} failed to initialize: ${s}`),console.warn(`[MCP] Server '${this.serverConfig.name}' is unavailable and will be skipped: ${s}`)),[]}}async buildClient(){let r=new wU({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 s=["@modelcontextprotocol/inspector",this.serverConfig.command,...this.serverConfig.args||[]],a={};this.serverConfig.env&&Object.keys(this.serverConfig.env).length>0&&(a.env=this.serverConfig.env),this.serverConfig.cwd&&(a.cwd=this.serverConfig.cwd),console.log(`Starting MCP Inspector process for ${this.serverConfig.name}}`),this.inspectorProcess=h0r("npx",s,{stdio:"inherit",...a}),this.inspectorProcess.on("exit",(o,c)=>{console.log(`MCP Inspector process for ${this.serverConfig.name} exited (code: ${o}, 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 kU(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(r),this.serverConfig.url&&this.wireRemoteReconnect(r),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,r}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 ${tGe}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(r){let n=!!this.serverConfig.url,i=this.serverConfig.oauth2?m0r:tGe,s=async()=>{console.log(`[MCP] ${this.serverConfig.name}: connecting (timeout=${i}ms)...`);let a=r.connect(this.transport),o,c=new Promise((u,f)=>{o=setTimeout(()=>f(new Error(`Connection timeout after ${i}ms`)),i)});try{await Promise.race([a,c])}finally{clearTimeout(o)}};if(!n){await s();return}try{await s(),this._usingLegacySSE=!1}catch(a){let o=a instanceof Error?a.message:String(a),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 s();return}if(!this.shouldFallbackToSSE(o))throw a;console.warn(`[MCP] ${this.serverConfig.name}: StreamableHTTP connection failed (${o}), falling back to legacy SSEClientTransport`);try{await this.transport.close()}catch{}let u=new URL(this.serverConfig.url);this.oauthProvider?this.transport=new J7(u,{authProvider:this.oauthProvider}):this.serverConfig.authToken?this.transport=new J7(u,{requestInit:{headers:{Authorization:`Bearer ${this.serverConfig.authToken}`}}}):this.transport=new J7(u),this._usingLegacySSE=!0,console.log(`[MCP] ${this.serverConfig.name}: retrying with legacy SSE transport`),await s()}}shouldFallbackToSSE(r){return!!(/\b4\d{2}\b/.test(r)||/not supported|method not allowed|unsupported/i.test(r))}wireRemoteReconnect(r){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 s=++this._reconnectAttempts,a=this._reconnectDelay;this._reconnectDelay=Math.min(this._reconnectDelay*2,i),console.warn(`[MCP] ${this.serverConfig.name}: transport closed unexpectedly \u2014 reconnecting in ${a}ms (attempt ${s}/${n})`),setTimeout(async()=>{if(this._killed){console.log(`[MCP] ${this.serverConfig.name}: reconnect cancelled (killed)`);return}console.log(`[MCP] ${this.serverConfig.name}: attempting reconnect #${s}...`),this.clientPromise=void 0,this.toolsPromise=void 0,this.tools=[],this.errorLogged=!1,this._usingLegacySSE=!1,this.transport=this.buildRemoteTransport();try{await this.connectWithTimeout(r),this.wireRemoteReconnect(r),this.clientPromise=Promise.resolve(r),console.log(`[MCP] ${this.serverConfig.name}: reconnected successfully (attempt ${s})`),this._reconnectAttempts=0,this._reconnectDelay=2e3}catch(o){let c=o instanceof Error?o.message:String(o);console.error(`[MCP] ${this.serverConfig.name}: reconnect #${s} failed: ${c}`)}},a)}}buildRemoteTransport(){let r=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 SB(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 H7(r,{authProvider:this.oauthProvider});return this.oauthProvider.setFinishAuth(s=>i.finishAuth(s)),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 H7(r,{requestInit:n})}return console.log(`[MCP] ${this.serverConfig.name}: connecting without authentication`),new H7(r)}async cleanupOnError(){if(console.log(`Cleaning up failed MCP connection for ${this.serverConfig.name}`),this.inspectorProcess){try{this.inspectorProcess.kill("SIGTERM"),await new Promise(r=>setTimeout(r,100)),this.inspectorProcess.killed||this.inspectorProcess.kill("SIGKILL")}catch(r){console.log(`Error killing inspector during cleanup: ${r}`)}this.inspectorProcess=void 0}if(this.transport){try{await this.transport.close()}catch(r){console.log(`Error closing transport during cleanup: ${r}`)}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(r=>setTimeout(r,100));try{process.kill(this.serverProcessPid,0),process.kill(this.serverProcessPid,"SIGKILL"),console.log(`Force killed with SIGKILL: ${this.serverProcessPid}`)}catch{}}catch(r){r.code!=="ESRCH"&&console.log(`Error killing MCP server process ${this.serverProcessPid}: ${r}`)}this.serverProcessPid=null}}async buildInternalTools(r){let n=[];console.log(`[MCP] ${this.serverConfig.name}: listing resource templates...`);try{let i=await r.listResourceTemplates();if(i&&i.templates&&Array.isArray(i.templates)){console.log(`[MCP] ${this.serverConfig.name}: found ${i.templates.length} resource template(s)`);for(let s of i.templates)n.push(this.createResourceTool(this.serverConfig,r,s))}}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 r.listTools();if(i&&i.tools&&Array.isArray(i.tools)){console.log(`[MCP] ${this.serverConfig.name}: found ${i.tools.length} tool(s): ${i.tools.map(s=>s.name).join(", ")}`);for(let s of i.tools)n.push(this.createFunctionTool(this.serverConfig,r,s))}}catch(i){console.warn(`[MCP] Error listing tools from server ${this.serverConfig.name}: ${i}`)}if(this.serverConfig.debug){let i=n.map(s=>`- ${s.function.name}
|
|
1410
1410
|
`).join();console.debug(`[MCP] ${this.serverConfig.name}:
|
|
1411
|
-
${i}`)}return n}createResourceTool(r,n,i){let s
|
|
1411
|
+
${i}`)}return n}sanitizeToolName(r){return r.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,128)}createResourceTool(r,n,i){let s=this.sanitizeToolName(`mcp__${r.id}__${i.name}`),a=async u=>{try{this.lastUsed=Date.now();let f=i.uriTemplate.replace(/\{([^}]+)\}/g,(p,h)=>encodeURIComponent(u[h]||"")),d=await n.readResource({uri:f});if(!d||!d.contents)throw new Error(`No content returned from resource ${i.name}`);return d.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(f){throw console.error(`[MCP] Error retrieving resource ${i.name}: ${f}`),new Error(`Failed to retrieve resource: ${f}`)}},o={},c=i.uriTemplate.match(/\{([^}]+)\}/g)||[];for(let u of c){let f=u.slice(1,-1);o[f]={type:"string",description:`Parameter ${f} for resource ${i.name}`}}return{type:"function",function:{name:s,description:i.description||`Resource from MCP server ${r.name}`,parameters:{type:"object",properties:o},parse:JSON.parse,function:a}}}createFunctionTool(r,n,i){let s=this.sanitizeToolName(`${r.name}__${i.name}`),a=async o=>{this.lastUsed=Date.now(),this.serverConfig.debug&&console.debug(`[MCP] ${s} input:
|
|
1412
1412
|
|
|
1413
1413
|
\`\`\`json
|
|
1414
1414
|
`+JSON.stringify(o)+"\n```");try{let c=await n.callTool({name:i.name,arguments:o});if(this.serverConfig.debug&&console.debug("[MCP] Tool output:\n\n```json\n"+JSON.stringify(c)+"\n```"),c&&"content"in c&&Array.isArray(c.content)){let u=c.content.map(f=>f.type==="text"?f.text:f.type==="image"&&f.data?{type:"image",content:f.data,mimeType:f.mimeType||"image/png",...f.width&&{width:f.width},...f.height&&{height:f.height}}:f.type==="resource"?f.resource:f);return u.length===1?u[0]:u}else if(c&&"toolResult"in c)return c.toolResult;return c}catch(c){throw console.error(`[MCP] Error calling function ${i.name}: ${c}`),new Error(`Failed to call function: ${c}`)}};return{type:"function",function:{name:s,description:i.description||`Function from MCP server ${r.name}`,parameters:{type:"object",properties:i.inputSchema?.properties||{}},parse:JSON.parse,function:a}}}};var oC=class extends Tr{constructor(r,n,i,s){super(r,n,i);this.baseUrl=s}static TYPE="CORE";async buildTools(r,n){return[{type:"function",function:{name:`${this.name}__get_context_info`,description:"Get current contextual information including time, date, username, and conversation URL",parameters:{type:"object",properties:{}},parse:JSON.parse,function:async()=>{let i=new Date,s=r.aiThread?.id??"no-thread",a=r.project.name??"no-project",o={currentTime:i.toISOString(),currentDate:i.toISOString().split("T")[0],dayOfWeek:i.toLocaleDateString("en-US",{weekday:"long"}),username:r.username,threadId:s};if(this.baseUrl){let c=this.baseUrl,u=c.endsWith("://")?"":"/";o.conversationUrl=`${c}${u}project/${a}/thread/${s}`}return JSON.stringify(o,null,2)}}},{type:"function",function:{name:`${this.name}__wait`,description:`Pause execution for a specified number of seconds.
|