@smithery/cli 1.1.3 → 1.1.4

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.
Files changed (2) hide show
  1. package/dist/index.js +1 -1
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -104,7 +104,7 @@ Valid clients are: ${pr.join(", ")}`)),process.exit(1));let t=await ms(r,e);if(!
104
104
  `,Kt.default.cyan(JSON.stringify(n,null,2).replace(/"(\w+)":/g,s=>Kt.default.green(s)).replace(/"([^"]+)"(?=,|\n|\})/g,s=>Kt.default.yellow(s))));let{action:i}=await Ix.default.prompt([{type:"list",name:"action",message:"What would you like to do?",choices:[{name:Kt.default.yellow("\u21A9 Back to primitives"),value:"back"},{name:Kt.default.red("\u2716 Exit"),value:"exit"}]}]);if(i==="exit")return"exit"}}var hR=be(yn());async function pR(r){try{r&&!pr.includes(r)&&(console.error(ru.default.red(`Invalid client: ${r}
105
105
  Valid clients are: ${pr.join(", ")}`)),process.exit(1));let e=Pr.getInstalledServerIds(r);if(e.length===0){console.log(ru.default.yellow(`
106
106
  No MCP servers are currently installed.`));return}let t=Pr.readConfig(r);for(;;){let n=dx(e.map(u=>({qualifiedName:u,name:Pr.denormalizeServerId(u),isInstalled:!0,connections:[]})),!1,!0),{selectedId:i}=await hR.default.prompt([{type:"list",name:"selectedId",message:"Select a server to inspect:",choices:n}]);if(i==="exit"&&process.exit(0),!i)return;console.log(ru.default.blue(`
107
- Connecting to server...`));let s=t.mcpServers[i.id];if("command"in s){let u=await fR(i.id,s);await dR(u)==="exit"&&process.exit(0)}else throw new Error("Only stdio connections are supported")}}catch(e){console.error(ru.default.red("Error during inspection:")),console.error(ru.default.red(e instanceof Error?e.message:String(e))),process.exit(1)}}var jx=class extends Ja{constructor(e,t){super(t),this._serverInfo=e,this._capabilities=t.capabilities,this.setRequestHandler(x2,n=>this._oninitialize(n)),this.setNotificationHandler(m2,()=>{var n;return(n=this.oninitialized)===null||n===void 0?void 0:n.call(this)})}assertCapabilityForMethod(e){var t,n;switch(e){case"sampling/createMessage":if(!(!((t=this._clientCapabilities)===null||t===void 0)&&t.sampling))throw new Error(`Client does not support sampling (required for ${e})`);break;case"roots/list":if(!(!((n=this._clientCapabilities)===null||n===void 0)&&n.roots))throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Server does not support sampling (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"ping":case"initialize":break}}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:yx.includes(t)?t:$c,capabilities:this.getCapabilities(),serverInfo:this._serverInfo}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Fn)}async createMessage(e,t){return this.request({method:"sampling/createMessage",params:e},w2,t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},C2,t)}async sendLoggingMessage(e){return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var A2=be(require("node:process"),1);var Bx=class{constructor(e=A2.default.stdin,t=A2.default.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new Qa,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{var i;(i=this.onerror)===null||i===void 0||i.call(this,n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(var e,t;;)try{let n=this._readBuffer.readMessage();if(n===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,n)}catch(n){(t=this.onerror)===null||t===void 0||t.call(this,n)}}async close(){var e;this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),(e=this.onclose)===null||e===void 0||e.call(this)}send(e){return new Promise(t=>{let n=Rx(e);this._stdout.write(n)?t():this._stdout.once("drain",t)})}};var vR=be(xR());var kx=class{constructor(e){this.context=e}async setupHandlers(e){console.error("[Gateway] Setting up handlers for remote capabilities:",e),e.tools&&this.setupToolHandlers(),e.resources&&this.setupResourceHandlers(),e.prompts&&this.setupPromptHandlers(),console.error("[Gateway] Handlers setup complete")}setupToolHandlers(){this.context.server.setRequestHandler(D2,async e=>(console.error("[Gateway] ListTools request:",JSON.stringify(e,null,2)),await this.context.makeRequest({method:"tools/list",params:{}},Yc))),this.context.server.setRequestHandler(Jc,async e=>{console.error("[Gateway] CallTool request:",JSON.stringify(e,null,2));try{let t=await this.context.makeRequest({method:"tools/call",params:e.params},uR);return console.error("[Gateway] CallTool response:",JSON.stringify(t,null,2)),t}catch(t){throw console.error("[Gateway] CallTool error:",t),t}})}setupResourceHandlers(){this.context.server.setRequestHandler(_2,async e=>this.context.isReconnecting?{resources:[{}]}:(console.error("[Gateway] ListResources request:",JSON.stringify(e,null,2)),await this.context.makeRequest({method:"resources/list",params:{}},Gc))),this.context.server.setRequestHandler(g2,async e=>{console.error("[Gateway] ReadResource request:",JSON.stringify(e,null,2));try{return await this.context.makeRequest({method:"resources/read",params:e.params},Hc)}catch(t){throw console.error("[Gateway] ReadResource error:",t),t}}),this.context.server.setRequestHandler(b2,async e=>(console.error("[Gateway] ListResourceTemplates request:",JSON.stringify(e,null,2)),await this.context.makeRequest({method:"resources/templates/list",params:{}},zc)))}setupPromptHandlers(){this.context.server.setRequestHandler(y2,async e=>(console.error("[Gateway] ListPrompts request:",JSON.stringify(e,null,2)),await this.context.makeRequest({method:"prompts/list",params:{}},Kc))),this.context.server.setRequestHandler(E2,async e=>{console.error("[Gateway] GetPrompt request:",JSON.stringify(e,null,2));try{return await this.context.makeRequest({method:"prompts/get",params:e.params},Zc)}catch(t){throw console.error("[Gateway] GetPrompt error:",t),t}})}};var Mx=class{constructor(){this.closing=!1;this.requestTimeout=O2;this.isReconnecting=!1;this.closing=!1,this.client=new Xa({name:"smithery-runner",version:"1.0.0"},{capabilities:{}})}async makeRequest(e,t){if(!this.client)throw new Error("Client not connected");let n=new AbortController,i=setTimeout(()=>{n.abort("Request timed out")},this.requestTimeout);try{return await this.client.request(e,t,{signal:n.signal})}finally{clearTimeout(i)}}async setupHandlers(e){let t={server:this.server,makeRequest:this.makeRequest.bind(this),isReconnecting:this.isReconnecting};this.handlerManager=new kx(t),await this.handlerManager.setupHandlers(e)}setupErrorHandling(){this.server.onerror=e=>{console.error("[Gateway] Server error:",e),this.closing||this.cleanup().catch(t=>{console.error("[Gateway] Cleanup error during error handling:",t)})},this.client.onerror=async e=>{console.error("[Gateway] client error:",e),this.closing||this.cleanup().catch(t=>{console.error("[Gateway] Cleanup error during error handling:",t)})},this.server.onclose=()=>{console.error("[Gateway] Server closed"),this.closing||this.cleanup().catch(e=>{console.error("[Gateway] Cleanup error during close:",e)})},this.client.onclose=async()=>{console.error("[Gateway] client closed"),this.closing||this.cleanup().catch(e=>{console.error("[Gateway] Cleanup error during close:",e)})},process.on("SIGINT",()=>this.cleanup()),process.on("SIGTERM",()=>this.cleanup())}async cleanup(){if(!this.closing){this.closing=!0,console.error("[Gateway] Starting cleanup...");try{this.client&&(console.error("[Gateway] Closing client..."),await this.client.close()),this.server&&(console.error("[Gateway] Closing server..."),await this.server.close()),console.error("[Gateway] Cleanup completed"),process.exit(0)}catch(e){console.error("[Gateway] Fatal error during cleanup:",e),process.exit(1)}}}async connect(e,t,n){let i=e.connections.find(A=>A.type==="stdio");if(!i)throw new Error("No STDIO connection found");let s=await tx(i,t),u=await fetch(`${ix}/servers/${e.qualifiedName}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({connectionType:"stdio",config:s,userId:n})});if(!u.ok)throw new Error(`Failed to get server configuration: ${u.statusText}`);let{result:c}=await u.json(),f=c;console.error("[Gateway] Server configuration:",f);let{command:d,args:v,env:g}=f,w=null;try{let O={...F2(),...g||{}};w=new eu({command:d,args:v||[],env:O,stderr:"pipe"}),w.onerror=K=>{console.error("[Gateway] STDIO transport error:",K),this.cleanup().catch(ae=>{console.error("[Gateway] Cleanup error during transport error:",ae)})},await this.client.connect(w);let P=this.client.getServerCapabilities()||{};console.error("[Gateway] Child process capabilities:",P),this.server=new jx({name:`smithery-runner-${e.qualifiedName}`,version:"1.0.0"},{capabilities:P}),this.setupErrorHandling(),await this.setupHandlers(P);let I=new Bx;if(await this.server.connect(I),console.error("[Gateway] STDIO server ready"),w.stderr&&w.stderr.on("data",K=>{console.error("[Gateway] Child process stderr:",K.toString())}),n){let K=I.onmessage?.bind(I);I.onmessage=ae=>{let{data:ve,error:pe}=Jc.safeParse(ae);!pe&&t2&&fetch(t2,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({eventName:"tool_call",payload:{connectionType:"stdio",serverQualifiedName:e.qualifiedName,toolParams:(0,vR.pick)(ve.params,"name")}})}),K?.(ae)}}}catch(A){if(console.error("[Gateway] Error during STDIO setup:",A),w)try{await w.close()}catch(O){console.error("[Gateway] Error closing transport during error recovery:",O)}throw A}let q=()=>{w&&!this.closing&&(console.error("[Gateway] Process termination detected, cleaning up..."),this.cleanup().catch(A=>{console.error("[Gateway] Cleanup error during process termination:",A),process.exit(1)}))};process.once("SIGTERM",q),process.once("SIGINT",q)}};var CDe="mcp",Lx=class{constructor(e){this._url=e}start(){if(this._socket)throw new Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,t)=>{this._socket=new WebSocket(this._url,CDe),this._socket.onerror=n=>{var i;let s="error"in n?n.error:new Error(`WebSocket error: ${JSON.stringify(n)}`);t(s),(i=this.onerror)===null||i===void 0||i.call(this,s)},this._socket.onopen=()=>{e()},this._socket.onclose=()=>{var n;(n=this.onclose)===null||n===void 0||n.call(this)},this._socket.onmessage=n=>{var i,s;let u;try{u=wx.parse(JSON.parse(n.data))}catch(c){(i=this.onerror)===null||i===void 0||i.call(this,c);return}(s=this.onmessage)===null||s===void 0||s.call(this,u)}})}async close(){var e;(e=this._socket)===null||e===void 0||e.close()}send(e){return new Promise((t,n)=>{var i;if(!this._socket){n(new Error("Not connected"));return}(i=this._socket)===null||i===void 0||i.send(JSON.stringify(e)),t()})}};function mR(r,e){let t=new URL(r);if(e){let n=typeof window<"u"?btoa(JSON.stringify(e)):Buffer.from(JSON.stringify(e)).toString("base64");t.searchParams.set("config",n)}return t}var Qwe=be(yR(),1),eSe=be(K2(),1),rSe=be(J2(),1),WI=be(i6(),1),tSe=be(UI(),1);var $I=WI.default;global.WebSocket=$I;var VI=3,nSe=1e3,GI=(r,e)=>{let t=new URL("/ws",r.replace(/^http/,"ws")).toString();return new Lx(mR(t,e))},zI=async(r,e)=>{let t=0,n="",i=!1,s=GI(r,e),u=(g,w)=>(console.error(`${w}:`,g.message),g),c=async g=>{if(n+=g.toString("utf8"),!i)return;let w=n.split(/\r?\n/);n=w.pop()??"";for(let q of w.filter(Boolean))try{await s.send(JSON.parse(q))}catch(A){if(A instanceof Error&&A.message.includes("CLOSED"))throw new Error("WebSocket closed");u(A,"Failed to send message")}},f=async()=>{console.error(`Connecting to WebSocket endpoint: ${r}`),s.onclose=async()=>{console.error("WebSocket connection closed"),i=!1,t++<VI?(await new Promise(g=>setTimeout(g,nSe*Math.pow(2,t))),s=GI(r,e),await f()):(console.error(`Max reconnection attempts (${VI}) reached`),process.exit(1))},s.onerror=g=>{u(g,"WebSocket connection error"),process.exit(1)},s.onmessage=g=>{try{"error"in g&&s.onerror?.(new Error(`WebSocket error: ${JSON.stringify(g.error)}`)),console.log(JSON.stringify(g))}catch(w){u(w,"Error handling message"),console.error("Raw message data:",JSON.stringify(g)),console.log(JSON.stringify(g))}},await s.start(),i=!0,await c(Buffer.from(""))},d=async()=>{console.error("Starting cleanup..."),await s.close().catch(g=>u(g,"Error during cleanup")),console.error("Cleanup completed")},v=async()=>{console.error("Shutting down WS Runner..."),await d(),process.exit(0)};return process.on("SIGINT",v),process.on("SIGTERM",v),process.stdin.on("data",g=>c(g).catch(w=>u(w,"Error processing message"))),await f(),d};async function HI(r,e,t){let n=r.connections.some(s=>s.type==="ws"),i=r.connections.some(s=>s.type==="stdio");if(n){let s=r.connections.find(u=>u.type==="ws");if(!s?.deploymentUrl)throw new Error("Missing deployment URL");await zI(s.deploymentUrl,e)}else if(i)await new Mx().connect(r,e,t);else throw new Error("No connection types found. Server not deployed.")}async function KI(r,e){try{let t=new ka,[n]=await Promise.all([ms(r),t.initialize()]);if(!n)throw new Error(`Could not resolve server: ${r}`);console.error("[Runner] Connecting to server:",{id:n.qualifiedName,connectionTypes:n.connections.map(s=>s.type)});let i=t.getAnalyticsConsent()?t.getUserId():void 0;await HI(n,e,i)}catch(t){console.error("[Runner] Fatal error:",t),process.exit(1)}}var YI=be(Re()),iSe=process.argv[2],Us=process.argv[3],o6=process.argv.indexOf("--client"),ZI=process.argv.indexOf("--config"),cl=o6!==-1?process.argv[o6+1]:"claude",sSe=ZI!==-1?(()=>{let r=JSON.parse(process.argv[ZI+1]);return typeof r=="string"&&(r=JSON.parse(r)),r})():{};async function oSe(){switch(iSe){case"inspect":await pR(cl);break;case"install":Us||(console.error("Please provide a package name to install"),process.exit(1)),o6===-1&&console.log(YI.default.yellow("Client not provided, defaulting to claude")),await FP(Us,cl);break;case"uninstall":await qP(Us,cl);break;case"installed":await px(cl);break;case"view":Us||(console.error("Please provide a package ID to get details"),process.exit(1)),await WP(Us,cl);break;case"run":Us||(console.error("Please provide a server ID to run"),process.exit(1)),await KI(Us,sSe);break;default:console.log("Available commands:"),console.log(" install <package> Install a package"),console.log(" --client <name> Specify the AI client"),console.log(" uninstall [package] Uninstall a package"),console.log(" installed List installed packages"),console.log(" view <package> Get details for a specific package"),console.log(" inspect Inspect installed servers"),console.log(" run <server-id> Run a server"),process.exit(1)}}oSe();
107
+ Connecting to server...`));let s=t.mcpServers[i.id];if("command"in s){let u=await fR(i.id,s);await dR(u)==="exit"&&process.exit(0)}else throw new Error("Only stdio connections are supported")}}catch(e){console.error(ru.default.red("Error during inspection:")),console.error(ru.default.red(e instanceof Error?e.message:String(e))),process.exit(1)}}var jx=class extends Ja{constructor(e,t){super(t),this._serverInfo=e,this._capabilities=t.capabilities,this.setRequestHandler(x2,n=>this._oninitialize(n)),this.setNotificationHandler(m2,()=>{var n;return(n=this.oninitialized)===null||n===void 0?void 0:n.call(this)})}assertCapabilityForMethod(e){var t,n;switch(e){case"sampling/createMessage":if(!(!((t=this._clientCapabilities)===null||t===void 0)&&t.sampling))throw new Error(`Client does not support sampling (required for ${e})`);break;case"roots/list":if(!(!((n=this._clientCapabilities)===null||n===void 0)&&n.roots))throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Server does not support sampling (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"ping":case"initialize":break}}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:yx.includes(t)?t:$c,capabilities:this.getCapabilities(),serverInfo:this._serverInfo}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Fn)}async createMessage(e,t){return this.request({method:"sampling/createMessage",params:e},w2,t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},C2,t)}async sendLoggingMessage(e){return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var A2=be(require("node:process"),1);var Bx=class{constructor(e=A2.default.stdin,t=A2.default.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new Qa,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{var i;(i=this.onerror)===null||i===void 0||i.call(this,n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(var e,t;;)try{let n=this._readBuffer.readMessage();if(n===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,n)}catch(n){(t=this.onerror)===null||t===void 0||t.call(this,n)}}async close(){var e;this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),(e=this.onclose)===null||e===void 0||e.call(this)}send(e){return new Promise(t=>{let n=Rx(e);this._stdout.write(n)?t():this._stdout.once("drain",t)})}};var vR=be(xR());var kx=class{constructor(e){this.context=e}async setupHandlers(e){console.error("[Gateway] Setting up handlers for remote capabilities:",e),e.tools&&this.setupToolHandlers(),e.resources&&this.setupResourceHandlers(),e.prompts&&this.setupPromptHandlers(),console.error("[Gateway] Handlers setup complete")}setupToolHandlers(){this.context.server.setRequestHandler(D2,async e=>(console.error("[Gateway] ListTools request:",JSON.stringify(e,null,2)),await this.context.makeRequest({method:"tools/list",params:{}},Yc))),this.context.server.setRequestHandler(Jc,async e=>{console.error("[Gateway] CallTool request:",JSON.stringify(e,null,2));try{let t=await this.context.makeRequest({method:"tools/call",params:e.params},uR);return console.error("[Gateway] CallTool response:",JSON.stringify(t,null,2)),t}catch(t){throw console.error("[Gateway] CallTool error:",t),t}})}setupResourceHandlers(){this.context.server.setRequestHandler(_2,async e=>this.context.isReconnecting?{resources:[{}]}:(console.error("[Gateway] ListResources request:",JSON.stringify(e,null,2)),await this.context.makeRequest({method:"resources/list",params:{}},Gc))),this.context.server.setRequestHandler(g2,async e=>{console.error("[Gateway] ReadResource request:",JSON.stringify(e,null,2));try{return await this.context.makeRequest({method:"resources/read",params:e.params},Hc)}catch(t){throw console.error("[Gateway] ReadResource error:",t),t}}),this.context.server.setRequestHandler(b2,async e=>(console.error("[Gateway] ListResourceTemplates request:",JSON.stringify(e,null,2)),await this.context.makeRequest({method:"resources/templates/list",params:{}},zc)))}setupPromptHandlers(){this.context.server.setRequestHandler(y2,async e=>(console.error("[Gateway] ListPrompts request:",JSON.stringify(e,null,2)),await this.context.makeRequest({method:"prompts/list",params:{}},Kc))),this.context.server.setRequestHandler(E2,async e=>{console.error("[Gateway] GetPrompt request:",JSON.stringify(e,null,2));try{return await this.context.makeRequest({method:"prompts/get",params:e.params},Zc)}catch(t){throw console.error("[Gateway] GetPrompt error:",t),t}})}};var Mx=class{constructor(){this.closing=!1;this.requestTimeout=O2;this.isReconnecting=!1;this.closing=!1,this.client=new Xa({name:"smithery-runner",version:"1.0.0"},{capabilities:{}})}async makeRequest(e,t){if(!this.client)throw new Error("Client not connected");let n=new AbortController,i=setTimeout(()=>{n.abort("Request timed out")},this.requestTimeout);try{return await this.client.request(e,t,{signal:n.signal})}finally{clearTimeout(i)}}async setupHandlers(e){let t={server:this.server,makeRequest:this.makeRequest.bind(this),isReconnecting:this.isReconnecting};this.handlerManager=new kx(t),await this.handlerManager.setupHandlers(e)}setupErrorHandling(){this.server.onerror=e=>{console.error("[Gateway] Server error:",e),this.closing||this.cleanup().catch(t=>{console.error("[Gateway] Cleanup error during error handling:",t)})},this.client.onerror=async e=>{console.error("[Gateway] client error:",e),this.closing||this.cleanup().catch(t=>{console.error("[Gateway] Cleanup error during error handling:",t)})},this.server.onclose=()=>{console.error("[Gateway] Server closed"),this.closing||this.cleanup().catch(e=>{console.error("[Gateway] Cleanup error during close:",e)})},this.client.onclose=async()=>{console.error("[Gateway] client closed"),this.closing||this.cleanup().catch(e=>{console.error("[Gateway] Cleanup error during close:",e)})},process.on("SIGINT",()=>this.cleanup()),process.on("SIGTERM",()=>this.cleanup())}async cleanup(){if(!this.closing){this.closing=!0,console.error("[Gateway] Starting cleanup...");try{this.client&&(console.error("[Gateway] Closing client..."),await this.client.close()),this.server&&(console.error("[Gateway] Closing server..."),await this.server.close()),console.error("[Gateway] Cleanup completed"),process.exit(0)}catch(e){console.error("[Gateway] Fatal error during cleanup:",e),process.exit(1)}}}async connect(e,t,n){let i=e.connections.find(A=>A.type==="stdio");if(!i)throw new Error("No STDIO connection found");let s=await tx(i,t),u=await fetch(`${ix}/servers/${e.qualifiedName}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({connectionType:"stdio",config:s,userId:n})});if(!u.ok)throw new Error(`Failed to get server configuration: ${u.statusText}`);let{result:c}=await u.json(),f=c;console.error("[Gateway] Server configuration:",f);let{command:d,args:v,env:g}=f,w=null;try{let O={...F2(),...g||{}};w=new eu({command:d,args:v||[],env:O,stderr:"pipe"}),w.onerror=K=>{console.error("[Gateway] STDIO transport error:",K),this.cleanup().catch(ae=>{console.error("[Gateway] Cleanup error during transport error:",ae)})},await this.client.connect(w);let P=this.client.getServerCapabilities()||{};console.error("[Gateway] Child process capabilities:",P),this.server=new jx({name:`smithery-runner-${e.qualifiedName}`,version:"1.0.0"},{capabilities:P}),this.setupErrorHandling(),await this.setupHandlers(P);let I=new Bx;if(await this.server.connect(I),console.error("[Gateway] STDIO server ready"),w.stderr&&w.stderr.on("data",K=>{console.error("[Gateway] Child process stderr:",K.toString())}),n){let K=I.onmessage?.bind(I);I.onmessage=ae=>{let{data:ve,error:pe}=Jc.safeParse(ae);!pe&&t2&&fetch(t2,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({eventName:"tool_call",payload:{connectionType:"stdio",serverQualifiedName:e.qualifiedName,toolParams:(0,vR.pick)(ve.params,"name")}})}),K?.(ae)}}}catch(A){if(console.error("[Gateway] Error during STDIO setup:",A),w)try{await w.close()}catch(O){console.error("[Gateway] Error closing transport during error recovery:",O)}throw A}let q=()=>{w&&!this.closing&&(console.error("[Gateway] Process termination detected, cleaning up..."),this.cleanup().catch(A=>{console.error("[Gateway] Cleanup error during process termination:",A),process.exit(1)}))};process.once("SIGTERM",q),process.once("SIGINT",q)}};var CDe="mcp",Lx=class{constructor(e){this._url=e}start(){if(this._socket)throw new Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,t)=>{this._socket=new WebSocket(this._url,CDe),this._socket.onerror=n=>{var i;let s="error"in n?n.error:new Error(`WebSocket error: ${JSON.stringify(n)}`);t(s),(i=this.onerror)===null||i===void 0||i.call(this,s)},this._socket.onopen=()=>{e()},this._socket.onclose=()=>{var n;(n=this.onclose)===null||n===void 0||n.call(this)},this._socket.onmessage=n=>{var i,s;let u;try{u=wx.parse(JSON.parse(n.data))}catch(c){(i=this.onerror)===null||i===void 0||i.call(this,c);return}(s=this.onmessage)===null||s===void 0||s.call(this,u)}})}async close(){var e;(e=this._socket)===null||e===void 0||e.close()}send(e){return new Promise((t,n)=>{var i;if(!this._socket){n(new Error("Not connected"));return}(i=this._socket)===null||i===void 0||i.send(JSON.stringify(e)),t()})}};function mR(r,e){let t=new URL(r);if(e){let n=typeof window<"u"?btoa(JSON.stringify(e)):Buffer.from(JSON.stringify(e)).toString("base64");t.searchParams.set("config",n)}return t}var Qwe=be(yR(),1),eSe=be(K2(),1),rSe=be(J2(),1),WI=be(i6(),1),tSe=be(UI(),1);var $I=WI.default;global.WebSocket=$I;var VI=3,nSe=1e3,GI=(r,e)=>{let t=new URL("/ws",r.replace(/^http/,"ws")).toString();return new Lx(mR(t,e))},zI=async(r,e)=>{let t=0,n="",i=!1,s=GI(r,e),u=(g,w)=>(console.error(`${w}:`,g.message),g),c=async g=>{if(n+=g.toString("utf8"),!i)return;let w=n.split(/\r?\n/);n=w.pop()??"";for(let q of w.filter(Boolean))try{await s.send(JSON.parse(q))}catch(A){if(A instanceof Error&&A.message.includes("CLOSED"))throw new Error("WebSocket closed");u(A,"Failed to send message")}},f=async()=>{console.error(`Connecting to WebSocket endpoint: ${r}`),s.onclose=async()=>{console.error("WebSocket connection closed"),i=!1,t++<VI?(await new Promise(g=>setTimeout(g,nSe*Math.pow(2,t))),s=GI(r,e),await f()):(console.error(`Max reconnection attempts (${VI}) reached`),process.exit(1))},s.onerror=g=>{u(g,"WebSocket connection error"),process.exit(1)},s.onmessage=g=>{try{"error"in g&&(console.error(`WebSocket error: ${JSON.stringify(g.error)}`),(g.error.message==="Missing configuration"||g.error.message==="Invalid configuration")&&process.exit(1)),console.log(JSON.stringify(g))}catch(w){u(w,"Error handling message"),console.error("Raw message data:",JSON.stringify(g)),console.log(JSON.stringify(g))}},await s.start(),i=!0,await c(Buffer.from(""))},d=async()=>{console.error("Starting cleanup..."),await s.close().catch(g=>u(g,"Error during cleanup")),console.error("Cleanup completed")},v=async()=>{console.error("Shutting down WS Runner..."),await d(),process.exit(0)};return process.on("SIGINT",v),process.on("SIGTERM",v),process.stdin.on("data",g=>c(g).catch(w=>u(w,"Error processing message"))),await f(),d};async function HI(r,e,t){let n=r.connections.some(s=>s.type==="ws"),i=r.connections.some(s=>s.type==="stdio");if(n){let s=r.connections.find(u=>u.type==="ws");if(!s?.deploymentUrl)throw new Error("Missing deployment URL");await zI(s.deploymentUrl,e)}else if(i)await new Mx().connect(r,e,t);else throw new Error("No connection types found. Server not deployed.")}async function KI(r,e){try{let t=new ka,[n]=await Promise.all([ms(r),t.initialize()]);if(!n)throw new Error(`Could not resolve server: ${r}`);console.error("[Runner] Connecting to server:",{id:n.qualifiedName,connectionTypes:n.connections.map(s=>s.type)});let i=t.getAnalyticsConsent()?t.getUserId():void 0;await HI(n,e,i)}catch(t){console.error("[Runner] Fatal error:",t),process.exit(1)}}var YI=be(Re()),iSe=process.argv[2],Us=process.argv[3],o6=process.argv.indexOf("--client"),ZI=process.argv.indexOf("--config"),cl=o6!==-1?process.argv[o6+1]:"claude",sSe=ZI!==-1?(()=>{let r=JSON.parse(process.argv[ZI+1]);return typeof r=="string"&&(r=JSON.parse(r)),r})():{};async function oSe(){switch(iSe){case"inspect":await pR(cl);break;case"install":Us||(console.error("Please provide a package name to install"),process.exit(1)),o6===-1&&console.log(YI.default.yellow("Client not provided, defaulting to claude")),await FP(Us,cl);break;case"uninstall":await qP(Us,cl);break;case"installed":await px(cl);break;case"view":Us||(console.error("Please provide a package ID to get details"),process.exit(1)),await WP(Us,cl);break;case"run":Us||(console.error("Please provide a server ID to run"),process.exit(1)),await KI(Us,sSe);break;default:console.log("Available commands:"),console.log(" install <package> Install a package"),console.log(" --client <name> Specify the AI client"),console.log(" uninstall [package] Uninstall a package"),console.log(" installed List installed packages"),console.log(" view <package> Get details for a specific package"),console.log(" inspect Inspect installed servers"),console.log(" run <server-id> Run a server"),process.exit(1)}}oSe();
108
108
  /*! Bundled license information:
109
109
 
110
110
  safe-buffer/index.js:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@smithery/cli",
3
- "version": "1.1.3",
3
+ "version": "1.1.4",
4
4
  "type": "commonjs",
5
5
  "private": false,
6
6
  "homepage": "https://smithery.ai/",