@onyxsecurity/mcp-gateway 1.0.4 → 1.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin/mcp-gateway.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Client as e,ConfigurationError as t,ProcessSpawnError as n,ProxyConnectionError as r,ReadBuffer as i,SSEClientTransport as a,Server as o,StdioServerTransport as s,StreamableHTTPClientTransport as c,TransportError as l,__commonJSMin as u,__toESM as d,addBreadcrumbSafe as f,addGlobalTags as p,captureExceptionSafe as m,config as h,createParser as g,initSentrySafe as ee,initializeTrafficMirror as _,logger as v,proxyServer as y,serializeMessage as te,startHTTPServer as ne}from"../stdio-
|
|
2
|
+
import{Client as e,ConfigurationError as t,ProcessSpawnError as n,ProxyConnectionError as r,ReadBuffer as i,SSEClientTransport as a,Server as o,StdioServerTransport as s,StreamableHTTPClientTransport as c,TransportError as l,__commonJSMin as u,__toESM as d,addBreadcrumbSafe as f,addGlobalTags as p,captureExceptionSafe as m,config as h,createParser as g,initSentrySafe as ee,initializeTrafficMirror as _,logger as v,proxyServer as y,serializeMessage as te,startHTTPServer as ne}from"../stdio-7bVg-CUZ.js";import{createRequire as re}from"node:module";import{readFileSync as b,readdirSync as x}from"node:fs";import{basename as ie,dirname as ae,extname as oe,join as se,normalize as ce,relative as le,resolve as ue}from"path";import{format as de,inspect as fe}from"util";import{fileURLToPath as pe}from"url";import{setTimeout as me}from"node:timers";import he from"node:util";import{notStrictEqual as ge,strictEqual as S}from"assert";import{readFileSync as _e,readdirSync as ve,statSync as ye,writeFile as be}from"fs";import{spawn as xe}from"node:child_process";import{PassThrough as Se,Transform as Ce}from"node:stream";var we=class extends Event{constructor(e,t){super(e),this.code=t?.code??void 0,this.message=t?.message??void 0}[Symbol.for(`nodejs.util.inspect.custom`)](e,t,n){return n(De(this),t)}[Symbol.for(`Deno.customInspect`)](e,t){return e(De(this),t)}};function Te(e){let t=globalThis.DOMException;return typeof t==`function`?new t(e,`SyntaxError`):SyntaxError(e)}function Ee(e){return e instanceof Error?`errors`in e&&Array.isArray(e.errors)?e.errors.map(Ee).join(`, `):`cause`in e&&e.cause instanceof Error?`${e}: ${Ee(e.cause)}`:e.message:`${e}`}function De(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var Oe=e=>{throw TypeError(e)},ke=(e,t,n)=>t.has(e)||Oe(`Cannot `+n),C=(e,t,n)=>(ke(e,t,`read from private field`),n?n.call(e):t.get(e)),w=(e,t,n)=>t.has(e)?Oe(`Cannot add the same private member more than once`):t instanceof WeakSet?t.add(e):t.set(e,n),T=(e,t,n,r)=>(ke(e,t,`write to private field`),t.set(e,n),n),Ae=(e,t,n)=>(ke(e,t,`access private method`),n),E,je,Me,Ne,Pe,Fe,Ie,Le,Re,ze,Be,Ve,He,D,Ue,We,Ge,Ke,qe,Je,Ye,Xe,Ze,Qe=class extends EventTarget{constructor(e,t){super(),w(this,D),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,w(this,E),w(this,je),w(this,Me),w(this,Ne),w(this,Pe),w(this,Fe),w(this,Ie),w(this,Le,null),w(this,Re),w(this,ze),w(this,Be,null),w(this,Ve,null),w(this,He,null),w(this,We,async e=>{var t;C(this,ze).reset();let{body:n,redirected:r,status:i,headers:a}=e;if(i===204){Ae(this,D,Ye).call(this,`Server sent HTTP 204, not reconnecting`,204),this.close();return}if(r?T(this,Me,new URL(e.url)):T(this,Me,void 0),i!==200){Ae(this,D,Ye).call(this,`Non-200 status code (${i})`,i);return}if(!(a.get(`content-type`)||``).startsWith(`text/event-stream`)){Ae(this,D,Ye).call(this,`Invalid content type, expected "text/event-stream"`,i);return}if(C(this,E)===this.CLOSED)return;T(this,E,this.OPEN);let o=new Event(`open`);if((t=C(this,He))==null||t.call(this,o),this.dispatchEvent(o),typeof n!=`object`||!n||!(`getReader`in n)){Ae(this,D,Ye).call(this,`Invalid response body, expected a web ReadableStream`,i),this.close();return}let s=new TextDecoder,c=n.getReader(),l=!0;do{let{done:e,value:t}=await c.read();t&&C(this,ze).feed(s.decode(t,{stream:!e})),e&&(l=!1,C(this,ze).reset(),Ae(this,D,Xe).call(this))}while(l)}),w(this,Ge,e=>{T(this,Re,void 0),!(e.name===`AbortError`||e.type===`aborted`)&&Ae(this,D,Xe).call(this,Ee(e))}),w(this,qe,e=>{typeof e.id==`string`&&T(this,Le,e.id);let t=new MessageEvent(e.event||`message`,{data:e.data,origin:C(this,Me)?C(this,Me).origin:C(this,je).origin,lastEventId:e.id||``});C(this,Ve)&&(!e.event||e.event===`message`)&&C(this,Ve).call(this,t),this.dispatchEvent(t)}),w(this,Je,e=>{T(this,Fe,e)}),w(this,Ze,()=>{T(this,Ie,void 0),C(this,E)===this.CONNECTING&&Ae(this,D,Ue).call(this)});try{if(e instanceof URL)T(this,je,e);else if(typeof e==`string`)T(this,je,new URL(e,$e()));else throw Error(`Invalid URL`)}catch{throw Te(`An invalid or illegal string was specified`)}T(this,ze,g({onEvent:C(this,qe),onRetry:C(this,Je)})),T(this,E,this.CONNECTING),T(this,Fe,3e3),T(this,Pe,t?.fetch??globalThis.fetch),T(this,Ne,t?.withCredentials??!1),Ae(this,D,Ue).call(this)}get readyState(){return C(this,E)}get url(){return C(this,je).href}get withCredentials(){return C(this,Ne)}get onerror(){return C(this,Be)}set onerror(e){T(this,Be,e)}get onmessage(){return C(this,Ve)}set onmessage(e){T(this,Ve,e)}get onopen(){return C(this,He)}set onopen(e){T(this,He,e)}addEventListener(e,t,n){let r=t;super.addEventListener(e,r,n)}removeEventListener(e,t,n){let r=t;super.removeEventListener(e,r,n)}close(){C(this,Ie)&&clearTimeout(C(this,Ie)),C(this,E)!==this.CLOSED&&(C(this,Re)&&C(this,Re).abort(),T(this,E,this.CLOSED),T(this,Re,void 0))}};E=new WeakMap,je=new WeakMap,Me=new WeakMap,Ne=new WeakMap,Pe=new WeakMap,Fe=new WeakMap,Ie=new WeakMap,Le=new WeakMap,Re=new WeakMap,ze=new WeakMap,Be=new WeakMap,Ve=new WeakMap,He=new WeakMap,D=new WeakSet,Ue=function(){T(this,E,this.CONNECTING),T(this,Re,new AbortController),C(this,Pe)(C(this,je),Ae(this,D,Ke).call(this)).then(C(this,We)).catch(C(this,Ge))},We=new WeakMap,Ge=new WeakMap,Ke=function(){let e={mode:`cors`,redirect:`follow`,headers:{Accept:`text/event-stream`,...C(this,Le)?{"Last-Event-ID":C(this,Le)}:void 0},cache:`no-store`,signal:C(this,Re)?.signal};return`window`in globalThis&&(e.credentials=this.withCredentials?`include`:`same-origin`),e},qe=new WeakMap,Je=new WeakMap,Ye=function(e,t){var n;C(this,E)!==this.CLOSED&&T(this,E,this.CLOSED);let r=new we(`error`,{code:t,message:e});(n=C(this,Be))==null||n.call(this,r),this.dispatchEvent(r)},Xe=function(e,t){var n;if(C(this,E)===this.CLOSED)return;T(this,E,this.CONNECTING);let r=new we(`error`,{code:t,message:e});(n=C(this,Be))==null||n.call(this,r),this.dispatchEvent(r),T(this,Ie,setTimeout(C(this,Ze),C(this,Fe)))},Ze=new WeakMap,Qe.CONNECTING=0,Qe.OPEN=1,Qe.CLOSED=2;function $e(){let e=`document`in globalThis?globalThis.document:void 0;return e&&typeof e==`object`&&`baseURI`in e&&typeof e.baseURI==`string`?e.baseURI:void 0}const et={right:at,center:ot};var tt=class{constructor(e){this.width=e.width,this.wrap=e.wrap??!0,this.rows=[]}span(...e){let t=this.div(...e);t.span=!0}resetOutput(){this.rows=[]}div(...e){if(e.length===0&&this.div(``),this.wrap&&this.shouldApplyLayoutDSL(...e)&&typeof e[0]==`string`)return this.applyLayoutDSL(e[0]);let t=e.map(e=>typeof e==`string`?this.colFromString(e):e);return this.rows.push(t),t}shouldApplyLayoutDSL(...e){return e.length===1&&typeof e[0]==`string`&&/[\t\n]/.test(e[0])}applyLayoutDSL(e){let t=e.split(`
|
|
3
3
|
`).map(e=>e.split(` `)),n=0;return t.forEach(e=>{e.length>1&&O.stringWidth(e[0])>n&&(n=Math.min(Math.floor(this.width*.5),O.stringWidth(e[0])))}),t.forEach(e=>{this.div(...e.map((t,r)=>({text:t.trim(),padding:this.measurePadding(t),width:r===0&&e.length>1?n:void 0})))}),this.rows[this.rows.length-1]}colFromString(e){return{text:e,padding:this.measurePadding(e)}}measurePadding(e){let t=O.stripAnsi(e);return[0,t.match(/\s*$/)[0].length,0,t.match(/^\s*/)[0].length]}toString(){let e=[];return this.rows.forEach(t=>{this.rowToString(t,e)}),e.filter(e=>!e.hidden).map(e=>e.text).join(`
|
|
4
4
|
`)}rowToString(e,t){return this.rasterize(e).forEach((n,r)=>{let i=``;n.forEach((n,a)=>{let{width:o}=e[a],s=this.negatePadding(e[a]),c=n;if(s>O.stringWidth(n)&&(c+=` `.repeat(s-O.stringWidth(n))),e[a].align&&e[a].align!==`left`&&this.wrap){let t=et[e[a].align];c=t(c,s),O.stringWidth(c)<s&&(c+=` `.repeat((o||0)-O.stringWidth(c)-1))}let l=e[a].padding||[0,0,0,0];l[3]&&(i+=` `.repeat(l[3])),i+=nt(e[a],c,`| `),i+=c,i+=nt(e[a],c,` |`),l[1]&&(i+=` `.repeat(l[1])),r===0&&t.length>0&&(i=this.renderInline(i,t[t.length-1]))}),t.push({text:i.replace(/ +$/,``),span:e.span})}),t}renderInline(e,t){let n=e.match(/^ */),r=n?n[0].length:0,i=t.text,a=O.stringWidth(i.trimRight());return t.span?this.wrap?r<a?e:(t.hidden=!0,i.trimRight()+` `.repeat(r-a)+e.trimLeft()):(t.hidden=!0,i+e):e}rasterize(e){let t=[],n=this.columnWidths(e),r;return e.forEach((e,i)=>{e.width=n[i],r=this.wrap?O.wrap(e.text,this.negatePadding(e),{hard:!0}).split(`
|
|
5
5
|
`):e.text.split(`
|
|
@@ -90,7 +90,6 @@ complete -o bashdefault -o default -F _{{app_name}}_yargs_completions {{app_name
|
|
|
90
90
|
`),void 0,`versionWarning`),I(this,G,`f`).key[e]=!0,t.alias&&this.alias(e,t.alias);let n=t.deprecate||t.deprecated;n&&this.deprecateOption(e,n);let r=t.demand||t.required||t.require;r&&this.demand(e,r),t.demandOption&&this.demandOption(e,typeof t.demandOption==`string`?t.demandOption:void 0),t.conflicts&&this.conflicts(e,t.conflicts),`default`in t&&this.default(e,t.default),t.implies!==void 0&&this.implies(e,t.implies),t.nargs!==void 0&&this.nargs(e,t.nargs),t.config&&this.config(e,t.configParser),t.normalize&&this.normalize(e),t.choices&&this.choices(e,t.choices),t.coerce&&this.coerce(e,t.coerce),t.group&&this.group(e,t.group),(t.boolean||t.type===`boolean`)&&(this.boolean(e),t.alias&&this.boolean(t.alias)),(t.array||t.type===`array`)&&(this.array(e),t.alias&&this.array(t.alias)),(t.number||t.type===`number`)&&(this.number(e),t.alias&&this.number(t.alias)),(t.string||t.type===`string`)&&(this.string(e),t.alias&&this.string(t.alias)),(t.count||t.type===`count`)&&this.count(e),typeof t.global==`boolean`&&this.global(e,t.global),t.defaultDescription&&(I(this,G,`f`).defaultDescription[e]=t.defaultDescription),t.skipValidation&&this.skipValidation(e);let i=t.describe||t.description||t.desc,a=I(this,J,`f`).getDescriptions();(!Object.prototype.hasOwnProperty.call(a,e)||typeof i==`string`)&&this.describe(e,i),t.hidden&&this.hide(e),t.requiresArg&&this.requiresArg(e)}return this}options(e,t){return this.option(e,t)}parse(e,t,n){P(`[string|array] [function|boolean|object] [function]`,[e,t,n],arguments.length),this[Lr](),e===void 0&&(e=I(this,Tr,`f`)),typeof t==`object`&&(F(this,Sr,t,`f`),t=n),typeof t==`function`&&(F(this,K,t,`f`),t=!1),t||F(this,Tr,e,`f`),I(this,K,`f`)&&F(this,B,!1,`f`);let r=this[di](e,!!t),i=this.parsed;return I(this,R,`f`).setParsed(this.parsed),M(r)?r.then(e=>(I(this,K,`f`)&&I(this,K,`f`).call(this,I(this,pr,`f`),e,I(this,W,`f`)),e)).catch(e=>{throw I(this,K,`f`)&&I(this,K,`f`)(e,this.parsed.argv,I(this,W,`f`)),e}).finally(()=>{this[Zr](),this.parsed=i}):(I(this,K,`f`)&&I(this,K,`f`).call(this,I(this,pr,`f`),r,I(this,W,`f`)),this[Zr](),this.parsed=i,r)}parseAsync(e,t,n){let r=this.parse(e,t,n);return M(r)?r:Promise.resolve(r)}parseSync(e,t,n){let r=this.parse(e,t,n);if(M(r))throw new N(`.parseSync() must not be used with asynchronous builders, handlers, or middleware`);return r}parserConfiguration(e){return P(`<object>`,[e],arguments.length),F(this,xr,e,`f`),this}pkgConf(e,t){P(`<string> [string]`,[e,t],arguments.length);let n=null,r=this[Wr](t||I(this,ur,`f`));return r[e]&&typeof r[e]==`object`&&(n=or(r[e],t||I(this,ur,`f`),this[zr]()[`deep-merge-config`]||!1,I(this,q,`f`)),I(this,G,`f`).configObjects=(I(this,G,`f`).configObjects||[]).concat(n)),this}positional(e,t){P(`<string> <object>`,[e,t],arguments.length);let n=[`default`,`defaultDescription`,`implies`,`normalize`,`choices`,`conflicts`,`coerce`,`type`,`describe`,`desc`,`description`,`alias`];t=Un(t,(e,t)=>e===`type`&&![`string`,`number`,`boolean`].includes(t)?!1:n.includes(e));let r=I(this,dr,`f`).fullCommands[I(this,dr,`f`).fullCommands.length-1],i=r?I(this,L,`f`).cmdToParseOptions(r):{array:[],alias:{},default:{},demand:{}};return Tn(i).forEach(n=>{let r=i[n];Array.isArray(r)?r.indexOf(e)!==-1&&(t[n]=!0):r[e]&&!(n in t)&&(t[n]=r[e])}),this.group(e,I(this,J,`f`).getPositionalGroupName()),this.option(e,t)}recommendCommands(e=!0){return P(`[boolean]`,[e],arguments.length),F(this,Er,e,`f`),this}required(e,t,n){return this.demand(e,t,n)}require(e,t,n){return this.demand(e,t,n)}requiresArg(e){return P(`<array|string|object> [number]`,[e],arguments.length),typeof e==`string`&&I(this,G,`f`).narg[e]||this[Kr](this.requiresArg.bind(this),`narg`,e,NaN),this}showCompletionScript(e,t){return P(`[string] [string]`,[e,t],arguments.length),e||=this.$0,I(this,yr,`f`).log(I(this,R,`f`).generateCompletionScript(e,t||I(this,z,`f`)||`completion`)),this}showHelp(e){if(P(`[string|function]`,[e],arguments.length),F(this,H,!0,`f`),!I(this,J,`f`).hasCachedHelpMessage()){if(!this.parsed){let t=this[di](I(this,Tr,`f`),void 0,void 0,0,!0);if(M(t))return t.then(()=>{I(this,J,`f`).showHelp(e)}),this}let t=I(this,L,`f`).runDefaultBuilderOn(this);if(M(t))return t.then(()=>{I(this,J,`f`).showHelp(e)}),this}return I(this,J,`f`).showHelp(e),this}scriptName(e){return this.customScriptName=!0,this.$0=e,this}showHelpOnFail(e,t){return P(`[boolean|string] [string]`,[e,t],arguments.length),I(this,J,`f`).showHelpOnFail(e,t),this}showVersion(e){return P(`[string|function]`,[e],arguments.length),I(this,J,`f`).showVersion(e),this}skipValidation(e){return P(`<array|string>`,[e],arguments.length),this[Gr](`skipValidation`,e),this}strict(e){return P(`[boolean]`,[e],arguments.length),F(this,Dr,e!==!1,`f`),this}strictCommands(e){return P(`[boolean]`,[e],arguments.length),F(this,Or,e!==!1,`f`),this}strictOptions(e){return P(`[boolean]`,[e],arguments.length),F(this,kr,e!==!1,`f`),this}string(e){return P(`<array|string>`,[e],arguments.length),this[Gr](`string`,e),this[mi](e),this}terminalWidth(){return P([],0),I(this,q,`f`).process.stdColumns}updateLocale(e){return this.updateStrings(e)}updateStrings(e){return P(`<object>`,[e],arguments.length),F(this,mr,!1,`f`),I(this,q,`f`).y18n.updateLocale(e),this}usage(e,t,n,r){if(P(`<string|null|undefined> [string|boolean] [function|object] [function]`,[e,t,n,r],arguments.length),t!==void 0){if(j(e,null,I(this,q,`f`)),(e||``).match(/^\$0( |$)/))return this.command(e,t,n,r);throw new N(`.usage() description must start with $0 if being used as alias for .command()`)}else return I(this,J,`f`).usage(e),this}usageConfiguration(e){return P(`<object>`,[e],arguments.length),F(this,Ar,e,`f`),this}version(e,t,n){let r=`version`;if(P(`[boolean|string] [string] [string]`,[e,t,n],arguments.length),I(this,jr,`f`)&&(this[Fr](I(this,jr,`f`)),I(this,J,`f`).version(void 0),F(this,jr,null,`f`)),arguments.length===0)n=this[Hr](),e=r;else if(arguments.length===1){if(e===!1)return this;n=e,e=r}else arguments.length===2&&(n=t,t=void 0);return F(this,jr,typeof e==`string`?e:r,`f`),t||=I(this,J,`f`).deferY18nLookup(`Show version number`),I(this,J,`f`).version(n||void 0),this.boolean(I(this,jr,`f`)),this.describe(I(this,jr,`f`),t),this}wrap(e){return P(`<number|null|undefined>`,[e],arguments.length),I(this,J,`f`).wrap(e),this}[(L=new WeakMap,ur=new WeakMap,dr=new WeakMap,R=new WeakMap,z=new WeakMap,fr=new WeakMap,pr=new WeakMap,mr=new WeakMap,hr=new WeakMap,B=new WeakMap,gr=new WeakMap,V=new WeakMap,_r=new WeakMap,H=new WeakMap,U=new WeakMap,vr=new WeakMap,yr=new WeakMap,W=new WeakMap,G=new WeakMap,br=new WeakMap,xr=new WeakMap,K=new WeakMap,Sr=new WeakMap,Cr=new WeakMap,wr=new WeakMap,Tr=new WeakMap,Er=new WeakMap,q=new WeakMap,Dr=new WeakMap,Or=new WeakMap,kr=new WeakMap,J=new WeakMap,Ar=new WeakMap,jr=new WeakMap,Y=new WeakMap,Nr)](e){if(!e._||!e[`--`])return e;e._.push.apply(e._,e[`--`]);try{delete e[`--`]}catch{}return e}[Pr](){return{log:(...e)=>{this[oi]()||console.log(...e),F(this,H,!0,`f`),I(this,W,`f`).length&&F(this,W,I(this,W,`f`)+`
|
|
91
91
|
`,`f`),F(this,W,I(this,W,`f`)+e.join(` `),`f`)},error:(...e)=>{this[oi]()||console.error(...e),F(this,H,!0,`f`),I(this,W,`f`).length&&F(this,W,I(this,W,`f`)+`
|
|
92
92
|
`,`f`),F(this,W,I(this,W,`f`)+e.join(` `),`f`)}}}[Fr](e){Tn(I(this,G,`f`)).forEach(t=>{if((e=>e===`configObjects`)(t))return;let n=I(this,G,`f`)[t];Array.isArray(n)?n.includes(e)&&n.splice(n.indexOf(e),1):typeof n==`object`&&delete n[e]}),delete I(this,J,`f`).getDescriptions()[e]}[Ir](e,t,n){I(this,hr,`f`)[n]||(I(this,q,`f`).process.emitWarning(e,t),I(this,hr,`f`)[n]=!0)}[Lr](){I(this,gr,`f`).push({options:I(this,G,`f`),configObjects:I(this,G,`f`).configObjects.slice(0),exitProcess:I(this,B,`f`),groups:I(this,_r,`f`),strict:I(this,Dr,`f`),strictCommands:I(this,Or,`f`),strictOptions:I(this,kr,`f`),completionCommand:I(this,z,`f`),output:I(this,W,`f`),exitError:I(this,pr,`f`),hasOutput:I(this,H,`f`),parsed:this.parsed,parseFn:I(this,K,`f`),parseContext:I(this,Sr,`f`)}),I(this,J,`f`).freeze(),I(this,Y,`f`).freeze(),I(this,L,`f`).freeze(),I(this,V,`f`).freeze()}[Rr](){let e=``,t;return t=/\b(node|iojs|electron)(\.exe)?$/.test(I(this,q,`f`).process.argv()[0])?I(this,q,`f`).process.argv().slice(1,2):I(this,q,`f`).process.argv().slice(0,1),e=t.map(e=>{let t=this[li](I(this,ur,`f`),e);return e.match(/^(\/|([a-zA-Z]:)?\\)/)&&t.length<e.length?t:e}).join(` `).trim(),I(this,q,`f`).getEnv(`_`)&&I(this,q,`f`).getProcessArgvBin()===I(this,q,`f`).getEnv(`_`)&&(e=I(this,q,`f`).getEnv(`_`).replace(`${I(this,q,`f`).path.dirname(I(this,q,`f`).process.execPath())}/`,``)),e}[zr](){return I(this,xr,`f`)}[Br](){return I(this,Ar,`f`)}[Vr](){if(!I(this,mr,`f`))return;let e=I(this,q,`f`).getEnv(`LC_ALL`)||I(this,q,`f`).getEnv(`LC_MESSAGES`)||I(this,q,`f`).getEnv(`LANG`)||I(this,q,`f`).getEnv(`LANGUAGE`)||`en_US`;this.locale(e.replace(/[.:].*/,``))}[Hr](){return this[Wr]().version||`unknown`}[Ur](e){let t=e[`--`]?e[`--`]:e._;for(let e=0,n;(n=t[e])!==void 0;e++)I(this,q,`f`).Parser.looksLikeNumber(n)&&Number.isSafeInteger(Math.floor(parseFloat(`${n}`)))&&(t[e]=Number(n));return e}[Wr](e){let t=e||`*`;if(I(this,Cr,`f`)[t])return I(this,Cr,`f`)[t];let n={};try{let t=e||I(this,q,`f`).mainFilename;I(this,q,`f`).path.extname(t)&&(t=I(this,q,`f`).path.dirname(t));let r=I(this,q,`f`).findUp(t,(e,t)=>{if(t.includes(`package.json`))return`package.json`});j(r,void 0,I(this,q,`f`)),n=JSON.parse(I(this,q,`f`).readFileSync(r,`utf8`))}catch{}return I(this,Cr,`f`)[t]=n||{},I(this,Cr,`f`)[t]}[Gr](e,t){t=[].concat(t),t.forEach(t=>{t=this[Yr](t),I(this,G,`f`)[e].push(t)})}[Kr](e,t,n,r){this[Jr](e,t,n,r,(e,t,n)=>{I(this,G,`f`)[e][t]=n})}[qr](e,t,n,r){this[Jr](e,t,n,r,(e,t,n)=>{I(this,G,`f`)[e][t]=(I(this,G,`f`)[e][t]||[]).concat(n)})}[Jr](e,t,n,r,i){if(Array.isArray(n))n.forEach(t=>{e(t,r)});else if((e=>typeof e==`object`)(n))for(let t of Tn(n))e(t,n[t]);else i(t,this[Yr](n),r)}[Yr](e){return e===`__proto__`?`___proto___`:e}[Xr](e,t){return this[Kr](this[Xr].bind(this),`key`,e,t),this}[Zr](){var e,t,n,r,i,a,o,s,c,l,u,d;let f=I(this,gr,`f`).pop();j(f,void 0,I(this,q,`f`));let p;e=this,t=this,n=this,r=this,i=this,a=this,o=this,s=this,c=this,l=this,u=this,d=this,{options:{set value(t){F(e,G,t,`f`)}}.value,configObjects:p,exitProcess:{set value(e){F(t,B,e,`f`)}}.value,groups:{set value(e){F(n,_r,e,`f`)}}.value,output:{set value(e){F(r,W,e,`f`)}}.value,exitError:{set value(e){F(i,pr,e,`f`)}}.value,hasOutput:{set value(e){F(a,H,e,`f`)}}.value,parsed:this.parsed,strict:{set value(e){F(o,Dr,e,`f`)}}.value,strictCommands:{set value(e){F(s,Or,e,`f`)}}.value,strictOptions:{set value(e){F(c,kr,e,`f`)}}.value,completionCommand:{set value(e){F(l,z,e,`f`)}}.value,parseFn:{set value(e){F(u,K,e,`f`)}}.value,parseContext:{set value(e){F(d,Sr,e,`f`)}}.value}=f,I(this,G,`f`).configObjects=p,I(this,J,`f`).unfreeze(),I(this,Y,`f`).unfreeze(),I(this,L,`f`).unfreeze(),I(this,V,`f`).unfreeze()}[Qr](e,t){return Nn(t,t=>(e(t),t))}getInternalMethods(){return{getCommandInstance:this[$r].bind(this),getContext:this[ei].bind(this),getHasOutput:this[ti].bind(this),getLoggerInstance:this[ni].bind(this),getParseContext:this[ri].bind(this),getParserConfiguration:this[zr].bind(this),getUsageConfiguration:this[Br].bind(this),getUsageInstance:this[ii].bind(this),getValidationInstance:this[ai].bind(this),hasParseCallback:this[oi].bind(this),isGlobalContext:this[si].bind(this),postProcess:this[ci].bind(this),reset:this[ui].bind(this),runValidation:this[fi].bind(this),runYargsParserAndExecuteCommands:this[di].bind(this),setHasOutput:this[pi].bind(this)}}[$r](){return I(this,L,`f`)}[ei](){return I(this,dr,`f`)}[ti](){return I(this,H,`f`)}[ni](){return I(this,yr,`f`)}[ri](){return I(this,Sr,`f`)||{}}[ii](){return I(this,J,`f`)}[ai](){return I(this,Y,`f`)}[oi](){return!!I(this,K,`f`)}[si](){return I(this,vr,`f`)}[ci](e,t,n,r){return n||M(e)?e:(t||(e=this[Nr](e)),(this[zr]()[`parse-positional-numbers`]||this[zr]()[`parse-positional-numbers`]===void 0)&&(e=this[Ur](e)),r&&(e=Mn(e,this,I(this,V,`f`).getMiddleware(),!1)),e)}[ui](e={}){F(this,G,I(this,G,`f`)||{},`f`);let t={};t.local=I(this,G,`f`).local||[],t.configObjects=I(this,G,`f`).configObjects||[];let n={};return t.local.forEach(t=>{n[t]=!0,(e[t]||[]).forEach(e=>{n[e]=!0})}),Object.assign(I(this,wr,`f`),Object.keys(I(this,_r,`f`)).reduce((e,t)=>{let r=I(this,_r,`f`)[t].filter(e=>!(e in n));return r.length>0&&(e[t]=r),e},{})),F(this,_r,{},`f`),[`array`,`boolean`,`string`,`skipValidation`,`count`,`normalize`,`number`,`hiddenOptions`].forEach(e=>{t[e]=(I(this,G,`f`)[e]||[]).filter(e=>!n[e])}),[`narg`,`key`,`alias`,`default`,`defaultDescription`,`config`,`choices`,`demandedOptions`,`demandedCommands`,`deprecatedOptions`].forEach(e=>{t[e]=Un(I(this,G,`f`)[e],e=>!n[e])}),t.envPrefix=I(this,G,`f`).envPrefix,F(this,G,t,`f`),F(this,J,I(this,J,`f`)?I(this,J,`f`).reset(n):Kn(this,I(this,q,`f`)),`f`),F(this,Y,I(this,Y,`f`)?I(this,Y,`f`).reset(n):rr(this,I(this,J,`f`),I(this,q,`f`)),`f`),F(this,L,I(this,L,`f`)?I(this,L,`f`).reset():Ln(I(this,J,`f`),I(this,Y,`f`),I(this,V,`f`),I(this,q,`f`)),`f`),I(this,R,`f`)||F(this,R,Qn(this,I(this,J,`f`),I(this,L,`f`),I(this,q,`f`)),`f`),I(this,V,`f`).reset(),F(this,z,null,`f`),F(this,W,``,`f`),F(this,pr,null,`f`),F(this,H,!1,`f`),this.parsed=!1,this}[li](e,t){return I(this,q,`f`).path.relative(e,t)}[di](e,t,n,r=0,i=!1){let a=!!n||i;e||=I(this,Tr,`f`),I(this,G,`f`).__=I(this,q,`f`).y18n.__,I(this,G,`f`).configuration=this[zr]();let o=!!I(this,G,`f`).configuration[`populate--`],s=Object.assign({},I(this,G,`f`).configuration,{"populate--":!0}),c=I(this,q,`f`).Parser.detailed(e,Object.assign({},I(this,G,`f`),{configuration:{"parse-positional-numbers":!1,...s}})),l=Object.assign(c.argv,I(this,Sr,`f`)),u,d=c.aliases,f=!1,p=!1;Object.keys(l).forEach(e=>{e===I(this,U,`f`)&&l[e]?f=!0:e===I(this,jr,`f`)&&l[e]&&(p=!0)}),l.$0=this.$0,this.parsed=c,r===0&&I(this,J,`f`).clearCachedHelpMessage();try{if(this[Vr](),t)return this[ci](l,o,!!n,!1);I(this,U,`f`)&&[I(this,U,`f`)].concat(d[I(this,U,`f`)]||[]).filter(e=>e.length>1).includes(``+l._[l._.length-1])&&(l._.pop(),f=!0),F(this,vr,!1,`f`);let s=I(this,L,`f`).getCommands(),m=I(this,R,`f`)?.completionKey?[I(this,R,`f`)?.completionKey,...this.getAliases()[I(this,R,`f`)?.completionKey]??[]].some(e=>Object.prototype.hasOwnProperty.call(l,e)):!1,h=f||m||i;if(l._.length){if(s.length){let e;for(let t=r||0,a;l._[t]!==void 0;t++)if(a=String(l._[t]),s.includes(a)&&a!==I(this,z,`f`)){let e=I(this,L,`f`).runCommand(a,this,c,t+1,i,f||p||i);return this[ci](e,o,!!n,!1)}else if(!e&&a!==I(this,z,`f`)){e=a;break}!I(this,L,`f`).hasDefaultCommand()&&I(this,Er,`f`)&&e&&!h&&I(this,Y,`f`).recommendCommands(e,s)}I(this,z,`f`)&&l._.includes(I(this,z,`f`))&&!m&&(I(this,B,`f`)&&Wn(!0),this.showCompletionScript(),this.exit(0))}if(I(this,L,`f`).hasDefaultCommand()&&!h){let e=I(this,L,`f`).runCommand(null,this,c,0,i,f||p||i);return this[ci](e,o,!!n,!1)}if(m){I(this,B,`f`)&&Wn(!0),e=[].concat(e);let t=e.slice(e.indexOf(`--${I(this,R,`f`).completionKey}`)+1);return I(this,R,`f`).getCompletion(t,(e,t)=>{if(e)throw new N(e.message);(t||[]).forEach(e=>{I(this,yr,`f`).log(e)}),this.exit(0)}),this[ci](l,!o,!!n,!1)}if(I(this,H,`f`)||(f?(I(this,B,`f`)&&Wn(!0),a=!0,this.showHelp(e=>{I(this,yr,`f`).log(e),this.exit(0)})):p&&(I(this,B,`f`)&&Wn(!0),a=!0,I(this,J,`f`).showVersion(`log`),this.exit(0))),!a&&I(this,G,`f`).skipValidation.length>0&&(a=Object.keys(l).some(e=>I(this,G,`f`).skipValidation.indexOf(e)>=0&&l[e]===!0)),!a){if(c.error)throw new N(c.error.message);if(!m){let e=this[fi](d,{},c.error);n||(u=Mn(l,this,I(this,V,`f`).getMiddleware(),!0)),u=this[Qr](e,u??l),M(u)&&!n&&(u=u.then(()=>Mn(l,this,I(this,V,`f`).getMiddleware(),!1)))}}}catch(e){if(e instanceof N)I(this,J,`f`).fail(e.message,e);else throw e}return this[ci](u??l,o,!!n,!0)}[fi](e,t,n,r){let i={...this.getDemandedOptions()};return a=>{if(n)throw new N(n.message);I(this,Y,`f`).nonOptionCount(a),I(this,Y,`f`).requiredArguments(a,i);let o=!1;I(this,Or,`f`)&&(o=I(this,Y,`f`).unknownCommands(a)),I(this,Dr,`f`)&&!o?I(this,Y,`f`).unknownArguments(a,e,t,!!r):I(this,kr,`f`)&&I(this,Y,`f`).unknownArguments(a,e,{},!1,!1),I(this,Y,`f`).limitedChoices(a),I(this,Y,`f`).implications(a),I(this,Y,`f`).conflicting(a)}}[pi](){F(this,H,!0,`f`)}[mi](e){if(typeof e==`string`)I(this,G,`f`).key[e]=!0;else for(let t of e)I(this,G,`f`).key[t]=!0}};function gi(e){return!!e&&typeof e.getInternalMethods==`function`}var _i=Mr(Cn),vi=class extends Ce{buffer=``;constructor(){super({objectMode:!1})}_flush(e){this.buffer.trim().startsWith(`{`)?e(null,Buffer.from(this.buffer)):e(null,null)}_transform(e,t,n){this.buffer+=e.toString();let r=this.buffer.split(`
|
|
93
|
-
`);this.buffer=r.pop()||``;let i=r.filter(e=>e.trim().startsWith(`{`));if(i.length>0){let e
|
|
94
|
-
`)
|
|
95
|
-
`;n(null,Buffer.from(e))}else n(null,null)}},yi=class{onclose;onerror;onmessage;get pid(){return this._process?.pid??null}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}_abortController=new AbortController;_process;_readBuffer=new i;_serverParams;_stderrStream=null;onEvent;constructor(e){this._serverParams=e,(e.stderr===`pipe`||e.stderr===`overlapped`)&&(this._stderrStream=new Se),this.onEvent=e.onEvent}async close(){this.onEvent?.({type:`close`}),this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(e){return new Promise(t=>{if(!this._process?.stdin)throw Error(`Not connected`);let n=te(e);this._process.stdin.write(n)?t():this._process.stdin.once(`drain`,t)})}async start(){if(this._process)throw Error(`StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.`);return new Promise((e,t)=>{this._process=xe(this._serverParams.command,this._serverParams.args??[],{cwd:this._serverParams.cwd,env:this._serverParams.env,shell:this._serverParams.shell??!1,signal:this._abortController.signal,stdio:[`pipe`,`pipe`,this._serverParams.stderr??`inherit`]}),this._process.on(`error`,e=>{if(e.name===`AbortError`){this.onclose?.();return}let r=new n(`Process spawn error: ${e.message}`,this._serverParams.command,this._serverParams.args,{cwd:this._serverParams.cwd,errorCode:e.code,errorErrno:e.errno,errorSyscall:e.syscall,shell:this._serverParams.shell});m(r),t(e),this.onerror?.(e)}),this._process.on(`spawn`,()=>{f(`Process spawned successfully`,`transport`,`info`,{argCount:this._serverParams.args?.length,command:this._serverParams.command,pid:this._process?.pid}),e()}),this._process.on(`close`,e=>{this.onEvent?.({type:`close`}),this._process=void 0,this.onclose?.()}),this._process.stdin?.on(`error`,e=>{let t=new l(`Stdin error: ${e.message}`,`stdio`,`write`,{command:this._serverParams.command,pid:this._process?.pid});m(t),this.onEvent?.({error:e,type:`error`}),this.onerror?.(e)});let r=new vi;this._process.stdout?.pipe(r),r.on(`data`,e=>{this.onEvent?.({chunk:e.toString(),type:`data`}),this._readBuffer.append(e),this.processReadBuffer()}),r.on(`error`,e=>{let t=new l(`JSON filter error: ${e.message}`,`stdio`,`parse`,{command:this._serverParams.command,pid:this._process?.pid});m(t),this.onEvent?.({error:e,type:`error`}),this.onerror?.(e)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onEvent?.({message:e,type:`message`}),this.onmessage?.(e)}catch(e){let t=null;try{t=this._readBuffer.readMessage()}catch{}let n=new l(`Message processing error: ${e.message}`,`stdio`,`process`,{command:this._serverParams.command,messageType:t?typeof t:`unknown`,pid:this._process?.pid});m(n),this.onEvent?.({error:e,type:`error`}),this.onerror?.(e)}}};he.inspect.defaultOptions.depth=8,`EventSource`in global||(global.EventSource=Qe);const X=await _i(on(process.argv)).scriptName(`mcp-gateway`).command(`stdio [command] [args...]`,`Run a local command with stdio transport (default)`,e=>e.positional(`command`,{describe:`The command to run`,type:`string`}).positional(`args`,{array:!0,describe:`The arguments to pass to the command`,type:`string`})).command(`remote`,`Connect to a remote MCP server`,e=>e.options({headers:{describe:`Headers for remote authentication (format: key:value)`,string:!0,type:`array`},"remote-transport":{choices:[`sse`,`stream`],default:`sse`,describe:`The transport type for remote connection (sse or stream)`,type:`string`},url:{demandOption:!0,describe:`The URL of the remote MCP server`,type:`string`}})).command(`$0 [command] [args...]`,`Run a command with MCP arguments (backward compatible)`,e=>e.positional(`command`,{describe:`The command to run`,type:`string`}).positional(`args`,{array:!0,describe:`The arguments to pass to the command`,type:`string`})).env(`MCP_GATEWAY`).parserConfiguration({"populate--":!0}).options({debug:{default:!1,describe:`Enable debug logging`,type:`boolean`},env:{describe:`Environment variables to pass to the command (format: KEY=value)`,string:!0,type:`array`},gracefulShutdownTimeout:{default:5e3,describe:`The timeout (in milliseconds) for graceful shutdown`,type:`number`},port:{describe:`Run as HTTP server on the specified port instead of stdio`,type:`number`},shell:{default:!1,describe:`Spawn the server via the user's shell`,type:`boolean`}}).help().parseAsync();let Z,Q,bi,$,xi;const Si={};if(X.headers)for(let e of X.headers){let[t,...n]=e.split(`:`);t&&n.length>0&&(Si[t.trim()]=n.join(`:`).trim())}const Ci={...h.mirror.headers};h.mirror.apiKey&&(Ci.apikey=h.mirror.apiKey),v.debug(`Initializing traffic mirror`,{hasApiKey:!!h.mirror.apiKey,mirrorEnabled:h.mirror.enabled,mirrorUrl:h.mirror.url});const wi={...h.scanner.headers};if(v.debug(`Initializing traffic scanner`,{failOpen:h.scanner.failOpen,hasApiKey:!!h.scanner.apiKey,scannerEnabled:h.scanner.enabled,scannerUrl:h.scanner.url,timeoutMs:h.scanner.timeoutMs}),X._[0]===`remote`){if(Z=`remote`,$=X.url,xi=X[`remote-transport`]||`sse`,!$)throw new t(`Remote URL is required for remote proxy type`,`url`,{transport:xi})}else{if(Z=`stdio`,X[`--`]&&X[`--`].length>0){let e=X[`--`];Q=e[0],bi=e.slice(1)}else Q=X.command,bi=X.args||[];if(!Q)throw new t(`No command specified for stdio proxy`,`command`)}const Ti={};if(X.env)for(let e of X.env){let[t,...n]=e.split(`=`);t&&n.length>0&&(Ti[t.trim()]=n.join(`=`).trim())}const Ei=async e=>{if(Z===`stdio`){let t={...process.env,...Ti},n=new yi({args:bi,command:Q,env:t,onEvent:e=>{X.debug&&v.debug(`Transport event`,{event:e})},shell:X.shell,stderr:`inherit`});try{await e.connect(n)}catch(e){throw new r(`Failed to connect to stdio process: ${e}`,void 0,`stdio`,{argCount:bi?.length,command:Q})}}else if(Z===`remote`){let t,n=Object.keys(Si).length>0?{headers:Si}:void 0;try{t=xi===`sse`?new a(new URL($),{requestInit:n}):new c(new URL($),{requestInit:n}),await e.connect(t)}catch(e){throw new r(`Failed to connect to remote server: ${e}`,$,xi,{headerCount:Object.keys(Si).length})}}},Di=async()=>{if(X.port){await _({cliArgs:Z===`stdio`?{args:bi,command:Q,proxyType:Z}:{proxyType:Z,url:$},enabled:h.mirror.enabled,headers:Ci,scanApiKey:h.scanner.apiKey,scanEnabled:h.scanner.enabled,scanFailOpen:h.scanner.failOpen,scanHeaders:wi,scanTimeoutMs:h.scanner.timeoutMs,scanUrl:h.scanner.url||``,url:h.mirror.url||``});let t,n=await ne({createServer:async()=>{t=new e({name:`mcp-gateway`,version:h.appVersion},{capabilities:{}}),await Ei(t);let n=t.getServerVersion(),r=t.getServerCapabilities(),i=new o(n,{capabilities:r});return y({client:t,server:i,serverCapabilities:r}),i},onClose:async e=>{t&&await t.close(),await e.close()},port:X.port});return v.info(`MCP gateway started as HTTP server`,{port:X.port,proxyType:Z}),Z===`stdio`?v.info(`Running command`,{args:bi?.join(` `)||``,command:Q}):v.info(`Connected to remote server`,{remoteTransport:xi,remoteUrl:$}),{close:()=>n.close()}}let t=new e({name:`mcp-gateway`,version:h.appVersion},{capabilities:{}});await Ei(t);let n=t.getServerVersion(),r=t.getServerCapabilities(),i=new o(n,{capabilities:r});y({client:t,server:i,serverCapabilities:r});let a=new s;return await _({cliArgs:Z===`stdio`?{args:bi,command:Q,proxyType:Z}:{proxyType:Z,url:$},enabled:h.mirror.enabled,headers:Ci,scanApiKey:h.scanner.apiKey,scanEnabled:h.scanner.enabled,scanFailOpen:h.scanner.failOpen,scanHeaders:wi,scanTimeoutMs:h.scanner.timeoutMs,scanUrl:h.scanner.url||``,url:h.mirror.url||``}),await i.connect(a),v.info(`MCP gateway started`,{proxyType:Z}),Z===`stdio`?v.info(`Running command`,{args:bi?.join(` `)||``,command:Q}):v.info(`Connected to remote server`,{remoteTransport:xi,remoteUrl:$}),{close:()=>t.close()}},Oi=({server:e,timeout:t})=>{let n=async()=>{v.info(`Received shutdown signal; shutting down`);try{await e.close(),process.exit(0)}catch(e){let n=`Error during shutdown: ${e}`;v.error(`Error during shutdown`,{error:n}),m(e instanceof Error?e:Error(n),{shutdownTimeout:t},{feature:`shutdown`,module:`cli`,operation:`close`}),process.exit(1)}},r=async()=>{me(()=>{v.error(`Graceful shutdown timeout exceeded, forcing exit`),process.exit(1)},t).unref(),await n()};return process.once(`SIGTERM`,r),process.once(`SIGINT`,r),()=>e.close()};await(async()=>{ee(),p({"proxy.mode":Z===`stdio`?`local`:`remote`,"proxy.transport":Z===`remote`?xi||`unknown`:`stdio`,"proxy.type":Z}),f(`MCP Gateway starting`,`lifecycle`,`info`,{command:Q,proxyType:Z,transport:xi,url:$});try{let e=await Di();Oi({server:e,timeout:X.gracefulShutdownTimeout})}catch(e){let t=`Could not start the proxy: ${e}`;v.error(`Unhandled error occurred`,{error:t}),e instanceof Error?m(e,{args:bi,command:Q,proxyType:Z,transport:xi,url:$},{feature:`startup`,module:`cli`,operation:`initialize`,proxyType:Z,transport:Z===`remote`?xi||`unknown`:`stdio`}):m(Error(t),{command:Q,originalError:String(e),proxyType:Z},{feature:`startup`,module:`cli`,operation:`initialize`}),me(()=>{process.exit(1)},1e3)}})();export{};
|
|
93
|
+
`);this.buffer=r.pop()||``;let i=r.filter(e=>e.trim().startsWith(`{`));if(i.length>0){let e=`${i.join(`
|
|
94
|
+
`)}\n`;n(null,Buffer.from(e))}else n(null,null)}},yi=class{onclose;onerror;onmessage;get pid(){return this._process?.pid??null}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}_abortController=new AbortController;_process;_readBuffer=new i;_serverParams;_stderrStream=null;onEvent;constructor(e){this._serverParams=e,(e.stderr===`pipe`||e.stderr===`overlapped`)&&(this._stderrStream=new Se),this.onEvent=e.onEvent}async close(){this.onEvent?.({type:`close`}),this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(e){return new Promise(t=>{if(!this._process?.stdin)throw Error(`Not connected`);let n=te(e);this._process.stdin.write(n)?t():this._process.stdin.once(`drain`,t)})}async start(){if(this._process)throw Error(`StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.`);return new Promise((e,t)=>{this._process=xe(this._serverParams.command,this._serverParams.args??[],{cwd:this._serverParams.cwd,env:this._serverParams.env,shell:this._serverParams.shell??!1,signal:this._abortController.signal,stdio:[`pipe`,`pipe`,this._serverParams.stderr??`inherit`]}),this._process.on(`error`,e=>{if(e.name===`AbortError`){this.onclose?.();return}let r=new n(`Process spawn error: ${e.message}`,this._serverParams.command,this._serverParams.args,{cwd:this._serverParams.cwd,errorCode:e.code,errorErrno:e.errno,errorSyscall:e.syscall,shell:this._serverParams.shell});m(r),t(e),this.onerror?.(e)}),this._process.on(`spawn`,()=>{f(`Process spawned successfully`,`transport`,`info`,{argCount:this._serverParams.args?.length,command:this._serverParams.command,pid:this._process?.pid}),e()}),this._process.on(`close`,e=>{this.onEvent?.({type:`close`}),this._process=void 0,this.onclose?.()}),this._process.stdin?.on(`error`,e=>{let t=new l(`Stdin error: ${e.message}`,`stdio`,`write`,{command:this._serverParams.command,pid:this._process?.pid});m(t),this.onEvent?.({error:e,type:`error`}),this.onerror?.(e)});let r=new vi;this._process.stdout?.pipe(r),r.on(`data`,e=>{this.onEvent?.({chunk:e.toString(),type:`data`}),this._readBuffer.append(e),this.processReadBuffer()}),r.on(`error`,e=>{let t=new l(`JSON filter error: ${e.message}`,`stdio`,`parse`,{command:this._serverParams.command,pid:this._process?.pid});m(t),this.onEvent?.({error:e,type:`error`}),this.onerror?.(e)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onEvent?.({message:e,type:`message`}),this.onmessage?.(e)}catch(e){let t=null;try{t=this._readBuffer.readMessage()}catch{}let n=new l(`Message processing error: ${e.message}`,`stdio`,`process`,{command:this._serverParams.command,messageType:t?typeof t:`unknown`,pid:this._process?.pid});m(n),this.onEvent?.({error:e,type:`error`}),this.onerror?.(e)}}};he.inspect.defaultOptions.depth=8,`EventSource`in global||(global.EventSource=Qe);const X=await _i(on(process.argv)).scriptName(`mcp-gateway`).command(`stdio [command] [args...]`,`Run a local command with stdio transport (default)`,e=>e.positional(`command`,{describe:`The command to run`,type:`string`}).positional(`args`,{array:!0,describe:`The arguments to pass to the command`,type:`string`})).command(`remote`,`Connect to a remote MCP server`,e=>e.options({headers:{describe:`Headers for remote authentication (format: key:value)`,string:!0,type:`array`},"remote-transport":{choices:[`sse`,`stream`],default:`sse`,describe:`The transport type for remote connection (sse or stream)`,type:`string`},url:{demandOption:!0,describe:`The URL of the remote MCP server`,type:`string`}})).command(`$0 [command] [args...]`,`Run a command with MCP arguments (backward compatible)`,e=>e.positional(`command`,{describe:`The command to run`,type:`string`}).positional(`args`,{array:!0,describe:`The arguments to pass to the command`,type:`string`})).env(`MCP_GATEWAY`).parserConfiguration({"populate--":!0}).options({debug:{default:!1,describe:`Enable debug logging`,type:`boolean`},env:{describe:`Environment variables to pass to the command (format: KEY=value)`,string:!0,type:`array`},gracefulShutdownTimeout:{default:5e3,describe:`The timeout (in milliseconds) for graceful shutdown`,type:`number`},port:{describe:`Run as HTTP server on the specified port instead of stdio`,type:`number`},shell:{default:!1,describe:`Spawn the server via the user's shell`,type:`boolean`}}).help().parseAsync();let Z,Q,bi,$,xi;const Si={};if(X.headers)for(let e of X.headers){let[t,...n]=e.split(`:`);t&&n.length>0&&(Si[t.trim()]=n.join(`:`).trim())}const Ci={...h.scanner.headers};if(v.debug(`Initializing traffic scanner`,{failOpen:h.scanner.failOpen,hasApiKey:!!h.scanner.apiKey,scannerEnabled:h.scanner.enabled,scannerUrl:h.scanner.url,timeoutMs:h.scanner.timeoutMs}),X._[0]===`remote`){if(Z=`remote`,$=X.url,xi=X[`remote-transport`]||`sse`,!$)throw new t(`Remote URL is required for remote proxy type`,`url`,{transport:xi})}else{if(Z=`stdio`,X[`--`]&&X[`--`].length>0){let e=X[`--`];Q=e[0],bi=e.slice(1)}else Q=X.command,bi=X.args||[];if(!Q)throw new t(`No command specified for stdio proxy`,`command`)}const wi={};if(X.env)for(let e of X.env){let[t,...n]=e.split(`=`);t&&n.length>0&&(wi[t.trim()]=n.join(`=`).trim())}const Ti=async e=>{if(Z===`stdio`){let t={...process.env,...wi},n=new yi({args:bi,command:Q,env:t,onEvent:e=>{X.debug&&v.debug(`Transport event`,{event:e})},shell:X.shell,stderr:`inherit`});try{await e.connect(n)}catch(e){throw new r(`Failed to connect to stdio process: ${e}`,void 0,`stdio`,{argCount:bi?.length,command:Q})}}else if(Z===`remote`){let t,n=Object.keys(Si).length>0?{headers:Si}:void 0;try{t=xi===`sse`?new a(new URL($),{requestInit:n}):new c(new URL($),{requestInit:n}),await e.connect(t)}catch(e){throw new r(`Failed to connect to remote server: ${e}`,$,xi,{headerCount:Object.keys(Si).length})}}},Ei=async()=>{if(X.port){await _({cliArgs:Z===`stdio`?{args:bi,command:Q,proxyType:Z}:{proxyType:Z,url:$},scanApiKey:h.scanner.apiKey,scanEnabled:h.scanner.enabled,scanFailOpen:h.scanner.failOpen,scanHeaders:Ci,scanTimeoutMs:h.scanner.timeoutMs,scanUrl:h.scanner.url||``});let t,n=await ne({createServer:async()=>{t=new e({name:`mcp-gateway`,version:h.appVersion},{capabilities:{}}),await Ti(t);let n=t.getServerVersion(),r=t.getServerCapabilities(),i=new o(n,{capabilities:r});return y({client:t,server:i,serverCapabilities:r}),i},onClose:async e=>{t&&await t.close(),await e.close()},port:X.port});return v.info(`MCP gateway started as HTTP server`,{port:X.port,proxyType:Z}),Z===`stdio`?v.info(`Running command`,{args:bi?.join(` `)||``,command:Q}):v.info(`Connected to remote server`,{remoteTransport:xi,remoteUrl:$}),{close:()=>n.close()}}let t=new e({name:`mcp-gateway`,version:h.appVersion},{capabilities:{}});await Ti(t);let n=t.getServerVersion(),r=t.getServerCapabilities(),i=new o(n,{capabilities:r});y({client:t,server:i,serverCapabilities:r});let a=new s;return await _({cliArgs:Z===`stdio`?{args:bi,command:Q,proxyType:Z}:{proxyType:Z,url:$},scanApiKey:h.scanner.apiKey,scanEnabled:h.scanner.enabled,scanFailOpen:h.scanner.failOpen,scanHeaders:Ci,scanTimeoutMs:h.scanner.timeoutMs,scanUrl:h.scanner.url||``}),await i.connect(a),v.info(`MCP gateway started`,{proxyType:Z}),Z===`stdio`?v.info(`Running command`,{args:bi?.join(` `)||``,command:Q}):v.info(`Connected to remote server`,{remoteTransport:xi,remoteUrl:$}),{close:()=>t.close()}},Di=({server:e,timeout:t})=>{let n=async()=>{v.info(`Received shutdown signal; shutting down`);try{await e.close(),process.exit(0)}catch(e){let n=`Error during shutdown: ${e}`;v.error(`Error during shutdown`,{error:n}),m(e instanceof Error?e:Error(n),{shutdownTimeout:t},{feature:`shutdown`,module:`cli`,operation:`close`}),process.exit(1)}},r=async()=>{me(()=>{v.error(`Graceful shutdown timeout exceeded, forcing exit`),process.exit(1)},t).unref(),await n()};return process.once(`SIGTERM`,r),process.once(`SIGINT`,r),()=>e.close()};await(async()=>{ee(),p({"proxy.mode":Z===`stdio`?`local`:`remote`,"proxy.transport":Z===`remote`?xi||`unknown`:`stdio`,"proxy.type":Z}),f(`MCP Gateway starting`,`lifecycle`,`info`,{command:Q,proxyType:Z,transport:xi,url:$});try{let e=await Ei();Di({server:e,timeout:X.gracefulShutdownTimeout})}catch(e){let t=`Could not start the proxy: ${e}`;v.error(`Unhandled error occurred`,{error:t}),e instanceof Error?m(e,{args:bi,command:Q,proxyType:Z,transport:xi,url:$},{feature:`startup`,module:`cli`,operation:`initialize`,proxyType:Z,transport:Z===`remote`?xi||`unknown`:`stdio`}):m(Error(t),{command:Q,originalError:String(e),proxyType:Z},{feature:`startup`,module:`cli`,operation:`initialize`}),me(()=>{process.exit(1)},1e3)}})();export{};
|
|
96
95
|
//# sourceMappingURL=mcp-gateway.js.map
|