xmcp 0.0.13 → 0.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +0,0 @@
1
- !function(e,s){if("object"==typeof exports&&"object"==typeof module)module.exports=s();else if("function"==typeof define&&define.amd)define([],s);else{var t=s();for(var r in t)("object"==typeof exports?exports:e)[r]=t[r]}}(this,(()=>(()=>{"use strict";var e,s,t,r={181:e=>{e.exports=require("buffer")},290:e=>{e.exports=require("async_hooks")},2018:e=>{e.exports=require("tty")},2203:e=>{e.exports=require("stream")},3106:e=>{e.exports=require("zlib")},3193:e=>{e.exports=require("string_decoder")},3480:e=>{e.exports=require("querystring")},3855:(e,s,t)=>{var r=t(1275),o=t.n(r),n=t(8611),i=t.n(n);const a=require("node:crypto");var d=t(9636),l=t(6619),h=t(1266),c=t(7016);class p{constructor(e,s){this._endpoint=e,this.res=s,this._sessionId=(0,a.randomUUID)()}async start(){if(this._sseResponse)throw new Error("SSEServerTransport already started! If using Server class, note that connect() calls start() automatically.");this.res.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive"});const e=new c.URL(this._endpoint,"http://localhost");e.searchParams.set("sessionId",this._sessionId);const s=e.pathname+e.search+e.hash;this.res.write(`event: endpoint\ndata: ${s}\n\n`),this._sseResponse=this.res,this.res.on("close",(()=>{var e;this._sseResponse=void 0,null===(e=this.onclose)||void 0===e||e.call(this)}))}async handlePostMessage(e,s,t){var r,o,n;if(!this._sseResponse){const e="SSE connection not established";throw s.writeHead(500).end(e),new Error(e)}const i=e.auth;let a;try{const s=h.parse(null!==(r=e.headers["content-type"])&&void 0!==r?r:"");if("application/json"!==s.type)throw new Error(`Unsupported content-type: ${s}`);a=null!=t?t:await l(e,{limit:"4mb",encoding:null!==(o=s.parameters.charset)&&void 0!==o?o:"utf-8"})}catch(e){return s.writeHead(400).end(String(e)),void(null===(n=this.onerror)||void 0===n||n.call(this,e))}try{await this.handleMessage("string"==typeof a?JSON.parse(a):a,{authInfo:i})}catch(e){return void s.writeHead(400).end(`Invalid message: ${a}`)}s.writeHead(202).end("Accepted")}async handleMessage(e,s){var t,r;let o;try{o=d.OR.parse(e)}catch(e){throw null===(t=this.onerror)||void 0===t||t.call(this,e),e}null===(r=this.onmessage)||void 0===r||r.call(this,o,s)}async close(){var e,s;null===(e=this._sseResponse)||void 0===e||e.end(),this._sseResponse=void 0,null===(s=this.onclose)||void 0===s||s.call(this)}async send(e){if(!this._sseResponse)throw new Error("Not connected");this._sseResponse.write(`event: message\ndata: ${JSON.stringify(e)}\n\n`)}get sessionId(){return this._sessionId}}var u=t(3299),g=t(993);function v(e,s,t){return s in e?Object.defineProperty(e,s,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[s]=t,e}const S=SSE_PORT,f=SSE_DEBUG,y=SSE_BODY_SIZE_LIMIT;class m{log(e,...s){this.debug&&console.log(`[SSE] ${e}`,...s)}logError(e,...s){this.debug&&console.error(`[SSE] ${e}`,...s)}setupMiddleware(e){this.app.use(((e,s,t)=>{const r=this.corsOptions;void 0!==r.origin&&s.setHeader("Access-Control-Allow-Origin",Array.isArray(r.origin)?r.origin.join(","):String(r.origin)),void 0!==r.methods&&s.setHeader("Access-Control-Allow-Methods",Array.isArray(r.methods)?r.methods.join(","):String(r.methods)),void 0!==r.allowedHeaders&&s.setHeader("Access-Control-Allow-Headers",Array.isArray(r.allowedHeaders)?r.allowedHeaders.join(","):String(r.allowedHeaders)),void 0!==r.exposedHeaders&&s.setHeader("Access-Control-Expose-Headers",Array.isArray(r.exposedHeaders)?r.exposedHeaders.join(","):String(r.exposedHeaders)),"boolean"==typeof r.credentials&&s.setHeader("Access-Control-Allow-Credentials",String(r.credentials)),"number"==typeof r.maxAge&&s.setHeader("Access-Control-Max-Age",String(r.maxAge)),"OPTIONS"!==e.method?t():s.sendStatus(200)})),this.app.use(o().json({limit:e})),this.app.use(((e,s,t)=>{this.log(`${e.method} ${e.path}`),t()}))}setupRoutes(){this.app.get("/",((e,s)=>{s.send((0,g.A)("/sse"))})),this.app.get("/health",((e,s)=>{s.status(200).json({status:"ok"})})),this.app.get("/sse",this.handleConnection.bind(this)),this.app.post("/message",this.handleMessage.bind(this))}async handleConnection(e,s){this.log("Client connected to SSE endpoint");const t=new p("/message",s);try{this.mcpServer.connect(t);const s=t.sessionId;this.log(`Created transport with session ID: ${s}`),this.activeTransports.set(s,t),e.on("close",(()=>{this.log(`Client disconnected for session ID: ${s}`),this.activeTransports.delete(s),t.close().catch((e=>{this.logError("Error closing transport:",e)}))}))}catch(e){this.logError("Error starting transport:",e),s.status(500).end("Internal Server Error")}}async handleMessage(e,s){const t=e.query.sessionId;if(!t)return this.log("Missing sessionId parameter"),void s.status(400).json({jsonrpc:"2.0",error:{code:-32e3,message:"Missing sessionId parameter"},id:e.body?.id||null});const r=this.activeTransports.get(t);if(!r)return this.log(`No active session found for sessionId: ${t}`),void s.status(404).json({jsonrpc:"2.0",error:{code:-32e3,message:`No active session found for sessionId: ${t}`},id:e.body?.id||null});try{await r.handlePostMessage(e,s,e.body)}catch(t){this.logError("Error handling message:",t),s.status(500).json({jsonrpc:"2.0",error:{code:-32603,message:"Internal error",data:t.message},id:e.body?.id||null})}}start(){this.server.listen(this.port,(()=>{console.log(`[SSE] MCP Server running with SDK transport on http://localhost:${this.port}`),console.log(`[SSE] - SSE endpoint: http://localhost:${this.port}/sse`),this.debug&&console.log("[SSE] Debug mode: enabled"),this.setupShutdownHandlers()}))}setupShutdownHandlers(){process.on("SIGINT",this.shutdown.bind(this)),process.on("SIGTERM",this.shutdown.bind(this))}shutdown(){this.log("Shutting down server"),this.server.close(),process.exit(0)}getActiveTransportsCount(){return this.activeTransports.size}constructor(e,s={},t={}){v(this,"app",void 0),v(this,"server",void 0),v(this,"port",void 0),v(this,"mcpServer",void 0),v(this,"activeTransports",new Map),v(this,"debug",void 0),v(this,"corsOptions",void 0),this.mcpServer=e,this.app=o()(),this.server=i().createServer(this.app),this.port=s.port??parseInt(process.env.PORT||"3001",10),this.debug=s.debug??!1,this.corsOptions=t,this.setupMiddleware(s.bodySizeLimit||"10mb"),this.setupRoutes()}}const E={origin:SSE_CORS_ORIGIN,methods:SSE_CORS_METHODS,allowedHeaders:SSE_CORS_ALLOWED_HEADERS,exposedHeaders:SSE_CORS_EXPOSED_HEADERS,credentials:SSE_CORS_CREDENTIALS,maxAge:SSE_CORS_MAX_AGE};(0,u.s)().then((e=>{new m(e,{port:S,debug:f,bodySizeLimit:y},E).start()}))},4434:e=>{e.exports=require("events")},6928:e=>{e.exports=require("path")},6982:e=>{e.exports=require("crypto")},7016:e=>{e.exports=require("url")},8611:e=>{e.exports=require("http")},9023:e=>{e.exports=require("util")},9278:e=>{e.exports=require("net")},9896:e=>{e.exports=require("fs")}},o={};function n(e){var s=o[e];if(void 0!==s)return s.exports;var t=o[e]={id:e,loaded:!1,exports:{}};return r[e].call(t.exports,t,t.exports,n),t.loaded=!0,t.exports}return n.m=r,n.x=()=>{var e=n.O(void 0,[804],(()=>n(3855)));return n.O(e)},e=[],n.O=(s,t,r,o)=>{if(!t){var i=1/0;for(h=0;h<e.length;h++){for(var[t,r,o]=e[h],a=!0,d=0;d<t.length;d++)(!1&o||i>=o)&&Object.keys(n.O).every((e=>n.O[e](t[d])))?t.splice(d--,1):(a=!1,o<i&&(i=o));if(a){e.splice(h--,1);var l=r();void 0!==l&&(s=l)}}return s}o=o||0;for(var h=e.length;h>0&&e[h-1][2]>o;h--)e[h]=e[h-1];e[h]=[t,r,o]},n.n=e=>{var s=e&&e.__esModule?()=>e.default:()=>e;return n.d(s,{a:s}),s},n.d=(e,s)=>{for(var t in s)n.o(s,t)&&!n.o(e,t)&&Object.defineProperty(e,t,{enumerable:!0,get:s[t]})},n.f={},n.e=e=>Promise.all(Object.keys(n.f).reduce(((s,t)=>(n.f[t](e,s),s)),[])),n.u=e=>"shared.js",n.o=(e,s)=>Object.prototype.hasOwnProperty.call(e,s),n.nmd=e=>(e.paths=[],e.children||(e.children=[]),e),n.j=942,t={942:1},n.O.require=e=>t[e],n.f.require=(e,s)=>{t[e]||(e=>{var s=e.modules,r=e.ids,o=e.runtime;for(var i in s)n.o(s,i)&&(n.m[i]=s[i]);o&&o(n);for(var a=0;a<r.length;a++)t[r[a]]=1;n.O()})(require("./"+n.u(e)))},s=n.x,n.x=()=>(n.e(804),s()),n.x()})()));
@@ -1 +0,0 @@
1
- !function(e,s){if("object"==typeof exports&&"object"==typeof module)module.exports=s();else if("function"==typeof define&&define.amd)define([],s);else{var t=s();for(var r in t)("object"==typeof exports?exports:e)[r]=t[r]}}(this,(()=>(()=>{"use strict";var e,s,t,r={181:e=>{e.exports=require("buffer")},290:e=>{e.exports=require("async_hooks")},1140:(e,s,t)=>{var r=t(3299),o=t(1275),i=t.n(o),n=t(8611),a=t.n(n),d=t(6982),l=t(6619),p=t.n(l),c=t(1266);function h(e,s,t){return s in e?Object.defineProperty(e,s,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[s]=t,e}class u{constructor(){h(this,"onmessage",void 0),h(this,"onerror",void 0),h(this,"onclose",void 0)}}var g=t(993);const T=require("./headers.js");function S(e,s,t){return s in e?Object.defineProperty(e,s,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[s]=t,e}class f extends u{async start(){if(this._started)throw new Error("Transport already started");this._started=!0}async close(){this._singleResponseCollectors?.forEach((e=>{e.res.headersSent||e.res.writeHead(503).end(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Service unavailable: Server shutting down"},id:null}))})),this._singleResponseCollectors?.clear(),this._requestToCollectorMapping?.clear()}async send(e){const s=e.id;if(null==s)return void(this.debug&&console.log("[StatelessHTTP] Dropping notification without request ID"));const t=this._requestToCollectorMapping?.get(s);if(t){const r=this._singleResponseCollectors?.get(t);if(r&&(void 0!==e.result||void 0!==e.error)&&(r.responses.push(e),r.requestIds.delete(s),0===r.requestIds.size)){const e={"Content-Type":"application/json"},s=1===r.responses.length?r.responses[0]:r.responses;r.res.writeHead(200,e).end(JSON.stringify(s)),this._singleResponseCollectors?.delete(t);for(const e of r.responses)void 0!==e.id&&null!==e.id&&this._requestToCollectorMapping?.delete(e.id)}}}async handleRequest(e,s,t){"POST"===e.method?await this.handlePOST(e,s,t):s.writeHead(405).end(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}))}async handlePOST(e,s,t){try{const r=e.headers.accept,o=r?.includes("application/json");if(!o)return void s.writeHead(406).end(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Not Acceptable: Client must accept application/json"},id:null}));let i;if(void 0!==t)i=t;else{const t=e.headers["content-type"];if(!t||!t.includes("application/json"))return void s.writeHead(415).end(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Unsupported Media Type: Content-Type must be application/json"},id:null}));const r=c.parse(t),o=await p()(e,{limit:this.bodySizeLimit,encoding:r.parameters.charset??"utf-8"});i=JSON.parse(o.toString())}const n=Array.isArray(i)?i:[i];if(!n.some((e=>e.method&&void 0!==e.id)))return void s.writeHead(202).end();const a=n.filter((e=>e.method&&void 0!==e.id)).map((e=>e.id));if(0===a.length)return void s.writeHead(202).end();const l=[],h=a.length,u=(0,d.randomUUID)();this._singleResponseCollectors=this._singleResponseCollectors||new Map,this._singleResponseCollectors.set(u,{res:s,requestIds:new Set(a),responses:l,expectedCount:h});for(const e of a)this._requestToCollectorMapping=this._requestToCollectorMapping||new Map,this._requestToCollectorMapping.set(e,u);for(const e of n)this.onmessage&&this.onmessage(e)}catch(e){s.writeHead(400).end(JSON.stringify({jsonrpc:"2.0",error:{code:-32700,message:"Parse error",data:String(e)},id:null}))}}constructor(e,s){super(),S(this,"debug",void 0),S(this,"bodySizeLimit",void 0),S(this,"_started",!1),S(this,"_singleResponseCollectors",new Map),S(this,"_requestToCollectorMapping",new Map),this.debug=e,this.bodySizeLimit=s}}class v{log(e,...s){this.debug&&console.log(`[StatelessHTTP] ${e}`,...s)}setupMiddleware(e){this.app.use(((e,s,t)=>{const r=this.corsOptions;void 0!==r.origin&&s.setHeader("Access-Control-Allow-Origin",Array.isArray(r.origin)?r.origin.join(","):String(r.origin)),void 0!==r.methods&&s.setHeader("Access-Control-Allow-Methods",Array.isArray(r.methods)?r.methods.join(","):String(r.methods)),void 0!==r.allowedHeaders&&s.setHeader("Access-Control-Allow-Headers",Array.isArray(r.allowedHeaders)?r.allowedHeaders.join(","):String(r.allowedHeaders)),void 0!==r.exposedHeaders&&s.setHeader("Access-Control-Expose-Headers",Array.isArray(r.exposedHeaders)?r.exposedHeaders.join(","):String(r.exposedHeaders)),"boolean"==typeof r.credentials&&s.setHeader("Access-Control-Allow-Credentials",String(r.credentials)),"number"==typeof r.maxAge&&s.setHeader("Access-Control-Max-Age",String(r.maxAge)),"OPTIONS"!==e.method?t():s.sendStatus(200)})),this.app.use(i().json({limit:e})),this.app.use(((e,s,t)=>{this.log(`${e.method} ${e.path} - New isolated request`),t()}))}setupRoutes(){this.app.get("/health",((e,s)=>{s.status(200).json({status:"ok",transport:"streamable-http",mode:"stateless"})})),this.app.get("/",((e,s)=>{s.send((0,g.A)(this.endpoint))})),this.middleware&&(this.app.use(this.middleware),this.app.use(((e,s,t)=>{(0,T.setHeaders)(e),t()}))),this.app.use(this.endpoint,(async(e,s)=>{await this.handleStatelessRequest(e,s)}))}async handleStatelessRequest(e,s){try{const t=await this.createServerFn(),r=new f(this.debug,this.options.bodySizeLimit||"10mb");s.on("close",(()=>{this.debug&&console.log("[StatelessHTTP] Request closed, cleaning up"),r.close(),t.close()})),await t.connect(r),await r.handleRequest(e,s,e.body)}catch(e){console.error("[StatelessHTTP] Error handling MCP request:",e),s.headersSent||s.status(500).json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:null})}}start(){const e=this.options.bindToLocalhost?"127.0.0.1":"0.0.0.0";this.server.listen(this.port,e,(()=>{console.log(`[StatelessHTTP] MCP Server running with Stateless HTTP transport on http://${e}:${this.port}`),console.log(`[StatelessHTTP] - MCP endpoint: http://${e}:${this.port}${this.endpoint}`),console.log("[StatelessHTTP] - POST only, per-request isolation, no sessions"),this.debug&&console.log("[StatelessHTTP] Debug mode: enabled"),this.setupShutdownHandlers()}))}setupShutdownHandlers(){process.on("SIGINT",this.shutdown.bind(this)),process.on("SIGTERM",this.shutdown.bind(this))}shutdown(){this.log("Shutting down server"),this.server.close(),process.exit(0)}constructor(e,s={},t={},r){S(this,"app",void 0),S(this,"server",void 0),S(this,"port",void 0),S(this,"endpoint",void 0),S(this,"debug",void 0),S(this,"options",void 0),S(this,"createServerFn",void 0),S(this,"corsOptions",void 0),S(this,"middleware",void 0),this.options={bindToLocalhost:!0,...s},this.app=i()(),this.server=a().createServer(this.app),this.port=s.port??parseInt(process.env.PORT||"3001",10),this.endpoint=s.endpoint??"/mcp",this.debug=s.debug??!1,this.createServerFn=e,this.corsOptions=t,this.middleware=r,this.setupMiddleware(s.bodySizeLimit||"10mb"),this.setupRoutes()}}const m=STREAMABLE_HTTP_PORT,y=STREAMABLE_HTTP_DEBUG,w=STREAMABLE_HTTP_BODY_SIZE_LIMIT,A=STREAMABLE_HTTP_ENDPOINT,_=STREAMABLE_HTTP_STATELESS,H=INJECTED_MIDDLEWARE,b=STREAMABLE_HTTP_CORS_ORIGIN,E=STREAMABLE_HTTP_CORS_METHODS,O=STREAMABLE_HTTP_CORS_ALLOWED_HEADERS,x=STREAMABLE_HTTP_CORS_EXPOSED_HEADERS,R=STREAMABLE_HTTP_CORS_CREDENTIALS,q=STREAMABLE_HTTP_CORS_MAX_AGE;!async function(){const e={port:m,debug:y,bodySizeLimit:w,endpoint:A,stateless:_},s={origin:b,methods:E,allowedHeaders:O,exposedHeaders:x,credentials:R,maxAge:q};let t;if(H){const e=await H();if(!e||!e.default||"function"!=typeof e.default)throw new Error("Middleware module does not export a default RequestHandler");t=e.default}new v(r.s,e,s,t).start()}()},2018:e=>{e.exports=require("tty")},2203:e=>{e.exports=require("stream")},3106:e=>{e.exports=require("zlib")},3193:e=>{e.exports=require("string_decoder")},3480:e=>{e.exports=require("querystring")},4434:e=>{e.exports=require("events")},6928:e=>{e.exports=require("path")},6982:e=>{e.exports=require("crypto")},7016:e=>{e.exports=require("url")},8611:e=>{e.exports=require("http")},9023:e=>{e.exports=require("util")},9278:e=>{e.exports=require("net")},9896:e=>{e.exports=require("fs")}},o={};function i(e){var s=o[e];if(void 0!==s)return s.exports;var t=o[e]={id:e,loaded:!1,exports:{}};return r[e].call(t.exports,t,t.exports,i),t.loaded=!0,t.exports}return i.m=r,i.x=()=>{var e=i.O(void 0,[804],(()=>i(1140)));return i.O(e)},e=[],i.O=(s,t,r,o)=>{if(!t){var n=1/0;for(p=0;p<e.length;p++){for(var[t,r,o]=e[p],a=!0,d=0;d<t.length;d++)(!1&o||n>=o)&&Object.keys(i.O).every((e=>i.O[e](t[d])))?t.splice(d--,1):(a=!1,o<n&&(n=o));if(a){e.splice(p--,1);var l=r();void 0!==l&&(s=l)}}return s}o=o||0;for(var p=e.length;p>0&&e[p-1][2]>o;p--)e[p]=e[p-1];e[p]=[t,r,o]},i.n=e=>{var s=e&&e.__esModule?()=>e.default:()=>e;return i.d(s,{a:s}),s},i.d=(e,s)=>{for(var t in s)i.o(s,t)&&!i.o(e,t)&&Object.defineProperty(e,t,{enumerable:!0,get:s[t]})},i.f={},i.e=e=>Promise.all(Object.keys(i.f).reduce(((s,t)=>(i.f[t](e,s),s)),[])),i.u=e=>"shared.js",i.o=(e,s)=>Object.prototype.hasOwnProperty.call(e,s),i.nmd=e=>(e.paths=[],e.children||(e.children=[]),e),i.j=368,t={368:1},i.O.require=e=>t[e],i.f.require=(e,s)=>{t[e]||(e=>{var s=e.modules,r=e.ids,o=e.runtime;for(var n in s)i.o(s,n)&&(i.m[n]=s[n]);o&&o(i);for(var a=0;a<r.length;a++)t[r[a]]=1;i.O()})(require("./"+i.u(e)))},s=i.x,i.x=()=>(i.e(804),s()),i.x()})()));