@genne/genne-cli 0.1.58 → 0.1.60

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.
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- var B=Object.defineProperty;var i=(t,r)=>B(t,"name",{value:r,configurable:!0});import{createServer as L}from"node:http";import{realpathSync as y}from"node:fs";import{readOwnedFile as U}from"./private-file.js";import{runWithRequestSignal as $}from"./request-scope.js";import{Readable as x}from"node:stream";import{isAbsolute as R}from"node:path";import{fileURLToPath as v}from"node:url";import Y from"../package.json"with{type:"json"};import{openRemoteAuthStore as F}from"./remote-auth-store.js";import{createRemoteAuth as H}from"./remote-auth.js";import{createRemoteCore as k}from"./remote-core.js";import{createRemoteOAuthHandler as W}from"./remote-http.js";import{createRemoteProductMcpHandler as z}from"./mcp.js";const K="genne-mcp-remote",V=Y.version,X=1024*1024,j=16*1024*1024,J=new Set(["localhost","127.0.0.1","[::1]"]),Q=new Set(["/health","/mcp","/oauth/authorize","/oauth/handoff","/oauth/token","/oauth/grants","/.well-known/oauth-protected-resource","/.well-known/oauth-authorization-server"]);class c extends Error{static{i(this,"RemoteConfigError")}constructor(r){super(r),this.name="RemoteConfigError"}}class I extends Error{static{i(this,"RequestTooLargeError")}constructor(){super("request_too_large"),this.name="RequestTooLargeError"}}class d extends Error{static{i(this,"InvalidRequestTargetError")}constructor(){super("invalid_request_target"),this.name="InvalidRequestTargetError"}}const C=i(t=>typeof t=="string"&&t.trim()!=="","hasValue");function p(t,r){if(C(t[r]))return t[r].trim()}i(p,"valueFrom");function E(t,r){const e=p(t,r);if(!e)throw new c(`Missing required configuration: ${r}`);return e}i(E,"requiredValue");function O(t,r,{https:e=!0,root:n=!1,expectedPath:a}={}){let o;try{o=new URL(t)}catch{throw new c(`Invalid ${r}`)}if(e&&o.protocol!=="https:"||!e&&!["https:","http:"].includes(o.protocol)||o.username||o.password||o.search||o.hash||n&&o.pathname!=="/"||a!==void 0&&o.pathname!==a)throw new c(`Invalid ${r}`);return o.href}i(O,"url");function g(t,r,{https:e=!0,allowLocalHttp:n=!1}={}){const a=O(t,r,{https:e&&!n}),o=new URL(a);if(o.pathname!=="/"||o.port&&!/^\d+$/.test(o.port))throw new c(`Invalid ${r}`);if(n&&o.protocol==="http:"&&!J.has(o.hostname))throw new c(`Invalid ${r}`);return o.origin}i(g,"origin");function Z(t){let r;try{r=t.startsWith("[")?JSON.parse(t):t.split(/[\n,]/u).map(n=>n.trim()).filter(Boolean)}catch{throw new c("Invalid GENNE_MCP_REDIRECT_URIS")}if(!Array.isArray(r)||r.length===0||r.some(n=>typeof n!="string"||!n.trim()))throw new c("Invalid GENNE_MCP_REDIRECT_URIS");const e=r.map(n=>O(n.trim(),"GENNE_MCP_REDIRECT_URIS",{https:!0}));if(new Set(e).size!==e.length)throw new c("Duplicate GENNE_MCP_REDIRECT_URIS");return e}i(Z,"redirectUris");function q(t,r){if(!C(t))return[];const e=t.split(/[\n,]/u).map(n=>n.trim()).filter(Boolean);if(e.length===0)throw new c(`Invalid ${r}`);return e.map(n=>g(n,r))}i(q,"origins");function P(t,r,{min:e,max:n}){if(!/^(?:0|[1-9]\d*)$/u.test(t))throw new c(`Invalid ${r}`);const a=Number(t);if(!Number.isSafeInteger(a)||a<e||a>n)throw new c(`Invalid ${r}`);return a}i(P,"integer");function tt(t,r){if(t.length===32)return t;const e=t.toString("utf8").trim();if(/^[0-9a-f]{64}$/iu.test(e))return Buffer.from(e,"hex");try{const n=Buffer.from(e,"base64url");if(n.length===32&&n.toString("base64url")===e.replace(/=+$/u,""))return n}catch{}throw new c(`Invalid ${r}`)}i(tt,"keyFromBytes");async function rt(t,r){try{return await U(t)}catch(e){throw e?.code==="ENOENT"?new c(`Cannot read ${r}`):new c(`Insecure ${r}`)}}i(rt,"secureFile");async function M(t,r,{key:e=!1}={}){const n=E(t,r),a=await rt(n,r),o=Buffer.isBuffer(a)?a:Buffer.from(a,"utf8");if(e)return tt(o,r);const s=o.toString("utf8").trim();if(s.length<32||/[\u0000-\u001f\u007f]/u.test(s))throw new c(`Invalid ${r}`);return s}i(M,"secret");function et(t=process.env){const r=O(E(t,"GENNE_MCP_RESOURCE"),"GENNE_MCP_RESOURCE",{expectedPath:"/mcp"}),e=g(E(t,"GENNE_MCP_ISSUER"),"GENNE_MCP_ISSUER"),n=g(E(t,"GENNE_MCP_CORE_ORIGIN"),"GENNE_MCP_CORE_ORIGIN",{allowLocalHttp:!0}),a=g(E(t,"GENNE_MCP_ADMIN_ORIGIN"),"GENNE_MCP_ADMIN_ORIGIN"),o=E(t,"GENNE_MCP_CLIENT_ID");if(!/^[A-Za-z0-9._~-]{1,128}$/u.test(o))throw new c("Invalid GENNE_MCP_CLIENT_ID");const s=Z(E(t,"GENNE_MCP_REDIRECT_URIS")),u=E(t,"GENNE_MCP_ADAPTER_KEY_FILE"),f=E(t,"GENNE_MCP_STORE_KEY_FILE");if(!R(u)||!R(f))throw new c("Secret file paths must be absolute");const l=E(t,"GENNE_MCP_STORE_PATH");if(!R(l))throw new c("GENNE_MCP_STORE_PATH must be absolute");const h=P(E(t,"GENNE_MCP_PORT"),"GENNE_MCP_PORT",{min:0,max:65535}),m=E(t,"GENNE_MCP_BIND");if(!/^(?:[A-Za-z0-9.-]+|\[[0-9A-Fa-f:]+\])$/u.test(m))throw new c("Invalid GENNE_MCP_BIND");const T=p(t,"GENNE_MCP_MAX_BODY_BYTES")?P(p(t,"GENNE_MCP_MAX_BODY_BYTES"),"GENNE_MCP_MAX_BODY_BYTES",{min:1,max:j}):X,S=q(p(t,"GENNE_MCP_ALLOWED_ORIGINS"),"GENNE_MCP_ALLOWED_ORIGINS"),G=new URL(r).origin,A=s.map(D=>new URL(D).origin),b=new Set(S.length?S:[e,G,...A]);return Object.freeze({resource:r,issuer:e,coreOrigin:n,adminOrigin:a,clientId:o,redirectUris:Object.freeze(s),adapterKeyFile:u,storeKeyFile:f,storePath:l,port:h,bind:m,maxBody:T,allowedOrigins:b})}i(et,"loadRemoteConfig");function _(t,r=200){return new Response(JSON.stringify(t),{status:r,headers:{"content-type":"application/json","cache-control":"no-store"}})}i(_,"responseJson");function nt(t,r){if(typeof t!="string"||!t.startsWith("/")||t.startsWith("//")||t.includes("\\"))throw new d;let e;try{e=new URL(t,r)}catch{throw new d}if(e.origin!==new URL(r).origin||e.username||e.password||e.hash||e.pathname.includes("//"))throw new d;return e}i(nt,"parseTarget");function ot(t){return Q.has(t)||/^\/oauth\/grants\/[0-9a-f-]{36}\/revoke$/u.test(t)}i(ot,"knownRequestPath");function it(t){const r=new Headers;for(const[e,n]of Object.entries(t.headers))if(Array.isArray(n))for(const a of n)r.append(e,a);else n!==void 0&&r.set(e,n);return r}i(it,"headerValues");function at(t){const r=t.headers["content-length"];if(r===void 0)return;if(Array.isArray(r)||!/^(?:0|[1-9]\d*)$/u.test(r))throw new d;const e=Number(r);if(!Number.isSafeInteger(e))throw new d;return e}i(at,"contentLength");async function st(t,r){let e;try{e=at(t)}catch(n){throw t.resume(),n}if(e!==void 0&&e>r)throw t.resume(),new I;return["GET","HEAD"].includes(t.method)?Buffer.alloc(0):new Promise((n,a)=>{const o=[];let s=0,u=!1;const f=i(l=>{u||(u=!0,t.resume(),a(l))},"fail");t.on("data",l=>{if(!u){if(s+=l.length,s>r){f(new I);return}o.push(l)}}),t.once("end",()=>{u||(u=!0,n(Buffer.concat(o,s)))}),t.once("aborted",()=>f(new d)),t.once("error",()=>f(new d))})}i(st,"readBoundedBody");function N(t,r){return r&&(t.headers.set("access-control-allow-origin",r),t.headers.set("access-control-expose-headers","WWW-Authenticate, MCP-Session-Id"),t.headers.append("vary","Origin")),t}i(N,"addCors");async function w(t,r){if(r.statusCode=t.status,t.headers.forEach((e,n)=>r.setHeader(n,e)),!t.body){r.end();return}try{for await(const e of x.fromWeb(t.body))r.write(e)||await new Promise((n,a)=>{const o=i(()=>{r.off("drain",s),r.off("close",u),r.off("error",f)},"cleanup"),s=i(()=>{o(),n()},"onDrain"),u=i(()=>{o(),a(new Error("response_closed"))},"onClose"),f=i(l=>{o(),a(l)},"onError");r.once("drain",s),r.once("close",u),r.once("error",f)});r.end()}catch{r.destroy()}}i(w,"sendResponse");function ct(t){return t instanceof I?_({error:"request_too_large"},413):t instanceof d?_({error:"invalid_request"},400):_({error:"internal_error"},500)}i(ct,"safeError");function ut({config:t,handler:r}){return async(e,n)=>{const a=new AbortController,o=i(()=>a.abort(),"onAbort");e.on("aborted",o);try{await $(a.signal,()=>ft(e,n,t,r))}finally{e.off("aborted",o)}}}i(ut,"requestHandler");async function ft(t,r,e,n){const a=t.headers.origin;if(a!==void 0&&(!C(a)||!e.allowedOrigins.has(a))){await w(_({error:"forbidden"},403),r);return}try{const o=nt(t.url,e.resource);if(t.method==="OPTIONS"){if(!a){await w(_({error:"invalid_request"},400),r);return}const h=new Response(null,{status:204,headers:{"cache-control":"no-store","access-control-allow-methods":"GET,HEAD,POST,OPTIONS","access-control-allow-headers":"Authorization, Content-Type, Accept, MCP-Protocol-Version, MCP-Session-Id, Last-Event-ID"}});await w(N(h,a),r);return}const s=await st(t,e.maxBody);if(o.pathname==="/health"){await w(N(_({service:K,version:V}),a),r);return}if(!ot(o.pathname)){await w(N(_({error:"not_found"},404),a),r);return}const u=it(t),f={method:t.method,headers:u};!["GET","HEAD"].includes(t.method)&&s.length>0&&(f.body=s);const l=await n(new Request(o,f));await w(N(l,a),r)}catch(o){await w(N(ct(o),a),r)}}i(ft,"serveRequest");function lt(t,r,e){return new Promise((n,a)=>{const o=i(u=>{t.off("listening",s),a(u)},"onError"),s=i(()=>{t.off("error",o),n(t.address())},"onListening");t.once("error",o),t.once("listening",s),t.listen(r,e)})}i(lt,"listen");async function Et(t){await new Promise((r,e)=>{t.close(n=>{!n||n.code==="ERR_SERVER_NOT_RUNNING"?r():e(n)})})}i(Et,"closeServer");async function dt({env:t=process.env,fetchImpl:r=fetch}={}){const e=et(t),n=await M(t,"GENNE_MCP_ADAPTER_KEY_FILE"),a=await M(t,"GENNE_MCP_STORE_KEY_FILE",{key:!0}),o=await F(e.storePath,a);try{const s=k({origin:e.coreOrigin,adapterKey:n,consentOrigin:e.adminOrigin,fetchImpl:r}),u=H({store:o,core:s,resource:e.resource,issuer:e.issuer,clientId:e.clientId,redirectUris:e.redirectUris}),f=z({auth:u,coreOrigin:e.coreOrigin,resource:e.resource,adapterKey:n,adminOrigin:e.adminOrigin,fetchImpl:r}),l=W({auth:u,core:s,mcpHandler:f}),h=L(ut({config:e,handler:l}));let m=!1;return{config:e,server:h,listen:i(()=>lt(h,e.port,e.bind),"listen"),close:i(async()=>{if(!m){m=!0;try{await Et(h)}finally{o.close()}}},"close")}}catch(s){throw o.close(),s}}i(dt,"createRemoteServer");async function ht(t={}){const r=await dt(t);try{return await r.listen(),r}catch(e){throw await r.close(),e}}i(ht,"startRemoteServer");async function _t(){const t=await ht(),r=i(async()=>{try{await t.close()}catch{process.exitCode=1}},"stop");process.once("SIGINT",r),process.once("SIGTERM",r)}i(_t,"main");function wt(){if(!process.argv[1])return!1;try{return y(process.argv[1])===y(v(import.meta.url))}catch{return!1}}i(wt,"isMainModule"),wt()&&_t().catch(()=>{console.error("genne-mcp-remote: failed to start; check the runtime configuration"),process.exitCode=1});export{X as DEFAULT_MAX_REQUEST_BODY_BYTES,K as REMOTE_SERVER_NAME,V as REMOTE_SERVER_VERSION,dt as createRemoteServer,et as loadRemoteConfig,ht as startRemoteServer};
2
+ var B=Object.defineProperty;var i=(t,r)=>B(t,"name",{value:r,configurable:!0});import{createServer as L}from"node:http";import{realpathSync as y}from"node:fs";import{readOwnedFile as U}from"./private-file.js";import{runWithRequestSignal as $}from"./request-scope.js";import{Readable as x}from"node:stream";import{isAbsolute as R}from"node:path";import{fileURLToPath as v}from"node:url";import Y from"../package.json"with{type:"json"};import{openRemoteAuthStore as F}from"./remote-auth-store.js";import{createRemoteAuth as H}from"./remote-auth.js";import{normalizeOAuthRedirect as k}from"./oauth-redirect.js";import{createRemoteCore as z}from"./remote-core.js";import{createRemoteOAuthHandler as W}from"./remote-http.js";import{createRemoteProductMcpHandler as K}from"./mcp.js";const V="genne-mcp-remote",X=Y.version,j=1024*1024,J=16*1024*1024,Q=new Set(["localhost","127.0.0.1","[::1]"]),Z=new Set(["/health","/mcp","/oauth/authorize","/oauth/handoff","/oauth/token","/oauth/grants","/.well-known/oauth-protected-resource","/.well-known/oauth-authorization-server"]);class c extends Error{static{i(this,"RemoteConfigError")}constructor(r){super(r),this.name="RemoteConfigError"}}class I extends Error{static{i(this,"RequestTooLargeError")}constructor(){super("request_too_large"),this.name="RequestTooLargeError"}}class E extends Error{static{i(this,"InvalidRequestTargetError")}constructor(){super("invalid_request_target"),this.name="InvalidRequestTargetError"}}const O=i(t=>typeof t=="string"&&t.trim()!=="","hasValue");function p(t,r){if(O(t[r]))return t[r].trim()}i(p,"valueFrom");function d(t,r){const e=p(t,r);if(!e)throw new c(`Missing required configuration: ${r}`);return e}i(d,"requiredValue");function S(t,r,{https:e=!0,root:n=!1,expectedPath:a}={}){let o;try{o=new URL(t)}catch{throw new c(`Invalid ${r}`)}if(e&&o.protocol!=="https:"||!e&&!["https:","http:"].includes(o.protocol)||o.username||o.password||o.search||o.hash||n&&o.pathname!=="/"||a!==void 0&&o.pathname!==a)throw new c(`Invalid ${r}`);return o.href}i(S,"url");function g(t,r,{https:e=!0,allowLocalHttp:n=!1}={}){const a=S(t,r,{https:e&&!n}),o=new URL(a);if(o.pathname!=="/"||o.port&&!/^\d+$/.test(o.port))throw new c(`Invalid ${r}`);if(n&&o.protocol==="http:"&&!Q.has(o.hostname))throw new c(`Invalid ${r}`);return o.origin}i(g,"origin");function q(t){let r;try{r=t.startsWith("[")?JSON.parse(t):t.split(/[\n,]/u).map(n=>n.trim()).filter(Boolean)}catch{throw new c("Invalid GENNE_MCP_REDIRECT_URIS")}if(!Array.isArray(r)||r.length===0||r.some(n=>typeof n!="string"||!n.trim()))throw new c("Invalid GENNE_MCP_REDIRECT_URIS");let e;try{e=r.map(n=>k(n.trim()))}catch{throw new c("Invalid GENNE_MCP_REDIRECT_URIS")}if(new Set(e).size!==e.length)throw new c("Duplicate GENNE_MCP_REDIRECT_URIS");return e}i(q,"redirectUris");function tt(t,r){if(!O(t))return[];const e=t.split(/[\n,]/u).map(n=>n.trim()).filter(Boolean);if(e.length===0)throw new c(`Invalid ${r}`);return e.map(n=>g(n,r))}i(tt,"origins");function P(t,r,{min:e,max:n}){if(!/^(?:0|[1-9]\d*)$/u.test(t))throw new c(`Invalid ${r}`);const a=Number(t);if(!Number.isSafeInteger(a)||a<e||a>n)throw new c(`Invalid ${r}`);return a}i(P,"integer");function rt(t,r){if(t.length===32)return t;const e=t.toString("utf8").trim();if(/^[0-9a-f]{64}$/iu.test(e))return Buffer.from(e,"hex");try{const n=Buffer.from(e,"base64url");if(n.length===32&&n.toString("base64url")===e.replace(/=+$/u,""))return n}catch{}throw new c(`Invalid ${r}`)}i(rt,"keyFromBytes");async function et(t,r){try{return await U(t)}catch(e){throw e?.code==="ENOENT"?new c(`Cannot read ${r}`):new c(`Insecure ${r}`)}}i(et,"secureFile");async function M(t,r,{key:e=!1}={}){const n=d(t,r),a=await et(n,r),o=Buffer.isBuffer(a)?a:Buffer.from(a,"utf8");if(e)return rt(o,r);const s=o.toString("utf8").trim();if(s.length<32||/[\u0000-\u001f\u007f]/u.test(s))throw new c(`Invalid ${r}`);return s}i(M,"secret");function nt(t=process.env){const r=S(d(t,"GENNE_MCP_RESOURCE"),"GENNE_MCP_RESOURCE",{expectedPath:"/mcp"}),e=g(d(t,"GENNE_MCP_ISSUER"),"GENNE_MCP_ISSUER"),n=g(d(t,"GENNE_MCP_CORE_ORIGIN"),"GENNE_MCP_CORE_ORIGIN",{allowLocalHttp:!0}),a=g(d(t,"GENNE_MCP_ADMIN_ORIGIN"),"GENNE_MCP_ADMIN_ORIGIN"),o=d(t,"GENNE_MCP_CLIENT_ID");if(!/^[A-Za-z0-9._~-]{1,128}$/u.test(o))throw new c("Invalid GENNE_MCP_CLIENT_ID");const s=q(d(t,"GENNE_MCP_REDIRECT_URIS")),u=d(t,"GENNE_MCP_ADAPTER_KEY_FILE"),f=d(t,"GENNE_MCP_STORE_KEY_FILE");if(!R(u)||!R(f))throw new c("Secret file paths must be absolute");const l=d(t,"GENNE_MCP_STORE_PATH");if(!R(l))throw new c("GENNE_MCP_STORE_PATH must be absolute");const h=P(d(t,"GENNE_MCP_PORT"),"GENNE_MCP_PORT",{min:0,max:65535}),m=d(t,"GENNE_MCP_BIND");if(!/^(?:[A-Za-z0-9.-]+|\[[0-9A-Fa-f:]+\])$/u.test(m))throw new c("Invalid GENNE_MCP_BIND");const T=p(t,"GENNE_MCP_MAX_BODY_BYTES")?P(p(t,"GENNE_MCP_MAX_BODY_BYTES"),"GENNE_MCP_MAX_BODY_BYTES",{min:1,max:J}):j,C=tt(p(t,"GENNE_MCP_ALLOWED_ORIGINS"),"GENNE_MCP_ALLOWED_ORIGINS"),G=new URL(r).origin,A=s.map(D=>new URL(D).origin),b=new Set(C.length?C:[e,G,...A]);return Object.freeze({resource:r,issuer:e,coreOrigin:n,adminOrigin:a,clientId:o,redirectUris:Object.freeze(s),adapterKeyFile:u,storeKeyFile:f,storePath:l,port:h,bind:m,maxBody:T,allowedOrigins:b})}i(nt,"loadRemoteConfig");function _(t,r=200){return new Response(JSON.stringify(t),{status:r,headers:{"content-type":"application/json","cache-control":"no-store"}})}i(_,"responseJson");function ot(t,r){if(typeof t!="string"||!t.startsWith("/")||t.startsWith("//")||t.includes("\\"))throw new E;let e;try{e=new URL(t,r)}catch{throw new E}if(e.origin!==new URL(r).origin||e.username||e.password||e.hash||e.pathname.includes("//"))throw new E;return e}i(ot,"parseTarget");function it(t){return Z.has(t)||/^\/oauth\/grants\/[0-9a-f-]{36}\/revoke$/u.test(t)}i(it,"knownRequestPath");function at(t){const r=new Headers;for(const[e,n]of Object.entries(t.headers))if(Array.isArray(n))for(const a of n)r.append(e,a);else n!==void 0&&r.set(e,n);return r}i(at,"headerValues");function st(t){const r=t.headers["content-length"];if(r===void 0)return;if(Array.isArray(r)||!/^(?:0|[1-9]\d*)$/u.test(r))throw new E;const e=Number(r);if(!Number.isSafeInteger(e))throw new E;return e}i(st,"contentLength");async function ct(t,r){let e;try{e=st(t)}catch(n){throw t.resume(),n}if(e!==void 0&&e>r)throw t.resume(),new I;return["GET","HEAD"].includes(t.method)?Buffer.alloc(0):new Promise((n,a)=>{const o=[];let s=0,u=!1;const f=i(l=>{u||(u=!0,t.resume(),a(l))},"fail");t.on("data",l=>{if(!u){if(s+=l.length,s>r){f(new I);return}o.push(l)}}),t.once("end",()=>{u||(u=!0,n(Buffer.concat(o,s)))}),t.once("aborted",()=>f(new E)),t.once("error",()=>f(new E))})}i(ct,"readBoundedBody");function N(t,r){return r&&(t.headers.set("access-control-allow-origin",r),t.headers.set("access-control-expose-headers","WWW-Authenticate, MCP-Session-Id"),t.headers.append("vary","Origin")),t}i(N,"addCors");async function w(t,r){if(r.statusCode=t.status,t.headers.forEach((e,n)=>r.setHeader(n,e)),!t.body){r.end();return}try{for await(const e of x.fromWeb(t.body))r.write(e)||await new Promise((n,a)=>{const o=i(()=>{r.off("drain",s),r.off("close",u),r.off("error",f)},"cleanup"),s=i(()=>{o(),n()},"onDrain"),u=i(()=>{o(),a(new Error("response_closed"))},"onClose"),f=i(l=>{o(),a(l)},"onError");r.once("drain",s),r.once("close",u),r.once("error",f)});r.end()}catch{r.destroy()}}i(w,"sendResponse");function ut(t){return t instanceof I?_({error:"request_too_large"},413):t instanceof E?_({error:"invalid_request"},400):_({error:"internal_error"},500)}i(ut,"safeError");function ft({config:t,handler:r}){return async(e,n)=>{const a=new AbortController,o=i(()=>a.abort(),"onAbort");e.on("aborted",o);try{await $(a.signal,()=>lt(e,n,t,r))}finally{e.off("aborted",o)}}}i(ft,"requestHandler");async function lt(t,r,e,n){const a=t.headers.origin;if(a!==void 0&&(!O(a)||!e.allowedOrigins.has(a))){await w(_({error:"forbidden"},403),r);return}try{const o=ot(t.url,e.resource);if(t.method==="OPTIONS"){if(!a){await w(_({error:"invalid_request"},400),r);return}const h=new Response(null,{status:204,headers:{"cache-control":"no-store","access-control-allow-methods":"GET,HEAD,POST,OPTIONS","access-control-allow-headers":"Authorization, Content-Type, Accept, MCP-Protocol-Version, MCP-Session-Id, Last-Event-ID"}});await w(N(h,a),r);return}const s=await ct(t,e.maxBody);if(o.pathname==="/health"){await w(N(_({service:V,version:X}),a),r);return}if(!it(o.pathname)){await w(N(_({error:"not_found"},404),a),r);return}const u=at(t),f={method:t.method,headers:u};!["GET","HEAD"].includes(t.method)&&s.length>0&&(f.body=s);const l=await n(new Request(o,f));await w(N(l,a),r)}catch(o){await w(N(ut(o),a),r)}}i(lt,"serveRequest");function dt(t,r,e){return new Promise((n,a)=>{const o=i(u=>{t.off("listening",s),a(u)},"onError"),s=i(()=>{t.off("error",o),n(t.address())},"onListening");t.once("error",o),t.once("listening",s),t.listen(r,e)})}i(dt,"listen");async function Et(t){await new Promise((r,e)=>{t.close(n=>{!n||n.code==="ERR_SERVER_NOT_RUNNING"?r():e(n)})})}i(Et,"closeServer");async function ht({env:t=process.env,fetchImpl:r=fetch}={}){const e=nt(t),n=await M(t,"GENNE_MCP_ADAPTER_KEY_FILE"),a=await M(t,"GENNE_MCP_STORE_KEY_FILE",{key:!0}),o=await F(e.storePath,a);try{const s=z({origin:e.coreOrigin,adapterKey:n,consentOrigin:e.adminOrigin,fetchImpl:r}),u=H({store:o,core:s,resource:e.resource,issuer:e.issuer,clientId:e.clientId,redirectUris:e.redirectUris}),f=K({auth:u,coreOrigin:e.coreOrigin,resource:e.resource,adapterKey:n,adminOrigin:e.adminOrigin,fetchImpl:r}),l=W({auth:u,core:s,mcpHandler:f}),h=L(ft({config:e,handler:l}));let m=!1;return{config:e,server:h,listen:i(()=>dt(h,e.port,e.bind),"listen"),close:i(async()=>{if(!m){m=!0;try{await Et(h)}finally{o.close()}}},"close")}}catch(s){throw o.close(),s}}i(ht,"createRemoteServer");async function _t(t={}){const r=await ht(t);try{return await r.listen(),r}catch(e){throw await r.close(),e}}i(_t,"startRemoteServer");async function wt(){const t=await _t(),r=i(async()=>{try{await t.close()}catch{process.exitCode=1}},"stop");process.once("SIGINT",r),process.once("SIGTERM",r)}i(wt,"main");function mt(){if(!process.argv[1])return!1;try{return y(process.argv[1])===y(v(import.meta.url))}catch{return!1}}i(mt,"isMainModule"),mt()&&wt().catch(()=>{console.error("genne-mcp-remote: failed to start; check the runtime configuration"),process.exitCode=1});export{j as DEFAULT_MAX_REQUEST_BODY_BYTES,V as REMOTE_SERVER_NAME,X as REMOTE_SERVER_VERSION,ht as createRemoteServer,nt as loadRemoteConfig,_t as startRemoteServer};