xmcp 1.10.2 → 1.10.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client.js +1 -1
- package/dist/index.js +1 -1
- package/dist/runtime/adapter-express.js +15 -15
- package/dist/runtime/adapter-fastify.js +15 -15
- package/dist/runtime/adapter-nestjs.js +22 -22
- package/dist/runtime/http.js +9 -9
- package/dist/runtime/vercel.js +10 -10
- package/package.json +1 -1
package/dist/runtime/http.js
CHANGED
|
@@ -233,7 +233,7 @@ Expected ReadResourceResult format:
|
|
|
233
233
|
{ uri: "resource://uri", mimeType: "application/json", text: "json content" },
|
|
234
234
|
{ uri: "resource://uri", blob: base64data }
|
|
235
235
|
]
|
|
236
|
-
}`)}return n.contents.forEach(e=>{e.uri||(e.uri=t.href)}),n}}(i,r,c);if("direct"===p.type)l?.(a.name,u),e.registerResource(a.name,u,mn(a),d);else{let t=Object.create(null);for(let e of p.parameters)s&&Object.hasOwn(s,e)&&(t[e]=s[e]);let r=new dB(u,{list:void 0,complete:t});l?.(a.name,r),e.registerResource(a.name,r,mn(a),async(e,t,r)=>{let a={};for(let e of p.parameters){let r=t[e],i=c[e];if(void 0===r)throw Error(`Missing required parameter: ${e}. Available variables: ${Object.keys(t)}`);i?a[e]=i.parse(r):a[e]=r}let n=i(a,r);return n instanceof Promise&&(n=await n),"string"==typeof n?{contents:[{uri:e.href,text:n}]}:n})}}),function(e,t,r,a){let i=[...hw(new Map(t.map(e=>[e.uri,{metadata:{name:e.frontmatter.name},skill:e}])),r).values()].map(({skill:e})=>e);if(0===i.length)return;for(let{frontmatter:t,files:r}of i){let i=r[0].uri.slice(0,r[0].uri.lastIndexOf("/")+1);r.forEach(({uri:r,mimeType:n,text:o,blob:s},c)=>{let l=0===c?{mimeType:n,description:t.description}:{mimeType:n},p=0===c?t.name:`${t.name}/${decodeURIComponent(r.slice(i.length))}`,u=void 0!==o?{uri:r,mimeType:n,text:o}:{uri:r,mimeType:n,blob:s??""};a?.(p,r),e.registerResource(p,r,l,()=>({contents:[u]}))})}let n=i.map(hT),o=new Map(n.map(e=>[e.uri,e]));e.server.registerCapabilities({extensions:{"io.modelcontextprotocol/skills":{}}}),e.server.setRequestHandler("skills/list",{params:hO},e=>{let t=e?.cursor===void 0?0:function(e,t){let r=0/0;try{r=Number(atob(e))}catch{}if(!Number.isSafeInteger(r)||r<=0||r>=t)throw new lS(lw.InvalidParams,`Invalid cursor: ${e}`);return r}(e.cursor,n.length),r=t+50;return{skills:n.slice(t,r),...r<n.length?{nextCursor:btoa(String(r))}:{},...hR}}),e.server.setRequestHandler("skills/get",{params:hP},({uri:e})=>{let t=o.get(e);if(!t)throw new lS(lw.InvalidParams,`No skill is served at ${e}`);return{skill:t,...hR}})}(e,hM,c,s?.registerResource)}),e}(a,s,c,l)}let hD=require("node:crypto"),hU=require("http");var hH=r.n(hU);require("http2");var hZ=r(2203),hV=r(6982),hB=global.Request,hJ=class extends hB{constructor(e,t){"object"==typeof e&&hK in e&&(e=e[hK]()),void 0!==t?.body?.getReader&&(t.duplex??="half"),super(e,t)}},hG=Symbol("wrapBodyStream"),hK=Symbol("getRequestCache"),hW=Symbol("requestCache"),hY=Symbol("incomingKey"),hX=Symbol("urlKey"),hQ=Symbol("headersKey"),h0=Symbol("abortControllerKey"),h1=Symbol("getAbortController"),h2={get method(){return this[hY].method||"GET"},get url(){return this[hX]},get headers(){return this[hQ]||=(e=>{let t=[],r=e.rawHeaders;for(let e=0;e<r.length;e+=2){let{[e]:a,[e+1]:i}=r;58!==a.charCodeAt(0)&&t.push([a,i])}return new Headers(t)})(this[hY])},[h1](){return this[hK](),this[h0]},[hK](){return this[h0]||=new AbortController,this[hW]||=((e,t,r,a,i)=>{let n={method:e,headers:r,signal:i.signal};if("TRACE"===e){n.method="GET";let e=new hJ(t,n);return Object.defineProperty(e,"method",{get:()=>"TRACE"}),e}if("GET"!==e&&"HEAD"!==e)if("rawBody"in a&&a.rawBody instanceof Buffer)n.body=new ReadableStream({start(e){e.enqueue(a.rawBody),e.close()}});else if(a[hG]){let e;n.body=new ReadableStream({async pull(t){try{e||=hZ.Readable.toWeb(a).getReader();let{done:r,value:i}=await e.read();r?t.close():t.enqueue(i)}catch(e){t.error(e)}}})}else n.body=hZ.Readable.toWeb(a);return new hJ(t,n)})(this.method,this[hX],this.headers,this[hY],this[h0])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(e=>{Object.defineProperty(h2,e,{get(){return this[hK]()[e]}})}),["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(h2,e,{value:function(){return this[hK]()[e]()}})}),Object.defineProperty(h2,Symbol.for("nodejs.util.inspect.custom"),{value:function(e,t,r){let a={method:this.method,url:this.url,headers:this.headers,nativeRequest:this[hW]};return`Request (lightweight) ${r(a,{...t,depth:null==e?null:e-1})}`}}),Object.setPrototypeOf(h2,hJ.prototype);var h4=Symbol("responseCache"),h8=Symbol("getResponseCache"),h9=Symbol("cache"),h5=global.Response,h6=class e{#e;#t;[h8](){return delete this[h9],this[h4]||=new h5(this.#e,this.#t)}constructor(t,r){let a;if(this.#e=t,r instanceof e){let e=r[h4];if(e){this.#t=e,this[h8]();return}this.#t=r.#t,a=new Headers(r.#t.headers)}else this.#t=r;("string"==typeof t||void 0!==t?.getReader||t instanceof Blob||t instanceof Uint8Array)&&(this[h9]=[r?.status||200,t,a||r?.headers])}get headers(){let e=this[h9];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":"text/plain; charset=UTF-8"})),e[2]):this[h8]().headers}get status(){return this[h9]?.[0]??this[h8]().status}get ok(){let e=this.status;return e>=200&&e<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(e=>{Object.defineProperty(h6.prototype,e,{get(){return this[h8]()[e]}})}),["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(h6.prototype,e,{value:function(){return this[h8]()[e]()}})}),Object.defineProperty(h6.prototype,Symbol.for("nodejs.util.inspect.custom"),{value:function(e,t,r){let a={status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[h4]};return`Response (lightweight) ${r(a,{...t,depth:null==e?null:e-1})}`}}),Object.setPrototypeOf(h6,h5),Object.setPrototypeOf(h6.prototype,h5.prototype),void 0===global.crypto&&(global.crypto=hV),Symbol("outgoingEnded"),Symbol("incomingDraining");var h3=class extends Error{status=413;constructor(e){super(`Payload Too Large: Request body must not exceed ${e} bytes`),this.name="RequestBodyTooLargeError"}};function h7(e){if(void 0===e)return 4194304;if("number"!=typeof e||!Number.isFinite(e)||e<=0)throw RangeError(`maxRequestBodySize must be a positive number of bytes, got ${String(e)}`);return e}function ge(e){return Array.isArray(e)?e[0]:e}var gt=r(7416),gr=r.n(gt);let ga=require("net");var gi=r.n(ga);function gn(e){return`\x1b[33m${e}\x1b[39m`}let go="This MCP server was bootstrapped with xmcp.",gs={cursor:`
|
|
236
|
+
}`)}return n.contents.forEach(e=>{e.uri||(e.uri=t.href)}),n}}(i,r,c);if("direct"===p.type)l?.(a.name,u),e.registerResource(a.name,u,mn(a),d);else{let t=Object.create(null);for(let e of p.parameters)s&&Object.hasOwn(s,e)&&(t[e]=s[e]);let r=new dB(u,{list:void 0,complete:t});l?.(a.name,r),e.registerResource(a.name,r,mn(a),async(e,t,r)=>{let a={};for(let e of p.parameters){let r=t[e],i=c[e];if(void 0===r)throw Error(`Missing required parameter: ${e}. Available variables: ${Object.keys(t)}`);i?a[e]=i.parse(r):a[e]=r}let n=i(a,r);return n instanceof Promise&&(n=await n),"string"==typeof n?{contents:[{uri:e.href,text:n}]}:n})}}),function(e,t,r,a){let i=[...hw(new Map(t.map(e=>[e.uri,{metadata:{name:e.frontmatter.name},skill:e}])),r).values()].map(({skill:e})=>e);if(0===i.length)return;for(let{frontmatter:t,files:r}of i){let i=r[0].uri.slice(0,r[0].uri.lastIndexOf("/")+1);r.forEach(({uri:r,mimeType:n,text:o,blob:s},c)=>{let l=0===c?{mimeType:n,description:t.description}:{mimeType:n},p=0===c?t.name:`${t.name}/${decodeURIComponent(r.slice(i.length))}`,u=void 0!==o?{uri:r,mimeType:n,text:o}:{uri:r,mimeType:n,blob:s??""};a?.(p,r),e.registerResource(p,r,l,()=>({contents:[u]}))})}let n=i.map(hT),o=new Map(n.map(e=>[e.uri,e]));e.server.registerCapabilities({extensions:{"io.modelcontextprotocol/skills":{}}}),e.server.setRequestHandler("skills/list",{params:hO},e=>{let t=e?.cursor===void 0?0:function(e,t){let r=0/0;try{r=Number(atob(e))}catch{}if(!Number.isSafeInteger(r)||r<=0||r>=t)throw new lS(lw.InvalidParams,`Invalid cursor: ${e}`);return r}(e.cursor,n.length),r=t+50;return{skills:n.slice(t,r),...r<n.length?{nextCursor:btoa(String(r))}:{},...hR}}),e.server.setRequestHandler("skills/get",{params:hP},({uri:e})=>{let t=o.get(e);if(!t)throw new lS(lw.InvalidParams,`No skill is served at ${e}`);return{skill:t,...hR}})}(e,hM,c,s?.registerResource)}),e}(a,s,c,l)}let hD=require("node:crypto");r(7067);let hU=require("node:http2"),hH=require("node:stream"),hZ=new Set(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","server","user-agent"]),hV=/^[!#$%&'*+\-.^_`|~\dA-Za-z]+$/,hB=e=>9===e||10===e||13===e||32===e,hJ=e=>{if(!hB(e.charCodeAt(0))&&!hB(e.charCodeAt(e.length-1)))return e;let t=0,r=e.length;for(;t<r&&hB(e.charCodeAt(t));)t++;for(;r>t&&hB(e.charCodeAt(r-1));)r--;return e.slice(t,r)},hG=/[\0\r\n]/,hK=globalThis.Headers,hW=(e,t=hK)=>{let r=new t;for(let t=0;t<e.length;t+=2){let a=e[t];a.startsWith(":")||r.append(a,e[t+1])}return r};var hY=class{#e;#t;#r;#a;constructor(e){this.#e=e,e instanceof hU.Http2ServerRequest&&(this.#t=e.rawHeaders.slice())}get #i(){return this.#t??=this.#e.rawHeaders.slice()}get #n(){return this.#r||(this.#r=hW(this.#i),this.#t=void 0),this.#r}#o(e){if("string"==typeof e){if(!hV.test(e))throw TypeError(`Invalid header name: ${e}`);return e.toLowerCase()}}#s(e){let t=this.#e instanceof hU.Http2ServerRequest?void 0:this.#e.headers;if(!t||hZ.has(e)||"set-cookie"===e||"__proto__"===e)return;if(!Object.hasOwn(t,e))return null;let r=t[e];if("string"==typeof r){let e=hJ(r);return hG.test(e)?void 0:e}}#c(e,t){let r="cookie"===t?"; ":", ",a=null;for(let i=0;i<e.length;i+=2){let n=e[i];if(n.length===t.length&&n.toLowerCase()===t){let t=hJ(e[i+1]);if(hG.test(t)){this.#a=!0;return}a=null===a?t:a+r+t}}return a}append(e,t){this.#n.append(e,t)}delete(e){this.#n.delete(e)}get(e){let t=this.#o(e);if(t&&!this.#r&&!this.#a){let e=this.#s(t);if(void 0!==e)return e;let r=this.#c(this.#i,t);if(void 0!==r)return r}return this.#n.get(e)}has(e){let t=this.#o(e);if(t&&!this.#r&&!this.#a){let e=this.#s(t);if(void 0!==e)return null!==e;let r=this.#c(this.#i,t);if(void 0!==r)return null!==r}return this.#n.has(e)}set(e,t){this.#n.set(e,t)}getSetCookie(){return this.#n.getSetCookie()}keys(){return this.#n.keys()}values(){return this.#n.values()}entries(){return this.#n.entries()}forEach(e,t){this.#n.forEach((r,a)=>{e.call(t,r,a,this)})}[Symbol.iterator](){return this.entries()}};Object.defineProperty(hY.prototype,Symbol.for("nodejs.util.inspect.custom"),{value:function(e,t,r){return`Headers (lightweight) ${r(Object.fromEntries(this),{...t,depth:null==e?null:e-1})}`}}),Object.setPrototypeOf(hY.prototype,hK.prototype);let hX=e=>globalThis.Headers===hK?new hY(e):hW(e.rawHeaders,globalThis.Headers),hQ=global.Request;var h0=class extends hQ{constructor(e,t){if("object"==typeof e&&h7 in e){let r=void 0!==t&&"body"in t&&null!=t.body;if(e[gp]&&!r)throw TypeError("Cannot construct a Request with a Request object that has already been used.");e=e[h7]()}void 0!==t?.body?.getReader&&(t.duplex??="half"),super(e,t)}};let h1=Symbol("wrapBodyStream"),h2=new Set(["latin1","binary","hex","base64","base64url"]),h4=Symbol("bodyBufferedBeforeDisconnect"),h8=Symbol("bodyBufferedLengthBeforeDisconnect"),h9=(e,t)=>Buffer.isBuffer(e)?e:Buffer.from(e,t??"utf8"),h5=e=>{let t;return!(e instanceof hU.Http2ServerRequest)&&!!e.complete&&!!e.readableAborted&&"function"==typeof e.read&&(null===(t=e.readableEncoding)||h2.has(t))},h6=(e,t)=>{let r;if(e.readableDidRead&&!t||!h5(e))return;if(void 0!==e[h4])return e[h4];let a=e.errored;if(a&&"ECONNRESET"!==a.code)r=a;else if(void 0!==e[h8]&&e.readableLength!==e[h8])r=gm();else{let a=t??[],i=e.read();null!==i&&a.push(h9(i,e.readableEncoding));let n=1===a.length?a[0]:Buffer.concat(a);r=n;let o=e.headers["content-length"];if("string"==typeof o&&/^\d+$/.test(o)){let e=Number(o);Number.isSafeInteger(e)&&n.length!==e&&(r=gm())}}return e[h4]=r,r},h3=(e,t)=>{t instanceof Error?e.error(t):(t.length>0&&e.enqueue(t),e.close())},h7=Symbol("getRequestCache"),ge=Symbol("requestCache"),gt=Symbol("incomingKey"),gr=Symbol("urlKey"),ga=Symbol("methodKey"),gi=Symbol("headersKey"),gn=Symbol("abortControllerKey"),go=Symbol("getAbortController"),gs=Symbol("abortRequest"),gc=Symbol("bodyBuffer"),gl=Symbol("bodyReadPromise"),gp=Symbol("bodyConsumedDirectly"),gu=Symbol("bodyLockReader"),gd=Symbol("abortReason"),gm=()=>TypeError("Body is unusable"),gf=new TextDecoder,gh=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,gg=(e,t,r)=>{if(e[gp])return Promise.reject(gm());let a=e.method;if("GET"===a||"HEAD"===a)return e[h7]()[t]();let i=(e=>{if(!gh.test(e))return TypeError(`'${e}' is not a valid HTTP method.`);let t=e.toUpperCase();if("CONNECT"===t||"TRACK"===t||"TRACE"===t&&"TRACE"!==e)return TypeError(`'${e}' HTTP method is unsupported.`)})(a);if(i)return Promise.reject(i);if(e[ge]&&"TRACE"!==a)return e[ge][t]();let n=(e=>{if(e[gp])return Promise.reject(gm());e[gp]=!0})(e);if(n)return n;let o=gv(e);if(o){let t=Promise.resolve(r(o,e));return e[gc]=void 0,t}return gb(e).then(t=>{let a=r(t,e);return e[gc]=void 0,a})},gv=e=>{let t=e[gt];if("rawBody"in t&&t.rawBody instanceof Buffer)return t.rawBody},gy=(e,t)=>{if(t.errored)return t.errored;let r=e[gd];return void 0!==r?r instanceof Error?r:Error(String(r)):Error("Client connection prematurely closed.")},gb=e=>{if(e[gc])return Promise.resolve(e[gc]);if(e[gl])return e[gl];let t=e[gt];if(t.readableDidRead)return Promise.reject(gm());let r=h6(t);if(void 0!==r)return r instanceof Error?Promise.reject(r):(e[gc]=r,Promise.resolve(r));let a=new Promise((r,a)=>{let i=[],n=!1,o=e=>{n||(n=!0,d(),e())},s=n=>{let s=t.errored??n;return!!h5(t)&&(!s||"ECONNRESET"===s.code)&&(o(()=>{let o=h6(t,i);o instanceof Error?a(o):void 0===o?a(n??gy(e,t)):(e[gc]=o,r(o))}),!0)},c=e=>{i.push(h9(e,t.readableEncoding))},l=()=>{o(()=>{let t=1===i.length?i[0]:Buffer.concat(i);e[gc]=t,r(t)})},p=e=>{s(e)||o(()=>{a(e)})},u=()=>{t.readableEnded?l():s()||o(()=>{a(gy(e,t))})},d=()=>{t.off("data",c),t.off("end",l),t.off("error",p),t.off("close",u),e[gl]=void 0};t.on("data",c),t.on("end",l),t.on("error",p),t.on("close",u),queueMicrotask(()=>{!n&&(t.readableEnded?l():t.errored?p(t.errored):t.destroyed&&u())})});return e[gl]=a,a},gx={get method(){return this[ga]},get url(){return this[gr]},get headers(){return this[gi]||=hX(this[gt])},[gs](e){void 0===this[gd]&&(this[gd]=e);let t=this[gn];t&&!t.signal.aborted&&t.abort(e)},[go](){return this[gn]||=new AbortController,void 0===this[gd]||this[gn].signal.aborted||this[gn].abort(this[gd]),this[gn]},[h7](){let e=this[go]();if(this[ge])return this[ge];let t=this.method;if(this[gp]&&"GET"!==t&&"HEAD"!==t){this[gc]=void 0;let r={method:"TRACE"===t?"GET":t,headers:this.headers,signal:e.signal};"TRACE"!==t&&(r.body=new ReadableStream({start(e){e.close()}}),r.duplex="half");let a=new h0(this[gr],r);return"TRACE"===t&&Object.defineProperty(a,"method",{get:()=>"TRACE"}),this[ge]=a}return this[ge]=((e,t,r,a,i)=>{let n={method:e,headers:r,signal:i.signal};if("TRACE"===e){n.method="GET";let e=new h0(t,n);return Object.defineProperty(e,"method",{get:()=>"TRACE"}),e}if("GET"!==e&&"HEAD"!==e)if("rawBody"in a&&a.rawBody instanceof Buffer)n.body=new ReadableStream({start(e){e.enqueue(a.rawBody),e.close()}});else if(a[h1]){let e;n.body=new ReadableStream({async pull(t){try{if(!e){let e=h6(a);if(void 0!==e)return void h3(t,e)}e||=hH.Readable.toWeb(a).getReader();let{done:r,value:i}=await e.read();r?t.close():t.enqueue(i)}catch(e){t.error(e)}}})}else{let e=h6(a);void 0!==e?n.body=new ReadableStream({start(t){h3(t,e)}}):n.body=hH.Readable.toWeb(a)}return new h0(t,n)})(this.method,this[gr],this.headers,this[gt],e)},get body(){if(!this[gp])return this[h7]().body;let e=this[h7]();return!this[gu]&&e.body&&(this[gu]=e.body.getReader()),e.body},get bodyUsed(){return!!this[gp]||!!this[ge]&&this[ge].bodyUsed}};Object.defineProperty(gx,"signal",{get(){return this[go]().signal}}),["cache","credentials","destination","duplex","integrity","mode","redirect","referrer","referrerPolicy","keepalive"].forEach(e=>{Object.defineProperty(gx,e,{get(){return this[h7]()[e]}})}),["clone","formData"].forEach(e=>{Object.defineProperty(gx,e,{value:function(){if(this[gp]){if("clone"===e)throw gm();return Promise.reject(gm())}return this[h7]()[e]()}})}),Object.defineProperty(gx,"text",{value:function(){return gg(this,"text",e=>gf.decode(e))}}),Object.defineProperty(gx,"arrayBuffer",{value:function(){return gg(this,"arrayBuffer",e=>e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength))}}),Object.defineProperty(gx,"blob",{value:function(){return gg(this,"blob",(e,t)=>{let r=(t[gi]||=hX(t[gt])).get("content-type")||"";return new Response(e,r?{headers:{"content-type":r}}:void 0).blob()})}}),Object.defineProperty(gx,"json",{value:function(){return this[gp]?Promise.reject(gm()):this.text().then(JSON.parse)}}),Object.defineProperty(gx,Symbol.for("nodejs.util.inspect.custom"),{value:function(e,t,r){return`Request (lightweight) ${r({method:this.method,url:this.url,headers:this.headers,nativeRequest:this[ge]},{...t,depth:null==e?null:e-1})}`}}),Object.setPrototypeOf(gx,h0.prototype);let g_=Symbol("responseCache"),gw=Symbol("getResponseCache"),gS=Symbol("cache"),gk=global.Response;var g$=class e{#l;#p;[gw](){let e=this[gS],t=e&&e[2]instanceof Headers?e[2]:void 0;return delete this[gS],this[g_]||=new gk(this.#l,t?{status:this.#p?.status,statusText:this.#p?.statusText,headers:t}:this.#p)}constructor(t,r){let a;if(this.#l=t,r instanceof gk){let t=r[g_];if(t){this.#p=t,this[gw]();return}this.#p=r instanceof e?r.#p:r,a=new Headers(r.headers)}else this.#p=r;(null==t||"string"==typeof t||void 0!==t?.getReader||t instanceof Blob||t instanceof Uint8Array)&&(this[gS]=[r?.status||200,t??null,a||r?.headers])}get headers(){let e=this[gS];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||(null===e[1]?void 0:{"content-type":"text/plain; charset=UTF-8"}))),e[2]):this[gw]().headers}get status(){return this[gS]?.[0]??this[gw]().status}get ok(){let e=this.status;return e>=200&&e<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(e=>{Object.defineProperty(g$.prototype,e,{get(){return this[gw]()[e]}})}),["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(g$.prototype,e,{value:function(){return this[gw]()[e]()}})}),Object.defineProperty(g$.prototype,Symbol.for("nodejs.util.inspect.custom"),{value:function(e,t,r){return`Response (lightweight) ${r({status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[g_]},{...t,depth:null==e?null:e-1})}`}}),Object.setPrototypeOf(g$,gk),Object.setPrototypeOf(g$.prototype,gk.prototype);let gj=/^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/,gC=new Set([301,302,303,307,308]);Object.defineProperty(g$,"redirect",{value:function(e,t=302){if(!gC.has(t))throw RangeError("Invalid status code");return new g$(null,{status:t,headers:{location:e instanceof URL?e.href:gj.test(e)?e:new URL(e).href}})},writable:!0,configurable:!0}),Object.defineProperty(g$,"json",{value:function(e,t){let r,a=JSON.stringify(e);if(void 0===a)throw TypeError("The data is not JSON serializable");let i=t?.headers;return i?(r=new Headers(i)).has("content-type")||r.set("content-type","application/json"):r={"content-type":"application/json"},new g$(a,{status:t?.status??200,statusText:t?.statusText,headers:r})},writable:!0,configurable:!0}),Symbol("outgoingEnded"),Symbol("incomingDraining"),globalThis.CloseEvent??Event,globalThis.ErrorEvent??Event,Symbol("CONNECTION_SYMBOL_KEY"),Symbol("WAIT_FOR_WEBSOCKET_SYMBOL");var gE=class extends Error{status=413;constructor(e){super(`Payload Too Large: Request body must not exceed ${e} bytes`),this.name="RequestBodyTooLargeError"}};function gR(e){if(void 0===e)return 4194304;if("number"!=typeof e||!Number.isFinite(e)||e<=0)throw RangeError(`maxRequestBodySize must be a positive number of bytes, got ${String(e)}`);return e}function gO(e){return Array.isArray(e)?e[0]:e}var gP=r(7416),gT=r.n(gP);let gA=require("http");var gI=r.n(gA);let gq=require("net");var gN=r.n(gq);function gz(e){return`\x1b[33m${e}\x1b[39m`}let gM="This MCP server was bootstrapped with xmcp.",gL={cursor:`
|
|
237
237
|
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
|
|
238
238
|
<g clip-path="url(#cursor)">
|
|
239
239
|
<path d="M18.1937 4.73376L10.1872 0.111231C9.93007 -0.0372398 9.61283 -0.0372398 9.35573 0.111231L1.34956 4.73376C1.13344 4.85855 1 5.08934 1 5.33929V14.6606C1 14.9106 1.13344 15.1414 1.34956 15.2662L9.3561 19.8887C9.6132 20.0372 9.93044 20.0372 10.1875 19.8887L18.1941 15.2662C18.4102 15.1414 18.5436 14.9106 18.5436 14.6606V5.33929C18.5436 5.08934 18.4102 4.85855 18.1941 4.73376H18.1937ZM17.6908 5.71291L9.96164 19.1001C9.90939 19.1903 9.77145 19.1535 9.77145 19.049V10.2832C9.77145 10.108 9.67785 9.94603 9.526 9.85808L1.9348 5.47536C1.84459 5.42311 1.88143 5.28517 1.98592 5.28517H17.4442C17.6637 5.28517 17.8009 5.5231 17.6912 5.71329H17.6908V5.71291Z" fill="currentColor" />
|
|
@@ -288,7 +288,7 @@ Expected ReadResourceResult format:
|
|
|
288
288
|
</clipPath>
|
|
289
289
|
</defs>
|
|
290
290
|
</svg>
|
|
291
|
-
`},
|
|
291
|
+
`},gF=String.raw`
|
|
292
292
|
:root {
|
|
293
293
|
color-scheme: dark;
|
|
294
294
|
--brand-white: #f7f7f7;
|
|
@@ -587,7 +587,7 @@ Expected ReadResourceResult format:
|
|
|
587
587
|
clip: rect(0, 0, 0, 0);
|
|
588
588
|
border: 0;
|
|
589
589
|
}
|
|
590
|
-
`,
|
|
590
|
+
`,gD={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 gU(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class gH{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,r,a)=>{let i=t.headers.origin;for(let[t,a]of Object.entries(function(e,t){let r={};if(void 0!==e.origin){if(!0===e.origin)t&&(r["Access-Control-Allow-Origin"]=t);else if(!1!==e.origin)if(Array.isArray(e.origin)){let a=t&&e.origin.includes(t)?t:e.origin[0]||"*";r["Access-Control-Allow-Origin"]=a}else r["Access-Control-Allow-Origin"]=String(e.origin)}return void 0!==e.methods&&(r["Access-Control-Allow-Methods"]=Array.isArray(e.methods)?e.methods.join(","):String(e.methods)),void 0!==e.allowedHeaders&&(r["Access-Control-Allow-Headers"]=Array.isArray(e.allowedHeaders)?e.allowedHeaders.join(","):String(e.allowedHeaders)),void 0!==e.exposedHeaders&&(r["Access-Control-Expose-Headers"]=Array.isArray(e.exposedHeaders)?e.exposedHeaders.join(","):String(e.exposedHeaders)),"boolean"==typeof e.credentials&&(r["Access-Control-Allow-Credentials"]=String(e.credentials)),"number"==typeof e.maxAge&&(r["Access-Control-Max-Age"]=String(e.maxAge)),r}(e,i)))r.setHeader(t,a);"OPTIONS"===t.method?r.status(204).end():a()})),this.app.use((e,t,r)=>{this.log(`${e.method} ${e.path}`),r()})}setupInitialRoutes(){this.app.get("/health",(e,t)=>{t.status(200).json({status:"ok",transport:"streamable-http",mode:"stateless"})}),this.app.get("/",(e,t)=>{var r,a,i;let n=this.options.template?.homePage;n?t.send(n):t.send((r=this.endpoint,a=this.options.template?.name,i=this.options.template?.description,`
|
|
591
591
|
<!DOCTYPE html>
|
|
592
592
|
<html lang="en">
|
|
593
593
|
<head>
|
|
@@ -608,7 +608,7 @@ Expected ReadResourceResult format:
|
|
|
608
608
|
rel="stylesheet"
|
|
609
609
|
/>
|
|
610
610
|
<style>
|
|
611
|
-
${
|
|
611
|
+
${gF}
|
|
612
612
|
</style>
|
|
613
613
|
</head>
|
|
614
614
|
<body>
|
|
@@ -618,7 +618,7 @@ ${gc}
|
|
|
618
618
|
<div class="section-header">
|
|
619
619
|
<h2 id="server-name" class="display text-gradient">xmcp server</h2>
|
|
620
620
|
<p id="server-description" class="lead">
|
|
621
|
-
${i||
|
|
621
|
+
${i||gM}
|
|
622
622
|
</p>
|
|
623
623
|
</div>
|
|
624
624
|
</div>
|
|
@@ -725,7 +725,7 @@ ${`
|
|
|
725
725
|
(templateConfig.serverName && templateConfig.serverName.trim()) || "xmcp server";
|
|
726
726
|
const resolvedDescription =
|
|
727
727
|
(templateConfig.serverDescription && templateConfig.serverDescription.trim()) ||
|
|
728
|
-
"${
|
|
728
|
+
"${gM}";
|
|
729
729
|
const endpointPath =
|
|
730
730
|
(templateConfig.endpoint && templateConfig.endpoint.trim()) || "/";
|
|
731
731
|
const normalizedEndpoint = endpointPath.startsWith("/")
|
|
@@ -747,7 +747,7 @@ ${`
|
|
|
747
747
|
elements.description.textContent = resolvedDescription;
|
|
748
748
|
}
|
|
749
749
|
|
|
750
|
-
const icons = ${JSON.stringify(
|
|
750
|
+
const icons = ${JSON.stringify(gL)};
|
|
751
751
|
|
|
752
752
|
const connectionOptions = [
|
|
753
753
|
{
|
|
@@ -950,10 +950,10 @@ args = ["-y", "mcp-remote", "$\{serverUrl}"]\`,
|
|
|
950
950
|
<\/script>
|
|
951
951
|
</body>
|
|
952
952
|
</html>
|
|
953
|
-
`))}),this.setupMcpServerCardRoute(),this.setupOpenAIAppsChallengeRoute(),this.app.use((e,t,r)=>{mp({id:(0,hD.randomUUID)(),headers:e.headers},()=>{r()})})}setupMcpServerCardRoute(){this.app.get("/.well-known/mcp/server-card.json",(e,t)=>{let r=e.get("host")??"localhost",a=r.replace(/:\d+$/,"").split(".").reverse().join("."),i=e.headers["x-forwarded-proto"]?.split(",")[0]?.trim()??e.protocol,n={$schema:"https://static.modelcontextprotocol.io/schemas/v1/server-card.schema.json",name:`${a}/mcp`,version:SERVER_INFO.version,description:this.options.template?.description,title:this.options.template?.name,remotes:[{type:"streamable-http",url:`${i}://${r}${this.endpoint}`}]};this.options.template?.icons?.length&&(n.icons=this.options.template.icons),t.setHeader("Content-Type","application/mcp-server-card+json").setHeader("Cache-Control","public, max-age=3600, must-revalidate").setHeader("Access-Control-Allow-Origin","*").json(n)})}setupOpenAIAppsChallengeRoute(){let e=process.env.OPENAI_APPS_VERIFICATION_TOKEN;if(!e){this.debug&&this.log("OpenAI Apps verification token not configured; skipping challenge route");return}this.app.get("/.well-known/openai-apps-challenge",(t,r)=>{r.status(200).set("Content-Type","text/plain").send(e)})}setupEndpointRoute(){this.app.use(this.endpoint,async(e,t)=>{this.log(`${e.method} ${e.path}`),this.extractAndStoreToolName(e),await this.handleStatelessRequest(e,t)})}extractAndStoreToolName(e){try{let t=function(e){if(e?.body===void 0||null===e.body)return[];let t=Array.isArray(e.body)?e.body:[e.body],r=[];for(let e of t)if("object"==typeof e&&null!==e&&"method"in e&&"tools/call"===e.method){let t=e.params;t&&"object"==typeof t&&"name"in t&&"string"==typeof t.name&&r.push(t.name)}return r}(e);t.length>0&&(0!==t.length&&(e.headers["x-mcp-tool-name"]=t[0],e.headers["x-mcp-tool-names"]=t.join(",")),global.__XMCP_CURRENT_TOOL_NAME=t[0])}catch(e){}}async handleStatelessRequest(e,t){let r=(e=>{for(let t of Array.isArray(e)?e:[e]){let e=mg(t);if(e)return e}})(e.body);t.on("finish",()=>{global.__XMCP_CURRENT_TOOL_NAME=void 0}),t.on("close",()=>{global.__XMCP_CURRENT_TOOL_NAME=void 0}),mc({clientInfo:r}),await this.nodeMcpHandler(e,t,e.body)}async start(){let e=this.options.host||"127.0.0.1",t=await async function e(t=3001,r="127.0.0.1"){return new Promise(a=>{let i;(i=
|
|
953
|
+
`))}),this.setupMcpServerCardRoute(),this.setupOpenAIAppsChallengeRoute(),this.app.use((e,t,r)=>{mp({id:(0,hD.randomUUID)(),headers:e.headers},()=>{r()})})}setupMcpServerCardRoute(){this.app.get("/.well-known/mcp/server-card.json",(e,t)=>{let r=e.get("host")??"localhost",a=r.replace(/:\d+$/,"").split(".").reverse().join("."),i=e.headers["x-forwarded-proto"]?.split(",")[0]?.trim()??e.protocol,n={$schema:"https://static.modelcontextprotocol.io/schemas/v1/server-card.schema.json",name:`${a}/mcp`,version:SERVER_INFO.version,description:this.options.template?.description,title:this.options.template?.name,remotes:[{type:"streamable-http",url:`${i}://${r}${this.endpoint}`}]};this.options.template?.icons?.length&&(n.icons=this.options.template.icons),t.setHeader("Content-Type","application/mcp-server-card+json").setHeader("Cache-Control","public, max-age=3600, must-revalidate").setHeader("Access-Control-Allow-Origin","*").json(n)})}setupOpenAIAppsChallengeRoute(){let e=process.env.OPENAI_APPS_VERIFICATION_TOKEN;if(!e){this.debug&&this.log("OpenAI Apps verification token not configured; skipping challenge route");return}this.app.get("/.well-known/openai-apps-challenge",(t,r)=>{r.status(200).set("Content-Type","text/plain").send(e)})}setupEndpointRoute(){this.app.use(this.endpoint,async(e,t)=>{this.log(`${e.method} ${e.path}`),this.extractAndStoreToolName(e),await this.handleStatelessRequest(e,t)})}extractAndStoreToolName(e){try{let t=function(e){if(e?.body===void 0||null===e.body)return[];let t=Array.isArray(e.body)?e.body:[e.body],r=[];for(let e of t)if("object"==typeof e&&null!==e&&"method"in e&&"tools/call"===e.method){let t=e.params;t&&"object"==typeof t&&"name"in t&&"string"==typeof t.name&&r.push(t.name)}return r}(e);t.length>0&&(0!==t.length&&(e.headers["x-mcp-tool-name"]=t[0],e.headers["x-mcp-tool-names"]=t.join(",")),global.__XMCP_CURRENT_TOOL_NAME=t[0])}catch(e){}}async handleStatelessRequest(e,t){let r=(e=>{for(let t of Array.isArray(e)?e:[e]){let e=mg(t);if(e)return e}})(e.body);t.on("finish",()=>{global.__XMCP_CURRENT_TOOL_NAME=void 0}),t.on("close",()=>{global.__XMCP_CURRENT_TOOL_NAME=void 0}),mc({clientInfo:r}),await this.nodeMcpHandler(e,t,e.body)}async start(){let e=this.options.host||"127.0.0.1",t=await async function e(t=3001,r="127.0.0.1"){return new Promise(a=>{let i;(i=gN().createServer(),new Promise((e,a)=>{i.once("error",t=>{"code"in t&&"EADDRINUSE"===t.code?e(!1):a(t)}),i.once("listening",()=>{i.close(),e(!0)}),i.listen(t,r)})).then(r=>{r?a(t):(console.log(`\x1b[1m\x1b[33m❯\x1b[39m\x1b[22m Port ${gz(String(t))} is in use, trying ${gz(String(t+1))} instead.`),e(t+1).then(a))})})}(this.port,e);this.server.listen(t,e,()=>{console.log(`\x1b[1m\x1b[32m✔\x1b[39m\x1b[22m MCP Server running on http://${e}:${t}${this.endpoint}`),this.setupShutdownHandlers()})}setupShutdownHandlers(){process.on("SIGINT",this.shutdown.bind(this)),process.on("SIGTERM",this.shutdown.bind(this))}shutdown(){this.log("Shutting down server"),this.mcpHandler.close(),this.server.close(),process.exit(0)}constructor(e,t={},r=gD,a){var i,n;let o;gU(this,"app",void 0),gU(this,"server",void 0),gU(this,"port",void 0),gU(this,"endpoint",void 0),gU(this,"debug",void 0),gU(this,"options",void 0),gU(this,"createServerFn",void 0),gU(this,"corsConfig",void 0),gU(this,"providers",void 0),gU(this,"mcpHandler",void 0),gU(this,"nodeMcpHandler",void 0),this.options={...t},this.app=gT()(),this.server=gI().createServer(this.app),this.port=t.port??parseInt(process.env.PORT||"3001",10),this.endpoint=t.endpoint??"/mcp",this.debug=t.debug??!1,this.createServerFn=e,this.corsConfig=r,this.providers=a,this.mcpHandler=function(e,t={}){var r;let{legacy:a,onerror:i,responseMode:n}=t,o=d9(t.maxRequestBodySize);if("function"==typeof a)throw TypeError("The 'legacy' option only accepts 'stateless' or 'reject', not a handler function. To serve 2025-era traffic with your own handler, route in user land with the exported isLegacyRequest(request) predicate in front of a strict (legacy: 'reject') handler.");let s=new Set,l=!1,m=e=>{try{i?.(e)}catch{}},f=t.bus??new d1(m),h={toolsChanged:()=>f.publish({kind:"tools_list_changed"}),promptsChanged:()=>f.publish({kind:"prompts_list_changed"}),resourcesChanged:()=>f.publish({kind:"resources_list_changed"}),resourceUpdated:e=>f.publish({kind:"resource_updated",uri:e})},g=function(e){let{bus:t,onerror:r}=e,a=e.maxSubscriptions??1024,i=e.keepAliveMs??15e3,n=new Set;return{serve:function(e,o,s,c){let l,p,u,d,m,f,h;if(n.size>=a)return r?.(Error(`subscriptions/listen refused: subscription limit reached (${a})`)),d2(e.id,-32603,"Subscription limit reached");let g=(m=lH(lU).validateRequest("subscriptions/listen",e)).ok?m.value.params?.notifications:void 0;if(void 0===g)return d2(e.id,-32602,"Invalid params: 'notifications' is required and must be a valid SubscriptionFilter");let v=(f={},h=e=>void 0===s||!0===e,!0===g.toolsListChanged&&h(s?.tools?.listChanged)&&(f.toolsListChanged=!0),!0===g.promptsListChanged&&h(s?.prompts?.listChanged)&&(f.promptsListChanged=!0),!0===g.resourcesListChanged&&h(s?.resources?.listChanged)&&(f.resourcesListChanged=!0),void 0!==g.resourceSubscriptions&&g.resourceSubscriptions.length>0&&h(s?.resources?.subscribe)&&(f.resourceSubscriptions=[...g.resourceSubscriptions]),f),y=e.id,b=new TextEncoder,x=!1,_=e=>{if(!x)try{l.enqueue(b.encode(e))}catch(e){r?.(e instanceof Error?e:Error(String(e)))}},w=(e,t)=>{_(`event: message
|
|
954
954
|
data: ${JSON.stringify({jsonrpc:"2.0",method:e,params:t})}
|
|
955
955
|
|
|
956
956
|
`)},S=e=>{if(!x){e&&_(`event: message
|
|
957
957
|
data: ${JSON.stringify({jsonrpc:"2.0",id:y,result:{resultType:"complete",_meta:{[n4]:y,[n1]:c}}})}
|
|
958
958
|
|
|
959
|
-
`),x=!0;try{p?.()}catch(e){r?.(e instanceof Error?e:Error(String(e)))}void 0!==u&&clearInterval(u),d?.(),n.delete(S);try{l.close()}catch{}}},k=new ReadableStream({start(e){l=e;let r=d4({method:"notifications/subscriptions/acknowledged",params:{notifications:v}},y);(w(r.method,r.params),0===Object.keys(v).length)?S(!0):(p=t.subscribe(e=>{if(x||!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)}}(v,e))return;let t=d4(function(e){switch(e.kind){case"tools_list_changed":return{method:"notifications/tools/list_changed",...void 0!==e.params&&{params:e.params}};case"prompts_list_changed":return{method:"notifications/prompts/list_changed",...void 0!==e.params&&{params:e.params}};case"resources_list_changed":return{method:"notifications/resources/list_changed",...void 0!==e.params&&{params:e.params}};case"resource_updated":return{method:"notifications/resources/updated",params:{...e.params,uri:e.uri}}}}(e),y);w(t.method,t.params)}),u=dA(i,()=>_(": keepalive\n\n")),n.add(S))},cancel(){S(!1)}});if(void 0!==o)if(o.aborted)S(!1);else{let e=()=>S(!1);o.addEventListener("abort",e,{once:!0}),d=()=>o.removeEventListener("abort",e)}return new Response(k,{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:f,maxSubscriptions:t.maxSubscriptions??1024,keepAliveMs:t.keepAliveMs??15e3,onerror:m});"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"===a?void 0:(r=t.keepAliveMs,async(t,a)=>{if("POST"!==t.method.toUpperCase())return d7(405,-32e3,"Method not allowed.");try{let i=await e({era:"legacy",...a?.authInfo!==void 0&&{authInfo:a.authInfo},requestInfo:t}),n=new d6({sessionIdGenerator:void 0,...void 0!==r&&{keepAliveMs:r},...void 0!==o&&{maxRequestBodySize:o}});await i.connect(n);let s=()=>{n.close().catch(()=>{}),i.close().catch(()=>{})};t.signal?.addEventListener("abort",s,{once:!0});let c=await n.handleRequest(t,{...a?.authInfo!==void 0&&{authInfo:a.authInfo},...a?.parsedBody!==void 0&&{parsedBody:a.parsedBody}});if(null===c.body||"text/event-stream"!==pH(c.headers.get("content-type")))return s(),c;let l=c.body.getReader(),p=!1,u=()=>{p||(p=!0,s())},d=new ReadableStream({pull:async e=>{try{let{done:t,value:r}=await l.read();if(t){u(),e.close();return}void 0!==r&&e.enqueue(r)}catch(t){u(),e.error(t)}},cancel:e=>(u(),l.cancel(e).catch(()=>{}))});return new Response(d,{status:c.status,statusText:c.statusText,headers:c.headers})}catch(e){try{m?.(mt(e))}catch{}return mr(d3(a?.parsedBody))}});return{fetch:async(r,a)=>{if(l)throw Error("This MCP handler has been closed");try{return await async function(r,a){let i=a?.authInfo;if("POST"===r.method.toUpperCase()&&!pZ(r.headers.get("content-type")))return m(Error("Unsupported Media Type: Content-Type must be application/json")),d7(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let l=await async function(e,t,r=!0,a=4194304){let i,n=e.method.toUpperCase(),o=t,s=e,c=!1;if("POST"===n){if(void 0===o){let t;r&&(s=e.clone());try{let r=await d5(e,a);if(r.tooLarge)return{step:"body-too-large"};t=r.text}catch{return{step:"unreadable-body"}}try{i=0===t.length?void 0:JSON.parse(t)}catch{c=!0}c||void 0===i||(o=i)}else i=o;if(c||void 0===i)return{step:"no-json-body",forwardRequest:s}}return{step:"classified",outcome:function(e){if("POST"!==(e={...e,...void 0!==e.protocolVersionHeader&&{protocolVersionHeader:pd(e.protocolVersionHeader)},...void 0!==e.mcpMethodHeader&&{mcpMethodHeader:pd(e.mcpMethodHeader)},...void 0!==e.mcpNameHeader&&{mcpNameHeader:pd(e.mcpNameHeader)}}).httpMethod.toUpperCase())return{kind:"legacy",reason:"http-method"};let t=e.body;if(Array.isArray(t)){if(0===t.length)return pl("jsonrpc-shape","empty-batch",400,new lS(lw.InvalidRequest,"Bad Request: empty JSON-RPC batch"),!0);for(let e of t){if(lY(pm(e)?e.params:void 0))return pl("jsonrpc-shape","batch-with-modern-element",400,new lS(lw.InvalidRequest,"Bad Request: JSON-RPC batches may not contain requests for protocol revision 2026-07-28 or later"),!0);if(!(l1(e)||l2(e)||l4(e)||l8(e)))return pl("jsonrpc-shape","batch-with-invalid-element",400,new lS(lw.InvalidRequest,"Bad Request: JSON-RPC batch contains an invalid message"),!0)}return{kind:"legacy",reason:"batch"}}return l4(t)||l8(t)?{kind:"legacy",reason:"response"}:pm(t)&&l1(t)?function(e,t){let r=t.params,a=t.method,i=e.protocolVersionHeader,n=void 0!==i&&i>=c4;if("initialize"===a&&!function(e){if(!lY(e))return!1;let t=lX(e);if(void 0===t||!(t>=c4))return!1;let r=lW(e);return void 0!==r&&0===lQ(r).length}(r)){if(n)return pp("initialize-with-modern-header",i,"an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header");let e=pm(r)&&"string"==typeof r.protocolVersion?r.protocolVersion:void 0;return{kind:"legacy",reason:"initialize",...void 0!==e&&{requestedVersion:e}}}if(lY(r)){let n=lW(r),o=(void 0===n?[]:lQ(n))[0];if(void 0!==o)return pl("envelope","envelope-invalid",400,new lS(lw.InvalidParams,`Invalid _meta envelope for protocol revision 2026-07-28: ${o.key}: ${o.problem}`,{envelope:o}),!0);let s=lX(r);return void 0!==i&&void 0!==s&&i!==s?pp("header-body-version-mismatch",i,`the body envelope names protocol version ${s} but the MCP-Protocol-Version header names ${i}`):void 0!==e.mcpMethodHeader&&e.mcpMethodHeader!==a?pp("method-header-mismatch",e.mcpMethodHeader,`the body names method ${a} but the Mcp-Method header names ${e.mcpMethodHeader}`):{kind:"modern",messageKind:"request",message:t,classification:pf(s)}}if(n){let e=lW(r),t=lQ(e??{}).filter(e=>"missing"===e.problem).map(e=>e.key),a=void 0===e?["_meta"]:t.length>0?t:[nQ];return pl("envelope","modern-header-without-claim",400,new lS(lw.InvalidParams,`Invalid params: the MCP-Protocol-Version header names protocol revision ${i}, but the request is missing the required per-request envelope key(s): ${a.join(", ")}`,{envelope:{missing:a}}),!0)}return{kind:"legacy",reason:"no-claim",...void 0!==i&&{requestedVersion:i}}}(e,t):pm(t)&&l2(t)?function(e,t){let r=t.params,a=t.method,i=e.protocolVersionHeader,n=void 0!==i&&i>=c4;if(lY(r)){let n=lX(r);if(void 0===n){let e=lW(r),t=(void 0===e?[]:lQ(e)).find(e=>e.key===nQ)??{key:nQ,problem:"expected a protocol version string"};return pl("envelope","notification-envelope-invalid",400,new lS(lw.InvalidParams,`Invalid _meta envelope for protocol revision 2026-07-28: ${t.key}: ${t.problem}`,{envelope:t}),!0)}if(void 0!==i&&i!==n)return pp("notification-header-body-version-mismatch",i,`the notification envelope names protocol version ${n} but the MCP-Protocol-Version header names ${i}`);let o=pf(n);return"modern"===o.era&&void 0!==e.mcpMethodHeader&&e.mcpMethodHeader!==a?pp("notification-method-header-mismatch",e.mcpMethodHeader,`the notification body names method ${a} but the Mcp-Method header names ${e.mcpMethodHeader}`):{kind:"modern",messageKind:"notification",message:t,classification:o}}return n?void 0!==e.mcpMethodHeader&&e.mcpMethodHeader!==a?pp("notification-method-header-mismatch",e.mcpMethodHeader,`the notification body names method ${a} but the Mcp-Method header names ${e.mcpMethodHeader}`):{kind:"modern",messageKind:"notification",message:t,classification:{era:"modern",revision:i}}:{kind:"legacy",reason:"notification",...void 0!==i&&{requestedVersion:i}}}(e,t):pl("jsonrpc-shape","invalid-json-rpc-body",400,new lS(lw.InvalidRequest,"Bad Request: the request body is not a valid JSON-RPC message"),!0)}({httpMethod:n,...mi(e),...void 0!==i&&{body:i}}),body:i,parsedBody:o,forwardRequest:s}}(r,a?.parsedBody,!0,o);if("unreadable-body"===l.step)return d7(400,-32700,"Parse error: the request body could not be read");if("body-too-large"===l.step)return d7(413,-32e3,d8(o));if("no-json-body"===l.step)return void 0!==v?v(l.forwardRequest,{...void 0!==i&&{authInfo:i}}):d7(400,-32700,"Parse error: the request body is not valid JSON");let{outcome:f,body:h,parsedBody:y,forwardRequest:b}=l;try{switch(f.kind){case"reject":return m(Error(`Rejected inbound request (${f.cell}): ${f.message}`)),me(f,d3(h));case"modern":return await async function(r,a,i){var o,l;let f=r.classification.revision;if(void 0===f||!c8.includes(f)){let e=new lj({supported:[...c8],requested:f??"unknown"});return m(e),d7(400,e.code,e.message,e.data,d3(r.message))}let h=function(e,t){if("request"!==t.messageKind)return;let r=t.message.method;if(void 0===e.protocolVersionHeader){let e=t.classification.revision;return pp("version-header-missing","(missing)",void 0===e?"the body carries a modern per-request envelope but the required MCP-Protocol-Version header is absent":`the body envelope names protocol version ${e} but the required MCP-Protocol-Version header is absent`,"standard-header-validation")}if(void 0===e.mcpMethodHeader)return pp("method-header-missing","(missing)",`the body names method ${r} but the required Mcp-Method header is absent`,"standard-header-validation");let a=function(e,t){let r=Object.hasOwn(pu,e)?pu[e]:void 0;if(void 0===r)return;let a=pm(t)?t[r]:void 0;return{field:r,value:"string"==typeof a?a:void 0}}(r,t.message.params);if(void 0===a)return;let{field:i,value:n}=a;if(void 0===e.mcpNameHeader){if(void 0===n)return;return pp("name-header-missing","(missing)",`the body carries params.${i}="${n}" but the required Mcp-Name header is absent`,"standard-header-validation")}let o=pd(e.mcpNameHeader),s=pn(o);return void 0===s?pp("name-header-invalid-encoding",o,"the Mcp-Name header carries an invalid Base64 sentinel value","standard-header-validation"):void 0!==n&&s!==n?pp("name-header-mismatch",o,`the body carries params.${i}="${n}" but the Mcp-Name header names "${s}"`,"standard-header-validation"):void 0}({httpMethod:a.method,...mi(a)},r);if(void 0!==h)return m(Error(`Rejected inbound request (${h.cell}): ${h.message}`)),me(h,d3(r.message));let v="request"===r.messageKind?lW(r.message.params):void 0,y=v?.[n2];if("request"===r.messageKind){let e=Object.hasOwn(c0,o=r.message.method)?c0[o]:void 0;if(void 0!==e){let t=c2(e,y);if(void 0!==t){let e=new lC({requiredCapabilities:t});return m(e),d7(pc[e.code]??400,e.code,e.message,e.data,r.message.id)}}}let b=await e({era:"modern",...void 0!==i&&{authInfo:i},requestInfo:a}),x=b instanceof dV?b.server:b;if(ma(x),"request"===r.messageKind&&"subscriptions/listen"===r.message.method){let e=x.getCapabilities(),t=d(x);return b.close().catch(m),g.serve(r.message,a.signal,e,t)}if("request"===r.messageKind&&"tools/call"===r.message.method&&b instanceof dV){let e=r.message.params,t="string"==typeof e?.name?e.name:void 0,i=void 0===t?void 0:b.toolInputSchemaJson(t);if(void 0!==i){let t=l7(i);if(void 0!==t.declarations&&t.declarations.length>0){let i=function(e,t,r){for(let a of e){let e=`Mcp-Param-${a.headerName}`,i=r.get(e),n=function(e,t){let r=e;for(let e of t){if(null===r||"object"!=typeof r)return;r=r[e]}return r}(t,a.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===i)return po("param-header-missing",e,`the body carries ${pr(a.path)}=${JSON.stringify(n)} but the ${e} header is absent`);let s=pn(i);if(void 0===s)return po("param-header-invalid-encoding",e,`the ${e} header carries an invalid Base64 sentinel value`);if(!(("integer"===a.type||"number"===a.type)&&pi.test(s)&&"number"==typeof n?Number(s)===n:s===o))return po("param-header-mismatch",e,`the ${e} header decodes to ${JSON.stringify(s)} but the body carries ${pr(a.path)}=${JSON.stringify(n)}`)}}(t.declarations,e?.arguments,a.headers);if(void 0!==i)return b.close().catch(m),m(Error(`Rejected inbound request (${i.cell}): ${i.message}`)),me(i,r.message.id)}}}if("request"===r.messageKind&&b instanceof dV)try{let e=await dz([r.message],i,e=>b.resolveScopeChallenge(e));if(void 0!==e)return b.close().catch(m),dL(e,dM(i))}catch(e){return b.close().catch(m),m(mt(e)),mr(r.message.id)}ma(x),c(x,f),u(x,c8),void 0!==v&&(l={clientInfo:v[n0],clientCapabilities:y},p(x,l));let _=x.onclose;s.add(x);let w=()=>{s.delete(x),x.onclose===w&&(x.onclose=_),_?.()};x.onclose=w;try{let e=await async function(e,t,r){let a=new dI({classification:r.classification,...void 0!==r.responseMode&&{responseMode:r.responseMode},...void 0!==r.keepAliveMs&&{keepAliveMs:r.keepAliveMs}});return await e.connect(a),a.handleMessage(t,{...void 0!==r.request&&{request:r.request},...void 0!==r.authInfo&&{authInfo:r.authInfo}})}(b,r.message,{classification:r.classification,request:a,...void 0!==i&&{authInfo:i},...void 0!==n&&{responseMode:n},...void 0!==t.keepAliveMs&&{keepAliveMs:t.keepAliveMs}});return"notification"===r.messageKind&&queueMicrotask(()=>void x.close().catch(()=>{})),e}catch(e){if(e instanceof cQ&&e.code===cX.ConnectionClosed)return new Response(null,{status:499});return await x.close().catch(()=>{}),s.delete(x),m(mt(e)),mr(d3(r.message))}}(f,r,i);case"legacy":return await async function(e,t,r,a){if(void 0!==v)return v(t,{...void 0!==r&&{authInfo:r},...void 0!==a&&{parsedBody:a}});let i=function(e,t){switch(e.reason){case"http-method":return pl("http-method","modern-only-method-not-allowed",405,new lS(-32e3,"Method not allowed."),!0);case"batch":return pl("jsonrpc-shape","modern-only-batch-not-supported",400,new lS(lw.InvalidRequest,"Bad Request: JSON-RPC batches are not supported by this endpoint"),!0);case"response":return pl("jsonrpc-shape","modern-only-response-post",400,new lS(lw.InvalidRequest,"Bad Request: JSON-RPC responses cannot be posted to this endpoint"),!0);case"notification":return;case"initialize":case"no-claim":{let r=e.requestedVersion;return pl("era-classification","modern-only-missing-envelope",400,void 0===r?new lS(lw.UnsupportedProtocolVersion,"Unsupported protocol version: the request did not name a protocol version",{supported:[...t]}):new lj({supported:[...t],requested:r}),!0)}}}(e,c8);return void 0===i?new Response(null,{status:202}):(m(Error(`Rejected 2025-era request on a modern-only endpoint (${i.cell}): ${i.message}`)),me(i,d3(a)))}(f,b,i,y)}}catch(e){return m(mt(e)),mr(d3(h))}}(r,a)}catch(e){return m(mt(e)),mr(d3(a?.parsedBody))}},notify:h,bus:f,close:async()=>{l=!0,g.closeAll();let e=[...s].map(e=>e.close().catch(()=>{}));s.clear(),await Promise.all(e)}}}(()=>this.createServerFn(),{legacy:"stateless",onerror:e=>this.log("MCP handler error:",e),maxSubscriptions:this.options.maxSubscriptions}),this.nodeMcpHandler=(i=this.mcpHandler,n={onerror:e=>console.error("[HTTP-server] Error handling MCP request:",e)},o=h7(n?.maxRequestBodySize),async(e,t,r)=>{let a,s;"function"==typeof r&&(r=void 0);let c=!1,l=new AbortController;t.on("close",()=>{c||l.abort()}),!0===t.destroyed&&l.abort();try{let t=await async function(e,t,r){let a,i=h7(r?.maxRequestBodySize),n=(e.method??"GET").toUpperCase(),o=`http://${ge(e.headers.host)??ge(e.headers[":authority"])??"localhost"}${e.url??"/"}`,s=new Headers;for(let[t,r]of Object.entries(e.headers))if(!(void 0===r||t.startsWith(":")))if(Array.isArray(r))for(let e of r)s.append(t,e);else s.set(t,r);if("GET"!==n&&"HEAD"!==n)if(void 0===t){if(Number(ge(e.headers["content-length"]))>i)throw new h3(i);let t=new TextDecoder,r="",n=0;for await(let a of e){if((n+="string"==typeof a?new TextEncoder().encode(a).byteLength:a.byteLength)>i)throw new h3(i);r+="string"==typeof a?a:t.decode(a,{stream:!0})}(r+=t.decode()).length>0&&(a=r)}else{let e=JSON.stringify(t);s.delete("content-encoding"),s.delete("transfer-encoding"),void 0===e?s.delete("content-length"):(a=e,s.set("content-length",String(new TextEncoder().encode(e).byteLength)))}return new Request(o,{method:n,headers:s,...r?.signal!==void 0&&{signal:r.signal},...void 0!==a&&{body:a}})}(e,r,{signal:l.signal,maxRequestBodySize:o});a=await i.fetch(t,{...void 0!==e.auth&&{authInfo:e.auth},...void 0!==r&&{parsedBody:r}})}catch(e){if(e instanceof h3)a=Response.json({jsonrpc:"2.0",error:{code:-32e3,message:e.message},id:null},{status:413,headers:{connection:"close"}});else{var p;try{n?.onerror?.(e instanceof Error?e:Error(String(e)))}catch{}p=function(e){if(null===e||"object"!=typeof e||Array.isArray(e))return null;let{method:t,id:r}=e;return"string"!=typeof t?null:"string"==typeof r||"number"==typeof r?r:null}(r),a=Response.json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:p},{status:500})}}let u={};for(let[e,t]of a.headers)u[e]=t;if(t.writeHead(a.status,u),null===a.body){c=!0,t.end();return}t.on("drain",()=>{s?.(),s=void 0});let d=new Promise(e=>{l.signal.addEventListener("abort",()=>e(),{once:!0})});try{for await(let e of a.body){if(l.signal.aborted)break;!1===t.write(e)&&await Promise.race([new Promise(e=>{s=e}),d])}}catch{}c=!0,t.end()}),this.app.use(gr().json({limit:this.options.bodySizeLimit||"10mb"})),this.setupInitialRoutes(),this.setupInitialMiddleware(),this.setupProviders(),this.setupEndpointRoute()}}M().config();let gd=HTTP_CONFIG,gm=HTTP_CORS_CONFIG,gf=TEMPLATE_CONFIG,gh=INJECTED_MIDDLEWARE;!async function(){let e=await async function(){let e={port:gd?.port,host:gd?.host,debug:gd?.debug,bodySizeLimit:gd?.bodySizeLimit?.toString(),maxSubscriptions:gd?.maxSubscriptions,endpoint:gd?.endpoint,template:gf},t={origin:gm.origin,methods:gm.methods,allowedHeaders:gm.allowedHeaders,exposedHeaders:gm.exposedHeaders,credentials:gm.credentials,maxAge:gm.maxAge},r=[];if(gh){let e=await gh();e&&e.default&&(r=function(e){let t=[];if(Array.isArray(e))for(let r of e)V(r)?t.push({middleware:r}):B(r)&&t.push({middleware:r.middleware,router:r.router});else V(e)?t.push({middleware:e}):B(e)&&t.push({middleware:e.middleware,router:e.router});return t}(e.default))}return Z({config:{http:gd}},async()=>new gu(hF,e,t,r))}();await e.start()}()})(),{}})());
|
|
959
|
+
`),x=!0;try{p?.()}catch(e){r?.(e instanceof Error?e:Error(String(e)))}void 0!==u&&clearInterval(u),d?.(),n.delete(S);try{l.close()}catch{}}},k=new ReadableStream({start(e){l=e;let r=d4({method:"notifications/subscriptions/acknowledged",params:{notifications:v}},y);(w(r.method,r.params),0===Object.keys(v).length)?S(!0):(p=t.subscribe(e=>{if(x||!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)}}(v,e))return;let t=d4(function(e){switch(e.kind){case"tools_list_changed":return{method:"notifications/tools/list_changed",...void 0!==e.params&&{params:e.params}};case"prompts_list_changed":return{method:"notifications/prompts/list_changed",...void 0!==e.params&&{params:e.params}};case"resources_list_changed":return{method:"notifications/resources/list_changed",...void 0!==e.params&&{params:e.params}};case"resource_updated":return{method:"notifications/resources/updated",params:{...e.params,uri:e.uri}}}}(e),y);w(t.method,t.params)}),u=dA(i,()=>_(": keepalive\n\n")),n.add(S))},cancel(){S(!1)}});if(void 0!==o)if(o.aborted)S(!1);else{let e=()=>S(!1);o.addEventListener("abort",e,{once:!0}),d=()=>o.removeEventListener("abort",e)}return new Response(k,{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:f,maxSubscriptions:t.maxSubscriptions??1024,keepAliveMs:t.keepAliveMs??15e3,onerror:m});"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"===a?void 0:(r=t.keepAliveMs,async(t,a)=>{if("POST"!==t.method.toUpperCase())return d7(405,-32e3,"Method not allowed.");try{let i=await e({era:"legacy",...a?.authInfo!==void 0&&{authInfo:a.authInfo},requestInfo:t}),n=new d6({sessionIdGenerator:void 0,...void 0!==r&&{keepAliveMs:r},...void 0!==o&&{maxRequestBodySize:o}});await i.connect(n);let s=()=>{n.close().catch(()=>{}),i.close().catch(()=>{})};t.signal?.addEventListener("abort",s,{once:!0});let c=await n.handleRequest(t,{...a?.authInfo!==void 0&&{authInfo:a.authInfo},...a?.parsedBody!==void 0&&{parsedBody:a.parsedBody}});if(null===c.body||"text/event-stream"!==pH(c.headers.get("content-type")))return s(),c;let l=c.body.getReader(),p=!1,u=()=>{p||(p=!0,s())},d=new ReadableStream({pull:async e=>{try{let{done:t,value:r}=await l.read();if(t){u(),e.close();return}void 0!==r&&e.enqueue(r)}catch(t){u(),e.error(t)}},cancel:e=>(u(),l.cancel(e).catch(()=>{}))});return new Response(d,{status:c.status,statusText:c.statusText,headers:c.headers})}catch(e){try{m?.(mt(e))}catch{}return mr(d3(a?.parsedBody))}});return{fetch:async(r,a)=>{if(l)throw Error("This MCP handler has been closed");try{return await async function(r,a){let i=a?.authInfo;if("POST"===r.method.toUpperCase()&&!pZ(r.headers.get("content-type")))return m(Error("Unsupported Media Type: Content-Type must be application/json")),d7(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let l=await async function(e,t,r=!0,a=4194304){let i,n=e.method.toUpperCase(),o=t,s=e,c=!1;if("POST"===n){if(void 0===o){let t;r&&(s=e.clone());try{let r=await d5(e,a);if(r.tooLarge)return{step:"body-too-large"};t=r.text}catch{return{step:"unreadable-body"}}try{i=0===t.length?void 0:JSON.parse(t)}catch{c=!0}c||void 0===i||(o=i)}else i=o;if(c||void 0===i)return{step:"no-json-body",forwardRequest:s}}return{step:"classified",outcome:function(e){if("POST"!==(e={...e,...void 0!==e.protocolVersionHeader&&{protocolVersionHeader:pd(e.protocolVersionHeader)},...void 0!==e.mcpMethodHeader&&{mcpMethodHeader:pd(e.mcpMethodHeader)},...void 0!==e.mcpNameHeader&&{mcpNameHeader:pd(e.mcpNameHeader)}}).httpMethod.toUpperCase())return{kind:"legacy",reason:"http-method"};let t=e.body;if(Array.isArray(t)){if(0===t.length)return pl("jsonrpc-shape","empty-batch",400,new lS(lw.InvalidRequest,"Bad Request: empty JSON-RPC batch"),!0);for(let e of t){if(lY(pm(e)?e.params:void 0))return pl("jsonrpc-shape","batch-with-modern-element",400,new lS(lw.InvalidRequest,"Bad Request: JSON-RPC batches may not contain requests for protocol revision 2026-07-28 or later"),!0);if(!(l1(e)||l2(e)||l4(e)||l8(e)))return pl("jsonrpc-shape","batch-with-invalid-element",400,new lS(lw.InvalidRequest,"Bad Request: JSON-RPC batch contains an invalid message"),!0)}return{kind:"legacy",reason:"batch"}}return l4(t)||l8(t)?{kind:"legacy",reason:"response"}:pm(t)&&l1(t)?function(e,t){let r=t.params,a=t.method,i=e.protocolVersionHeader,n=void 0!==i&&i>=c4;if("initialize"===a&&!function(e){if(!lY(e))return!1;let t=lX(e);if(void 0===t||!(t>=c4))return!1;let r=lW(e);return void 0!==r&&0===lQ(r).length}(r)){if(n)return pp("initialize-with-modern-header",i,"an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header");let e=pm(r)&&"string"==typeof r.protocolVersion?r.protocolVersion:void 0;return{kind:"legacy",reason:"initialize",...void 0!==e&&{requestedVersion:e}}}if(lY(r)){let n=lW(r),o=(void 0===n?[]:lQ(n))[0];if(void 0!==o)return pl("envelope","envelope-invalid",400,new lS(lw.InvalidParams,`Invalid _meta envelope for protocol revision 2026-07-28: ${o.key}: ${o.problem}`,{envelope:o}),!0);let s=lX(r);return void 0!==i&&void 0!==s&&i!==s?pp("header-body-version-mismatch",i,`the body envelope names protocol version ${s} but the MCP-Protocol-Version header names ${i}`):void 0!==e.mcpMethodHeader&&e.mcpMethodHeader!==a?pp("method-header-mismatch",e.mcpMethodHeader,`the body names method ${a} but the Mcp-Method header names ${e.mcpMethodHeader}`):{kind:"modern",messageKind:"request",message:t,classification:pf(s)}}if(n){let e=lW(r),t=lQ(e??{}).filter(e=>"missing"===e.problem).map(e=>e.key),a=void 0===e?["_meta"]:t.length>0?t:[nQ];return pl("envelope","modern-header-without-claim",400,new lS(lw.InvalidParams,`Invalid params: the MCP-Protocol-Version header names protocol revision ${i}, but the request is missing the required per-request envelope key(s): ${a.join(", ")}`,{envelope:{missing:a}}),!0)}return{kind:"legacy",reason:"no-claim",...void 0!==i&&{requestedVersion:i}}}(e,t):pm(t)&&l2(t)?function(e,t){let r=t.params,a=t.method,i=e.protocolVersionHeader,n=void 0!==i&&i>=c4;if(lY(r)){let n=lX(r);if(void 0===n){let e=lW(r),t=(void 0===e?[]:lQ(e)).find(e=>e.key===nQ)??{key:nQ,problem:"expected a protocol version string"};return pl("envelope","notification-envelope-invalid",400,new lS(lw.InvalidParams,`Invalid _meta envelope for protocol revision 2026-07-28: ${t.key}: ${t.problem}`,{envelope:t}),!0)}if(void 0!==i&&i!==n)return pp("notification-header-body-version-mismatch",i,`the notification envelope names protocol version ${n} but the MCP-Protocol-Version header names ${i}`);let o=pf(n);return"modern"===o.era&&void 0!==e.mcpMethodHeader&&e.mcpMethodHeader!==a?pp("notification-method-header-mismatch",e.mcpMethodHeader,`the notification body names method ${a} but the Mcp-Method header names ${e.mcpMethodHeader}`):{kind:"modern",messageKind:"notification",message:t,classification:o}}return n?void 0!==e.mcpMethodHeader&&e.mcpMethodHeader!==a?pp("notification-method-header-mismatch",e.mcpMethodHeader,`the notification body names method ${a} but the Mcp-Method header names ${e.mcpMethodHeader}`):{kind:"modern",messageKind:"notification",message:t,classification:{era:"modern",revision:i}}:{kind:"legacy",reason:"notification",...void 0!==i&&{requestedVersion:i}}}(e,t):pl("jsonrpc-shape","invalid-json-rpc-body",400,new lS(lw.InvalidRequest,"Bad Request: the request body is not a valid JSON-RPC message"),!0)}({httpMethod:n,...mi(e),...void 0!==i&&{body:i}}),body:i,parsedBody:o,forwardRequest:s}}(r,a?.parsedBody,!0,o);if("unreadable-body"===l.step)return d7(400,-32700,"Parse error: the request body could not be read");if("body-too-large"===l.step)return d7(413,-32e3,d8(o));if("no-json-body"===l.step)return void 0!==v?v(l.forwardRequest,{...void 0!==i&&{authInfo:i}}):d7(400,-32700,"Parse error: the request body is not valid JSON");let{outcome:f,body:h,parsedBody:y,forwardRequest:b}=l;try{switch(f.kind){case"reject":return m(Error(`Rejected inbound request (${f.cell}): ${f.message}`)),me(f,d3(h));case"modern":return await async function(r,a,i){var o,l;let f=r.classification.revision;if(void 0===f||!c8.includes(f)){let e=new lj({supported:[...c8],requested:f??"unknown"});return m(e),d7(400,e.code,e.message,e.data,d3(r.message))}let h=function(e,t){if("request"!==t.messageKind)return;let r=t.message.method;if(void 0===e.protocolVersionHeader){let e=t.classification.revision;return pp("version-header-missing","(missing)",void 0===e?"the body carries a modern per-request envelope but the required MCP-Protocol-Version header is absent":`the body envelope names protocol version ${e} but the required MCP-Protocol-Version header is absent`,"standard-header-validation")}if(void 0===e.mcpMethodHeader)return pp("method-header-missing","(missing)",`the body names method ${r} but the required Mcp-Method header is absent`,"standard-header-validation");let a=function(e,t){let r=Object.hasOwn(pu,e)?pu[e]:void 0;if(void 0===r)return;let a=pm(t)?t[r]:void 0;return{field:r,value:"string"==typeof a?a:void 0}}(r,t.message.params);if(void 0===a)return;let{field:i,value:n}=a;if(void 0===e.mcpNameHeader){if(void 0===n)return;return pp("name-header-missing","(missing)",`the body carries params.${i}="${n}" but the required Mcp-Name header is absent`,"standard-header-validation")}let o=pd(e.mcpNameHeader),s=pn(o);return void 0===s?pp("name-header-invalid-encoding",o,"the Mcp-Name header carries an invalid Base64 sentinel value","standard-header-validation"):void 0!==n&&s!==n?pp("name-header-mismatch",o,`the body carries params.${i}="${n}" but the Mcp-Name header names "${s}"`,"standard-header-validation"):void 0}({httpMethod:a.method,...mi(a)},r);if(void 0!==h)return m(Error(`Rejected inbound request (${h.cell}): ${h.message}`)),me(h,d3(r.message));let v="request"===r.messageKind?lW(r.message.params):void 0,y=v?.[n2];if("request"===r.messageKind){let e=Object.hasOwn(c0,o=r.message.method)?c0[o]:void 0;if(void 0!==e){let t=c2(e,y);if(void 0!==t){let e=new lC({requiredCapabilities:t});return m(e),d7(pc[e.code]??400,e.code,e.message,e.data,r.message.id)}}}let b=await e({era:"modern",...void 0!==i&&{authInfo:i},requestInfo:a}),x=b instanceof dV?b.server:b;if(ma(x),"request"===r.messageKind&&"subscriptions/listen"===r.message.method){let e=x.getCapabilities(),t=d(x);return b.close().catch(m),g.serve(r.message,a.signal,e,t)}if("request"===r.messageKind&&"tools/call"===r.message.method&&b instanceof dV){let e=r.message.params,t="string"==typeof e?.name?e.name:void 0,i=void 0===t?void 0:b.toolInputSchemaJson(t);if(void 0!==i){let t=l7(i);if(void 0!==t.declarations&&t.declarations.length>0){let i=function(e,t,r){for(let a of e){let e=`Mcp-Param-${a.headerName}`,i=r.get(e),n=function(e,t){let r=e;for(let e of t){if(null===r||"object"!=typeof r)return;r=r[e]}return r}(t,a.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===i)return po("param-header-missing",e,`the body carries ${pr(a.path)}=${JSON.stringify(n)} but the ${e} header is absent`);let s=pn(i);if(void 0===s)return po("param-header-invalid-encoding",e,`the ${e} header carries an invalid Base64 sentinel value`);if(!(("integer"===a.type||"number"===a.type)&&pi.test(s)&&"number"==typeof n?Number(s)===n:s===o))return po("param-header-mismatch",e,`the ${e} header decodes to ${JSON.stringify(s)} but the body carries ${pr(a.path)}=${JSON.stringify(n)}`)}}(t.declarations,e?.arguments,a.headers);if(void 0!==i)return b.close().catch(m),m(Error(`Rejected inbound request (${i.cell}): ${i.message}`)),me(i,r.message.id)}}}if("request"===r.messageKind&&b instanceof dV)try{let e=await dz([r.message],i,e=>b.resolveScopeChallenge(e));if(void 0!==e)return b.close().catch(m),dL(e,dM(i))}catch(e){return b.close().catch(m),m(mt(e)),mr(r.message.id)}ma(x),c(x,f),u(x,c8),void 0!==v&&(l={clientInfo:v[n0],clientCapabilities:y},p(x,l));let _=x.onclose;s.add(x);let w=()=>{s.delete(x),x.onclose===w&&(x.onclose=_),_?.()};x.onclose=w;try{let e=await async function(e,t,r){let a=new dI({classification:r.classification,...void 0!==r.responseMode&&{responseMode:r.responseMode},...void 0!==r.keepAliveMs&&{keepAliveMs:r.keepAliveMs}});return await e.connect(a),a.handleMessage(t,{...void 0!==r.request&&{request:r.request},...void 0!==r.authInfo&&{authInfo:r.authInfo}})}(b,r.message,{classification:r.classification,request:a,...void 0!==i&&{authInfo:i},...void 0!==n&&{responseMode:n},...void 0!==t.keepAliveMs&&{keepAliveMs:t.keepAliveMs}});return"notification"===r.messageKind&&queueMicrotask(()=>void x.close().catch(()=>{})),e}catch(e){if(e instanceof cQ&&e.code===cX.ConnectionClosed)return new Response(null,{status:499});return await x.close().catch(()=>{}),s.delete(x),m(mt(e)),mr(d3(r.message))}}(f,r,i);case"legacy":return await async function(e,t,r,a){if(void 0!==v)return v(t,{...void 0!==r&&{authInfo:r},...void 0!==a&&{parsedBody:a}});let i=function(e,t){switch(e.reason){case"http-method":return pl("http-method","modern-only-method-not-allowed",405,new lS(-32e3,"Method not allowed."),!0);case"batch":return pl("jsonrpc-shape","modern-only-batch-not-supported",400,new lS(lw.InvalidRequest,"Bad Request: JSON-RPC batches are not supported by this endpoint"),!0);case"response":return pl("jsonrpc-shape","modern-only-response-post",400,new lS(lw.InvalidRequest,"Bad Request: JSON-RPC responses cannot be posted to this endpoint"),!0);case"notification":return;case"initialize":case"no-claim":{let r=e.requestedVersion;return pl("era-classification","modern-only-missing-envelope",400,void 0===r?new lS(lw.UnsupportedProtocolVersion,"Unsupported protocol version: the request did not name a protocol version",{supported:[...t]}):new lj({supported:[...t],requested:r}),!0)}}}(e,c8);return void 0===i?new Response(null,{status:202}):(m(Error(`Rejected 2025-era request on a modern-only endpoint (${i.cell}): ${i.message}`)),me(i,d3(a)))}(f,b,i,y)}}catch(e){return m(mt(e)),mr(d3(h))}}(r,a)}catch(e){return m(mt(e)),mr(d3(a?.parsedBody))}},notify:h,bus:f,close:async()=>{l=!0,g.closeAll();let e=[...s].map(e=>e.close().catch(()=>{}));s.clear(),await Promise.all(e)}}}(()=>this.createServerFn(),{legacy:"stateless",onerror:e=>this.log("MCP handler error:",e),maxSubscriptions:this.options.maxSubscriptions}),this.nodeMcpHandler=(i=this.mcpHandler,n={onerror:e=>console.error("[HTTP-server] Error handling MCP request:",e)},o=gR(n?.maxRequestBodySize),async(e,t,r)=>{let a,s;"function"==typeof r&&(r=void 0);let c=!1,l=new AbortController;t.on("close",()=>{c||l.abort()}),!0===t.destroyed&&l.abort();try{let t=await async function(e,t,r){let a,i=gR(r?.maxRequestBodySize),n=(e.method??"GET").toUpperCase(),o=`http://${gO(e.headers.host)??gO(e.headers[":authority"])??"localhost"}${e.url??"/"}`,s=new Headers;for(let[t,r]of Object.entries(e.headers))if(!(void 0===r||t.startsWith(":")))if(Array.isArray(r))for(let e of r)s.append(t,e);else s.set(t,r);if("GET"!==n&&"HEAD"!==n)if(void 0===t){if(Number(gO(e.headers["content-length"]))>i)throw new gE(i);let t=new TextDecoder,r="",n=0;for await(let a of e){if((n+="string"==typeof a?new TextEncoder().encode(a).byteLength:a.byteLength)>i)throw new gE(i);r+="string"==typeof a?a:t.decode(a,{stream:!0})}(r+=t.decode()).length>0&&(a=r)}else{let e=JSON.stringify(t);s.delete("content-encoding"),s.delete("transfer-encoding"),void 0===e?s.delete("content-length"):(a=e,s.set("content-length",String(new TextEncoder().encode(e).byteLength)))}return new Request(o,{method:n,headers:s,...r?.signal!==void 0&&{signal:r.signal},...void 0!==a&&{body:a}})}(e,r,{signal:l.signal,maxRequestBodySize:o});a=await i.fetch(t,{...void 0!==e.auth&&{authInfo:e.auth},...void 0!==r&&{parsedBody:r}})}catch(e){if(e instanceof gE)a=Response.json({jsonrpc:"2.0",error:{code:-32e3,message:e.message},id:null},{status:413,headers:{connection:"close"}});else{var p;try{n?.onerror?.(e instanceof Error?e:Error(String(e)))}catch{}p=function(e){if(null===e||"object"!=typeof e||Array.isArray(e))return null;let{method:t,id:r}=e;return"string"!=typeof t?null:"string"==typeof r||"number"==typeof r?r:null}(r),a=Response.json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:p},{status:500})}}let u={};for(let[e,t]of a.headers)u[e]=t;if(t.writeHead(a.status,u),null===a.body){c=!0,t.end();return}t.on("drain",()=>{s?.(),s=void 0});let d=new Promise(e=>{l.signal.addEventListener("abort",()=>e(),{once:!0})});try{for await(let e of a.body){if(l.signal.aborted)break;!1===t.write(e)&&await Promise.race([new Promise(e=>{s=e}),d])}}catch{}c=!0,t.end()}),this.app.use(gT().json({limit:this.options.bodySizeLimit||"10mb"})),this.setupInitialRoutes(),this.setupInitialMiddleware(),this.setupProviders(),this.setupEndpointRoute()}}M().config();let gZ=HTTP_CONFIG,gV=HTTP_CORS_CONFIG,gB=TEMPLATE_CONFIG,gJ=INJECTED_MIDDLEWARE;!async function(){let e=await async function(){let e={port:gZ?.port,host:gZ?.host,debug:gZ?.debug,bodySizeLimit:gZ?.bodySizeLimit?.toString(),maxSubscriptions:gZ?.maxSubscriptions,endpoint:gZ?.endpoint,template:gB},t={origin:gV.origin,methods:gV.methods,allowedHeaders:gV.allowedHeaders,exposedHeaders:gV.exposedHeaders,credentials:gV.credentials,maxAge:gV.maxAge},r=[];if(gJ){let e=await gJ();e&&e.default&&(r=function(e){let t=[];if(Array.isArray(e))for(let r of e)V(r)?t.push({middleware:r}):B(r)&&t.push({middleware:r.middleware,router:r.router});else V(e)?t.push({middleware:e}):B(e)&&t.push({middleware:e.middleware,router:e.router});return t}(e.default))}return Z({config:{http:gZ}},async()=>new gH(hF,e,t,r))}();await e.start()}()})(),{}})());
|