xmcp 1.1.1 → 1.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -587,7 +587,7 @@ Expected ReadResourceResult format:
587
587
  clip: rect(0, 0, 0, 0);
588
588
  border: 0;
589
589
  }
590
- `;function fO(e){return`\u001b[33m${e}\u001b[39m`}var fA=a(9278),fI=a.n(fA);async function fq(e=3001,t="127.0.0.1"){return new Promise(a=>{let i;(i=fI().createServer(),new Promise((a,r)=>{i.once("error",e=>{"code"in e&&"EADDRINUSE"===e.code?a(!1):r(e)}),i.once("listening",()=>{i.close(),a(!0)}),i.listen(e,t)})).then(t=>{t?a(e):(console.log(`\u001b[1m\u001b[33m❯\u001b[39m\u001b[22m Port ${fO(String(e))} is in use, trying ${fO(String(e+1))} instead.`),fq(e+1).then(a))})})}let fN={origin:"*",methods:["GET","POST"],allowedHeaders:["Content-Type","Authorization","mcp-session-id","mcp-protocol-version","mcp-method","mcp-name","x-mcp-client-name","x-mcp-client-version","x-mcp-client-title","x-mcp-client-website-url","x-mcp-client-description"],exposedHeaders:["Content-Type","Authorization","mcp-session-id"],credentials:!1,maxAge:86400};function fz(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}class fM{log(e,...t){this.debug&&console.log(`[StatelessHTTP] ${e}`,...t)}setupProviders(){if(this.providers)for(let e of this.providers)e.router&&this.app.use(e.router),e.middleware&&this.app.use(e.middleware)}setupInitialMiddleware(){var e;this.app.use((e=this.corsConfig,(t,a,i)=>{let r=t.headers.origin;for(let[t,i]of Object.entries(function(e,t){let a={};if(void 0!==e.origin){if(!0===e.origin)t&&(a["Access-Control-Allow-Origin"]=t);else if(!1!==e.origin)if(Array.isArray(e.origin)){let i=t&&e.origin.includes(t)?t:e.origin[0]||"*";a["Access-Control-Allow-Origin"]=i}else a["Access-Control-Allow-Origin"]=String(e.origin)}return void 0!==e.methods&&(a["Access-Control-Allow-Methods"]=Array.isArray(e.methods)?e.methods.join(","):String(e.methods)),void 0!==e.allowedHeaders&&(a["Access-Control-Allow-Headers"]=Array.isArray(e.allowedHeaders)?e.allowedHeaders.join(","):String(e.allowedHeaders)),void 0!==e.exposedHeaders&&(a["Access-Control-Expose-Headers"]=Array.isArray(e.exposedHeaders)?e.exposedHeaders.join(","):String(e.exposedHeaders)),"boolean"==typeof e.credentials&&(a["Access-Control-Allow-Credentials"]=String(e.credentials)),"number"==typeof e.maxAge&&(a["Access-Control-Max-Age"]=String(e.maxAge)),a}(e,r)))a.setHeader(t,i);"OPTIONS"===t.method?a.status(204).end():i()})),this.app.use((e,t,a)=>{this.log(`${e.method} ${e.path}`),a()})}setupInitialRoutes(){this.app.get("/health",(e,t)=>{t.status(200).json({status:"ok",transport:"streamable-http",mode:"stateless"})}),this.app.get("/",(e,t)=>{var a,i,r;let n=this.options.template?.homePage;n?t.send(n):t.send((a=this.endpoint,i=this.options.template?.name,r=this.options.template?.description,`
590
+ `;function fO(e){return`\u001b[33m${e}\u001b[39m`}var fA=a(9278),fI=a.n(fA);async function fq(e=3001,t="127.0.0.1"){return new Promise(a=>{let i;(i=fI().createServer(),new Promise((a,r)=>{i.once("error",e=>{"code"in e&&"EADDRINUSE"===e.code?a(!1):r(e)}),i.once("listening",()=>{i.close(),a(!0)}),i.listen(e,t)})).then(t=>{t?a(e):(console.log(`\u001b[1m\u001b[33m❯\u001b[39m\u001b[22m Port ${fO(String(e))} is in use, trying ${fO(String(e+1))} instead.`),fq(e+1).then(a))})})}let fN={origin:"*",methods:["GET","POST"],allowedHeaders:["Content-Type","Authorization","mcp-session-id","mcp-protocol-version","mcp-method","mcp-name","x-mcp-client-name","x-mcp-client-version","x-mcp-client-title","x-mcp-client-website-url","x-mcp-client-description"],exposedHeaders:["Content-Type","Authorization","mcp-session-id"],credentials:!1,maxAge:86400};function fz(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}class fM{get requestListener(){return this.app}log(e,...t){this.debug&&console.log(`[StatelessHTTP] ${e}`,...t)}setupProviders(){if(this.providers)for(let e of this.providers)e.router&&this.app.use(e.router),e.middleware&&this.app.use(e.middleware)}setupInitialMiddleware(){var e;this.app.use((e=this.corsConfig,(t,a,i)=>{let r=t.headers.origin;for(let[t,i]of Object.entries(function(e,t){let a={};if(void 0!==e.origin){if(!0===e.origin)t&&(a["Access-Control-Allow-Origin"]=t);else if(!1!==e.origin)if(Array.isArray(e.origin)){let i=t&&e.origin.includes(t)?t:e.origin[0]||"*";a["Access-Control-Allow-Origin"]=i}else a["Access-Control-Allow-Origin"]=String(e.origin)}return void 0!==e.methods&&(a["Access-Control-Allow-Methods"]=Array.isArray(e.methods)?e.methods.join(","):String(e.methods)),void 0!==e.allowedHeaders&&(a["Access-Control-Allow-Headers"]=Array.isArray(e.allowedHeaders)?e.allowedHeaders.join(","):String(e.allowedHeaders)),void 0!==e.exposedHeaders&&(a["Access-Control-Expose-Headers"]=Array.isArray(e.exposedHeaders)?e.exposedHeaders.join(","):String(e.exposedHeaders)),"boolean"==typeof e.credentials&&(a["Access-Control-Allow-Credentials"]=String(e.credentials)),"number"==typeof e.maxAge&&(a["Access-Control-Max-Age"]=String(e.maxAge)),a}(e,r)))a.setHeader(t,i);"OPTIONS"===t.method?a.status(204).end():i()})),this.app.use((e,t,a)=>{this.log(`${e.method} ${e.path}`),a()})}setupInitialRoutes(){this.app.get("/health",(e,t)=>{t.status(200).json({status:"ok",transport:"streamable-http",mode:"stateless"})}),this.app.get("/",(e,t)=>{var a,i,r;let n=this.options.template?.homePage;n?t.send(n):t.send((a=this.endpoint,i=this.options.template?.name,r=this.options.template?.description,`
591
591
  <!DOCTYPE html>
592
592
  <html lang="en">
593
593
  <head>
@@ -956,4 +956,4 @@ data: ${JSON.stringify({jsonrpc:"2.0",method:e,params:t})}
956
956
  `)},j=e=>{if(!S){e&&k(`event: message
957
957
  data: ${JSON.stringify({jsonrpc:"2.0",id:_,result:{resultType:"complete",_meta:{[rR]:_,[rj]:c}}})}
958
958
 
959
- `),S=!0;try{m?.()}catch(e){a?.(e instanceof Error?e:Error(String(e)))}void 0!==f&&clearInterval(f),h?.(),n.delete(j);try{d.close()}catch{}}},E=new ReadableStream({start(e){d=e;let a=ua({method:"notifications/subscriptions/acknowledged",params:{notifications:x}},_);$(a.method,a.params),m=t.subscribe(e=>{if(S||!function(e,t){switch(t.kind){case"tools_list_changed":return!0===e.toolsListChanged;case"prompts_list_changed":return!0===e.promptsListChanged;case"resources_list_changed":return!0===e.resourcesListChanged;case"resource_updated":return void 0!==e.resourceSubscriptions&&e.resourceSubscriptions.includes(t.uri)}}(x,e))return;let t=ua(function(e){switch(e.kind){case"tools_list_changed":return{method:"notifications/tools/list_changed"};case"prompts_list_changed":return{method:"notifications/prompts/list_changed"};case"resources_list_changed":return{method:"notifications/resources/list_changed"};case"resource_updated":return{method:"notifications/resources/updated",params:{uri:e.uri}}}}(e),_);$(t.method,t.params)}),f=p7(r,()=>k(": keepalive\n\n")),n.add(j)},cancel(){j(!1)}});if(void 0!==o)if(o.aborted)j(!1);else{let e=()=>j(!1);o.addEventListener("abort",e,{once:!0}),h=()=>o.removeEventListener("abort",e)}return new Response(E,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}})},closeAll(){for(let e of n)e(!0)},get openCount(){return n.size}}}({bus:m,maxSubscriptions:t.maxSubscriptions??1024,keepAliveMs:t.keepAliveMs??15e3,onerror:d});"json"===n&&console.warn("responseMode: 'json' drops mid-call notifications. subscriptions/listen streams are always served over SSE regardless; other notifications emitted before a result are dropped.");let v="reject"===i?void 0:(a=t.keepAliveMs,async(t,i)=>{if("POST"!==t.method.toUpperCase())return uw(405,-32e3,"Method not allowed.");try{let r=await e({era:"legacy",...i?.authInfo!==void 0&&{authInfo:i.authInfo},requestInfo:t}),n=new ux({sessionIdGenerator:void 0,...void 0!==a&&{keepAliveMs:a}});await r.connect(n);let o=()=>{n.close().catch(()=>{}),r.close().catch(()=>{})};t.signal?.addEventListener("abort",o,{once:!0});let s=await n.handleRequest(t,{...i?.authInfo!==void 0&&{authInfo:i.authInfo},...i?.parsedBody!==void 0&&{parsedBody:i.parsedBody}});if(null===s.body||"text/event-stream"!==ll(s.headers.get("content-type")))return o(),s;let c=s.body.getReader(),l=!1,p=()=>{l||(l=!0,o())},u=new ReadableStream({pull:async e=>{try{let{done:t,value:a}=await c.read();if(t){p(),e.close();return}void 0!==a&&e.enqueue(a)}catch(t){p(),e.error(t)}},cancel:e=>(p(),c.cancel(e).catch(()=>{}))});return new Response(u,{status:s.status,statusText:s.statusText,headers:s.headers})}catch(e){try{d?.(uk(e))}catch{}return u$(u_(i?.parsedBody))}});async function g(a,i,r){var u,m;let f=a.classification.revision;if(void 0===f||!sE.includes(f)){let e=new s9({supported:[...sE],requested:f??"unknown"});return d(e),uw(400,e.code,e.message,e.data,u_(a.message))}let v=function(e,t){if("request"!==t.messageKind)return;let a=t.message.method;if(void 0===e.mcpMethodHeader)return cU("method-header-missing","(missing)",`the body names method ${a} but the required Mcp-Method header is absent`,"standard-header-validation");let i=Object.hasOwn(cH,a)?cH[a]:void 0;if(void 0===i)return;let r=t.message.params?.[i],n="string"==typeof r?r:void 0;if(void 0===e.mcpNameHeader){if(void 0===n)return;return cU("name-header-missing","(missing)",`the body carries params.${i}="${n}" but the required Mcp-Name header is absent`,"standard-header-validation")}let o=cV(e.mcpNameHeader),s=cz(o);return void 0===s?cU("name-header-invalid-encoding",o,"the Mcp-Name header carries an invalid Base64 sentinel value","standard-header-validation"):void 0!==n&&s!==n?cU("name-header-mismatch",o,`the body carries params.${i}="${n}" but the Mcp-Name header names "${s}"`,"standard-header-validation"):void 0}({httpMethod:i.method,mcpMethodHeader:i.headers.get("mcp-method")??void 0,mcpNameHeader:i.headers.get("mcp-name")??void 0},a);if(void 0!==v)return d(Error(`Rejected inbound request (${v.cell}): ${v.message}`)),uS(v,u_(a.message));let g="request"===a.messageKind?cy(a.message.params):void 0,y=g?.[rE];if("request"===a.messageKind){let e=Object.hasOwn(sS,u=a.message.method)?sS[u]:void 0;if(void 0!==e){let t=s$(e,y);if(void 0!==t){let e=new s5({requiredCapabilities:t});return d(e),uw(cD[e.code]??400,e.code,e.message,e.data,a.message.id)}}}let b=await e({era:"modern",...void 0!==r&&{authInfo:r},requestInfo:i}),x=b instanceof uc?b.server:b;if("request"===a.messageKind&&"subscriptions/listen"===a.message.method){let e=x.getCapabilities(),t=l(x);return b.close().catch(d),h.serve(a.message,i.signal,e,t)}if("request"===a.messageKind&&"tools/call"===a.message.method&&b instanceof uc){let e=a.message.params,t="string"==typeof e?.name?e.name:void 0,r=void 0===t?void 0:b.toolInputSchemaJson(t);if(void 0!==r){let t=cP(r);if(t.valid&&t.declarations.length>0){let r=function(e,t,a){for(let i of e){let e=`Mcp-Param-${i.headerName}`,r=a.get(e),n=function(e,t){let a=e;for(let e of t){if(null===a||"object"!=typeof a)return;a=a[e]}return a}(t,i.path);if(null==n)continue;let o=function(e){if("string"==typeof e)return e;if("boolean"==typeof e)return e?"true":"false";if("number"==typeof e){if(!Number.isFinite(e)||Number.isInteger(e)&&!Number.isSafeInteger(e))return;return String(e)}}(n);if(void 0===o)continue;if(null===r)return cM("param-header-missing",e,`the body carries ${cI(i.path)}=${JSON.stringify(n)} but the ${e} header is absent`);let s=cz(r);if(void 0===s)return cM("param-header-invalid-encoding",e,`the ${e} header carries an invalid Base64 sentinel value`);if(!(("integer"===i.type||"number"===i.type)&&cN.test(s)&&"number"==typeof n?Number(s)===n:s===o))return cM("param-header-mismatch",e,`the ${e} header decodes to ${JSON.stringify(s)} but the body carries ${cI(i.path)}=${JSON.stringify(n)}`)}}(t.declarations,e?.arguments,i.headers);if(void 0!==r)return b.close().catch(d),d(Error(`Rejected inbound request (${r.cell}): ${r.message}`)),uS(r,a.message.id)}}}o(x,f),c(x,sE),void 0!==g&&(m={clientInfo:g[r$],clientCapabilities:y},s(x,m));let _=x.onclose;p.add(x),x.onclose=()=>{p.delete(x),_?.()};try{let e=await ub(b,a.message,{classification:a.classification,request:i,...void 0!==r&&{authInfo:r},...void 0!==n&&{responseMode:n},...void 0!==t.keepAliveMs&&{keepAliveMs:t.keepAliveMs}});return"notification"===a.messageKind&&queueMicrotask(()=>void x.close().catch(()=>{})),e}catch(e){if(e instanceof sw&&e.code===s_.ConnectionClosed)return new Response(null,{status:499});return await x.close().catch(()=>{}),p.delete(x),d(uk(e)),u$(u_(a.message))}}async function y(e,t,a,i){if(void 0!==v)return v(t,{...void 0!==a&&{authInfo:a},...void 0!==i&&{parsedBody:i}});let r=function(e,t){switch(e.reason){case"http-method":return cF("http-method","modern-only-method-not-allowed",405,new s2(-32e3,"Method not allowed."),!0);case"batch":return cF("jsonrpc-shape","modern-only-batch-not-supported",400,new s2(s1.InvalidRequest,"Bad Request: JSON-RPC batches are not supported by this endpoint"),!0);case"response":return cF("jsonrpc-shape","modern-only-response-post",400,new s2(s1.InvalidRequest,"Bad Request: JSON-RPC responses cannot be posted to this endpoint"),!0);case"notification":return;case"initialize":case"no-claim":{let a=e.requestedVersion;return cF("era-classification","modern-only-missing-envelope",400,void 0===a?new s2(s1.UnsupportedProtocolVersion,"Unsupported protocol version: the request did not name a protocol version",{supported:[...t]}):new s9({supported:[...t],requested:a}),!0)}}}(e,sE);return void 0===r?new Response(null,{status:202}):(d(Error(`Rejected 2025-era request on a modern-only endpoint (${r.cell}): ${r.message}`)),uS(r,u_(i)))}async function b(e,t){let a=t?.authInfo;if("POST"===e.method.toUpperCase()&&!lp(e.headers.get("content-type")))return d(Error("Unsupported Media Type: Content-Type must be application/json")),uw(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let i=await uj(e,t?.parsedBody);if("unreadable-body"===i.step)return uw(400,-32700,"Parse error: the request body could not be read");if("no-json-body"===i.step)return void 0!==v?v(i.forwardRequest,{...void 0!==a&&{authInfo:a}}):uw(400,-32700,"Parse error: the request body is not valid JSON");let{outcome:r,body:n,parsedBody:o,forwardRequest:s}=i;try{switch(r.kind){case"reject":return d(Error(`Rejected inbound request (${r.cell}): ${r.message}`)),uS(r,u_(n));case"modern":return await g(r,e,a);case"legacy":return await y(r,s,a,o)}}catch(e){return d(uk(e)),u$(u_(n))}}return{fetch:async(e,t)=>{if(u)throw Error("This MCP handler has been closed");try{return await b(e,t)}catch(e){return d(uk(e)),u$(u_(t?.parsedBody))}},notify:f,bus:m,close:async()=>{u=!0,h.closeAll();let e=[...p].map(e=>e.close().catch(()=>{}));p.clear(),await Promise.all(e)}}}(()=>this.createServerFn(),{legacy:"stateless",onerror:e=>this.log("MCP handler error:",e)}),this.nodeMcpHandler=(r=this.mcpHandler,n={onerror:e=>console.error("[HTTP-server] Error handling MCP request:",e)},async(e,t,a)=>{let i,o;"function"==typeof a&&(a=void 0);let s=!1,c=new AbortController;t.on("close",()=>{s||c.abort()}),!0===t.destroyed&&c.abort();try{let t=await f$(e,a,{signal:c.signal});i=await r.fetch(t,{...void 0!==e.auth&&{authInfo:e.auth},...void 0!==a&&{parsedBody:a}})}catch(e){var l;try{n?.onerror?.(e instanceof Error?e:Error(String(e)))}catch{}l=function(e){if(null===e||"object"!=typeof e||Array.isArray(e))return null;let{method:t,id:a}=e;return"string"!=typeof t?null:"string"==typeof a||"number"==typeof a?a:null}(a),i=Response.json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:l},{status:500})}let p={};for(let[e,t]of i.headers)p[e]=t;if(t.writeHead(i.status,p),null===i.body){s=!0,t.end();return}t.on("drain",()=>{o?.(),o=void 0});let u=new Promise(e=>{c.signal.addEventListener("abort",()=>e(),{once:!0})});try{for await(let e of i.body){if(c.signal.aborted)break;!1===t.write(e)&&await Promise.race([new Promise(e=>{o=e}),u])}}catch{}s=!0,t.end()}),this.app.use(fE().json({limit:this.options.bodySizeLimit||"10mb"})),this.setupInitialRoutes(),this.setupInitialMiddleware(),this.setupProviders(),this.setupEndpointRoute()}}function fL(e){return"function"==typeof e}function fD(e){var t;return"object"==typeof e&&null!==e&&"middleware"in e&&"router"in e&&"function"==typeof e.middleware&&"function"==typeof(t=e.router)&&null!==t&&"function"==typeof t.use&&"function"==typeof t.get&&"function"==typeof t.post&&"function"==typeof t.route}let fF=mn({name:"http-transport-context"});fF.setContext,fF.getContext;let fU=fF.provider;var fH=a(8583);a.n(fH)().config();let fV=HTTP_CONFIG,fZ=HTTP_CORS_CONFIG,fB=TEMPLATE_CONFIG,fJ=INJECTED_MIDDLEWARE;!async function(){let e={port:fV?.port,host:fV?.host,debug:fV?.debug,bodySizeLimit:fV?.bodySizeLimit?.toString(),endpoint:fV?.endpoint,template:fB},t={origin:fZ.origin,methods:fZ.methods,allowedHeaders:fZ.allowedHeaders,exposedHeaders:fZ.exposedHeaders,credentials:fZ.credentials,maxAge:fZ.maxAge},a=[];if(fJ){let e=await fJ();e&&e.default&&(a=function(e){let t=[];if(Array.isArray(e))for(let a of e)fL(a)?t.push({middleware:a}):fD(a)&&t.push({middleware:a.middleware,router:a.router});else fL(e)?t.push({middleware:e}):fD(e)&&t.push({middleware:e.middleware,router:e.router});return t}(e.default))}fU({config:{http:fV}},async()=>{let i=new fM(fi,e,t,a);await i.start()})}()})(),{}})());
959
+ `),S=!0;try{m?.()}catch(e){a?.(e instanceof Error?e:Error(String(e)))}void 0!==f&&clearInterval(f),h?.(),n.delete(j);try{d.close()}catch{}}},E=new ReadableStream({start(e){d=e;let a=ua({method:"notifications/subscriptions/acknowledged",params:{notifications:x}},_);$(a.method,a.params),m=t.subscribe(e=>{if(S||!function(e,t){switch(t.kind){case"tools_list_changed":return!0===e.toolsListChanged;case"prompts_list_changed":return!0===e.promptsListChanged;case"resources_list_changed":return!0===e.resourcesListChanged;case"resource_updated":return void 0!==e.resourceSubscriptions&&e.resourceSubscriptions.includes(t.uri)}}(x,e))return;let t=ua(function(e){switch(e.kind){case"tools_list_changed":return{method:"notifications/tools/list_changed"};case"prompts_list_changed":return{method:"notifications/prompts/list_changed"};case"resources_list_changed":return{method:"notifications/resources/list_changed"};case"resource_updated":return{method:"notifications/resources/updated",params:{uri:e.uri}}}}(e),_);$(t.method,t.params)}),f=p7(r,()=>k(": keepalive\n\n")),n.add(j)},cancel(){j(!1)}});if(void 0!==o)if(o.aborted)j(!1);else{let e=()=>j(!1);o.addEventListener("abort",e,{once:!0}),h=()=>o.removeEventListener("abort",e)}return new Response(E,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}})},closeAll(){for(let e of n)e(!0)},get openCount(){return n.size}}}({bus:m,maxSubscriptions:t.maxSubscriptions??1024,keepAliveMs:t.keepAliveMs??15e3,onerror:d});"json"===n&&console.warn("responseMode: 'json' drops mid-call notifications. subscriptions/listen streams are always served over SSE regardless; other notifications emitted before a result are dropped.");let v="reject"===i?void 0:(a=t.keepAliveMs,async(t,i)=>{if("POST"!==t.method.toUpperCase())return uw(405,-32e3,"Method not allowed.");try{let r=await e({era:"legacy",...i?.authInfo!==void 0&&{authInfo:i.authInfo},requestInfo:t}),n=new ux({sessionIdGenerator:void 0,...void 0!==a&&{keepAliveMs:a}});await r.connect(n);let o=()=>{n.close().catch(()=>{}),r.close().catch(()=>{})};t.signal?.addEventListener("abort",o,{once:!0});let s=await n.handleRequest(t,{...i?.authInfo!==void 0&&{authInfo:i.authInfo},...i?.parsedBody!==void 0&&{parsedBody:i.parsedBody}});if(null===s.body||"text/event-stream"!==ll(s.headers.get("content-type")))return o(),s;let c=s.body.getReader(),l=!1,p=()=>{l||(l=!0,o())},u=new ReadableStream({pull:async e=>{try{let{done:t,value:a}=await c.read();if(t){p(),e.close();return}void 0!==a&&e.enqueue(a)}catch(t){p(),e.error(t)}},cancel:e=>(p(),c.cancel(e).catch(()=>{}))});return new Response(u,{status:s.status,statusText:s.statusText,headers:s.headers})}catch(e){try{d?.(uk(e))}catch{}return u$(u_(i?.parsedBody))}});async function g(a,i,r){var u,m;let f=a.classification.revision;if(void 0===f||!sE.includes(f)){let e=new s9({supported:[...sE],requested:f??"unknown"});return d(e),uw(400,e.code,e.message,e.data,u_(a.message))}let v=function(e,t){if("request"!==t.messageKind)return;let a=t.message.method;if(void 0===e.mcpMethodHeader)return cU("method-header-missing","(missing)",`the body names method ${a} but the required Mcp-Method header is absent`,"standard-header-validation");let i=Object.hasOwn(cH,a)?cH[a]:void 0;if(void 0===i)return;let r=t.message.params?.[i],n="string"==typeof r?r:void 0;if(void 0===e.mcpNameHeader){if(void 0===n)return;return cU("name-header-missing","(missing)",`the body carries params.${i}="${n}" but the required Mcp-Name header is absent`,"standard-header-validation")}let o=cV(e.mcpNameHeader),s=cz(o);return void 0===s?cU("name-header-invalid-encoding",o,"the Mcp-Name header carries an invalid Base64 sentinel value","standard-header-validation"):void 0!==n&&s!==n?cU("name-header-mismatch",o,`the body carries params.${i}="${n}" but the Mcp-Name header names "${s}"`,"standard-header-validation"):void 0}({httpMethod:i.method,mcpMethodHeader:i.headers.get("mcp-method")??void 0,mcpNameHeader:i.headers.get("mcp-name")??void 0},a);if(void 0!==v)return d(Error(`Rejected inbound request (${v.cell}): ${v.message}`)),uS(v,u_(a.message));let g="request"===a.messageKind?cy(a.message.params):void 0,y=g?.[rE];if("request"===a.messageKind){let e=Object.hasOwn(sS,u=a.message.method)?sS[u]:void 0;if(void 0!==e){let t=s$(e,y);if(void 0!==t){let e=new s5({requiredCapabilities:t});return d(e),uw(cD[e.code]??400,e.code,e.message,e.data,a.message.id)}}}let b=await e({era:"modern",...void 0!==r&&{authInfo:r},requestInfo:i}),x=b instanceof uc?b.server:b;if("request"===a.messageKind&&"subscriptions/listen"===a.message.method){let e=x.getCapabilities(),t=l(x);return b.close().catch(d),h.serve(a.message,i.signal,e,t)}if("request"===a.messageKind&&"tools/call"===a.message.method&&b instanceof uc){let e=a.message.params,t="string"==typeof e?.name?e.name:void 0,r=void 0===t?void 0:b.toolInputSchemaJson(t);if(void 0!==r){let t=cP(r);if(t.valid&&t.declarations.length>0){let r=function(e,t,a){for(let i of e){let e=`Mcp-Param-${i.headerName}`,r=a.get(e),n=function(e,t){let a=e;for(let e of t){if(null===a||"object"!=typeof a)return;a=a[e]}return a}(t,i.path);if(null==n)continue;let o=function(e){if("string"==typeof e)return e;if("boolean"==typeof e)return e?"true":"false";if("number"==typeof e){if(!Number.isFinite(e)||Number.isInteger(e)&&!Number.isSafeInteger(e))return;return String(e)}}(n);if(void 0===o)continue;if(null===r)return cM("param-header-missing",e,`the body carries ${cI(i.path)}=${JSON.stringify(n)} but the ${e} header is absent`);let s=cz(r);if(void 0===s)return cM("param-header-invalid-encoding",e,`the ${e} header carries an invalid Base64 sentinel value`);if(!(("integer"===i.type||"number"===i.type)&&cN.test(s)&&"number"==typeof n?Number(s)===n:s===o))return cM("param-header-mismatch",e,`the ${e} header decodes to ${JSON.stringify(s)} but the body carries ${cI(i.path)}=${JSON.stringify(n)}`)}}(t.declarations,e?.arguments,i.headers);if(void 0!==r)return b.close().catch(d),d(Error(`Rejected inbound request (${r.cell}): ${r.message}`)),uS(r,a.message.id)}}}o(x,f),c(x,sE),void 0!==g&&(m={clientInfo:g[r$],clientCapabilities:y},s(x,m));let _=x.onclose;p.add(x),x.onclose=()=>{p.delete(x),_?.()};try{let e=await ub(b,a.message,{classification:a.classification,request:i,...void 0!==r&&{authInfo:r},...void 0!==n&&{responseMode:n},...void 0!==t.keepAliveMs&&{keepAliveMs:t.keepAliveMs}});return"notification"===a.messageKind&&queueMicrotask(()=>void x.close().catch(()=>{})),e}catch(e){if(e instanceof sw&&e.code===s_.ConnectionClosed)return new Response(null,{status:499});return await x.close().catch(()=>{}),p.delete(x),d(uk(e)),u$(u_(a.message))}}async function y(e,t,a,i){if(void 0!==v)return v(t,{...void 0!==a&&{authInfo:a},...void 0!==i&&{parsedBody:i}});let r=function(e,t){switch(e.reason){case"http-method":return cF("http-method","modern-only-method-not-allowed",405,new s2(-32e3,"Method not allowed."),!0);case"batch":return cF("jsonrpc-shape","modern-only-batch-not-supported",400,new s2(s1.InvalidRequest,"Bad Request: JSON-RPC batches are not supported by this endpoint"),!0);case"response":return cF("jsonrpc-shape","modern-only-response-post",400,new s2(s1.InvalidRequest,"Bad Request: JSON-RPC responses cannot be posted to this endpoint"),!0);case"notification":return;case"initialize":case"no-claim":{let a=e.requestedVersion;return cF("era-classification","modern-only-missing-envelope",400,void 0===a?new s2(s1.UnsupportedProtocolVersion,"Unsupported protocol version: the request did not name a protocol version",{supported:[...t]}):new s9({supported:[...t],requested:a}),!0)}}}(e,sE);return void 0===r?new Response(null,{status:202}):(d(Error(`Rejected 2025-era request on a modern-only endpoint (${r.cell}): ${r.message}`)),uS(r,u_(i)))}async function b(e,t){let a=t?.authInfo;if("POST"===e.method.toUpperCase()&&!lp(e.headers.get("content-type")))return d(Error("Unsupported Media Type: Content-Type must be application/json")),uw(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let i=await uj(e,t?.parsedBody);if("unreadable-body"===i.step)return uw(400,-32700,"Parse error: the request body could not be read");if("no-json-body"===i.step)return void 0!==v?v(i.forwardRequest,{...void 0!==a&&{authInfo:a}}):uw(400,-32700,"Parse error: the request body is not valid JSON");let{outcome:r,body:n,parsedBody:o,forwardRequest:s}=i;try{switch(r.kind){case"reject":return d(Error(`Rejected inbound request (${r.cell}): ${r.message}`)),uS(r,u_(n));case"modern":return await g(r,e,a);case"legacy":return await y(r,s,a,o)}}catch(e){return d(uk(e)),u$(u_(n))}}return{fetch:async(e,t)=>{if(u)throw Error("This MCP handler has been closed");try{return await b(e,t)}catch(e){return d(uk(e)),u$(u_(t?.parsedBody))}},notify:f,bus:m,close:async()=>{u=!0,h.closeAll();let e=[...p].map(e=>e.close().catch(()=>{}));p.clear(),await Promise.all(e)}}}(()=>this.createServerFn(),{legacy:"stateless",onerror:e=>this.log("MCP handler error:",e)}),this.nodeMcpHandler=(r=this.mcpHandler,n={onerror:e=>console.error("[HTTP-server] Error handling MCP request:",e)},async(e,t,a)=>{let i,o;"function"==typeof a&&(a=void 0);let s=!1,c=new AbortController;t.on("close",()=>{s||c.abort()}),!0===t.destroyed&&c.abort();try{let t=await f$(e,a,{signal:c.signal});i=await r.fetch(t,{...void 0!==e.auth&&{authInfo:e.auth},...void 0!==a&&{parsedBody:a}})}catch(e){var l;try{n?.onerror?.(e instanceof Error?e:Error(String(e)))}catch{}l=function(e){if(null===e||"object"!=typeof e||Array.isArray(e))return null;let{method:t,id:a}=e;return"string"!=typeof t?null:"string"==typeof a||"number"==typeof a?a:null}(a),i=Response.json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:l},{status:500})}let p={};for(let[e,t]of i.headers)p[e]=t;if(t.writeHead(i.status,p),null===i.body){s=!0,t.end();return}t.on("drain",()=>{o?.(),o=void 0});let u=new Promise(e=>{c.signal.addEventListener("abort",()=>e(),{once:!0})});try{for await(let e of i.body){if(c.signal.aborted)break;!1===t.write(e)&&await Promise.race([new Promise(e=>{o=e}),u])}}catch{}s=!0,t.end()}),this.app.use(fE().json({limit:this.options.bodySizeLimit||"10mb"})),this.setupInitialRoutes(),this.setupInitialMiddleware(),this.setupProviders(),this.setupEndpointRoute()}}function fL(e){return"function"==typeof e}function fD(e){var t;return"object"==typeof e&&null!==e&&"middleware"in e&&"router"in e&&"function"==typeof e.middleware&&"function"==typeof(t=e.router)&&null!==t&&"function"==typeof t.use&&"function"==typeof t.get&&"function"==typeof t.post&&"function"==typeof t.route}let fF=mn({name:"http-transport-context"});fF.setContext,fF.getContext;let fU=fF.provider;var fH=a(8583);a.n(fH)().config();let fV=HTTP_CONFIG,fZ=HTTP_CORS_CONFIG,fB=TEMPLATE_CONFIG,fJ=INJECTED_MIDDLEWARE;async function fG(){let e={port:fV?.port,host:fV?.host,debug:fV?.debug,bodySizeLimit:fV?.bodySizeLimit?.toString(),endpoint:fV?.endpoint,template:fB},t={origin:fZ.origin,methods:fZ.methods,allowedHeaders:fZ.allowedHeaders,exposedHeaders:fZ.exposedHeaders,credentials:fZ.credentials,maxAge:fZ.maxAge},a=[];if(fJ){let e=await fJ();e&&e.default&&(a=function(e){let t=[];if(Array.isArray(e))for(let a of e)fL(a)?t.push({middleware:a}):fD(a)&&t.push({middleware:a.middleware,router:a.router});else fL(e)?t.push({middleware:e}):fD(e)&&t.push({middleware:e.middleware,router:e.router});return t}(e.default))}return fU({config:{http:fV}},async()=>new fM(fi,e,t,a))}!async function(){let e=await fG();await e.start()}()})(),{}})());