import{toFetchResponse as i,toReqRes as E}from"fetch-to-node";import{logger as d}from"../../../tools/notifiers/logger.js";import{DEFAULT_CONNECTION_TIMEOUT_MS as w}from"../constants.js";import{createMethodNotAllowedError as R,withErrorHandling as y}from"./errors.js";function N(u){const{createServerInstance:l,serverType:p,connectionTimeoutMs:m=w}=u;return async(r,h,f)=>{let e,n;const c=async()=>{try{n&&(clearTimeout(n),n=void 0),e&&(await e.cleanup(),e=void 0)}catch(a){d.error("Error during mcp server cleanup:",a)}};return y(async()=>{const a={};r.headers.forEach((o,T)=>{a[T]=o}),e=await l(h,f,a,r);const{req:s,res:t}=E(r);switch(n=setTimeout(()=>{c()},m),t.on("close",()=>{c().catch(o=>{d.error("Error during response close cleanup:",o)})}),r.method){case"GET":return await e.transport.handleRequest(s,t),i(t);case"POST":const o=await r.json();return await e.transport.handleRequest(s,t,o),i(t);default:return R()}},p,c)}}export{N as createMcpRequestHandler};
