@mastra/mcp 0.14.4 → 0.14.5-alpha.0

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/index.js CHANGED
@@ -2963,6 +2963,7 @@ Provided arguments: ${JSON.stringify(request.params.arguments, null, 2)}`
2963
2963
  * @param options.options.onsessioninitialized - Callback when a new session is initialized
2964
2964
  * @param options.options.enableJsonResponse - If true, return JSON instead of SSE streaming
2965
2965
  * @param options.options.eventStore - Event store for message resumability
2966
+ * @param options.options.serverless - If true, run in stateless mode without session management (ideal for serverless environments)
2966
2967
  *
2967
2968
  * @throws {MastraError} If HTTP connection setup fails
2968
2969
  *
@@ -2988,6 +2989,25 @@ Provided arguments: ${JSON.stringify(request.params.arguments, null, 2)}`
2988
2989
  *
2989
2990
  * httpServer.listen(1234);
2990
2991
  * ```
2992
+ *
2993
+ * @example Serverless mode (Cloudflare Workers, Vercel Edge, etc.)
2994
+ * ```typescript
2995
+ * export default {
2996
+ * async fetch(request: Request) {
2997
+ * const url = new URL(request.url);
2998
+ * if (url.pathname === '/mcp') {
2999
+ * await server.startHTTP({
3000
+ * url,
3001
+ * httpPath: '/mcp',
3002
+ * req: request,
3003
+ * res: response,
3004
+ * options: { serverless: true },
3005
+ * });
3006
+ * }
3007
+ * return new Response('Not found', { status: 404 });
3008
+ * },
3009
+ * };
3010
+ * ```
2991
3011
  */
2992
3012
  async startHTTP({
2993
3013
  url,
@@ -3003,6 +3023,12 @@ Provided arguments: ${JSON.stringify(request.params.arguments, null, 2)}`
3003
3023
  res.end();
3004
3024
  return;
3005
3025
  }
3026
+ const isStatelessMode = options?.serverless || options && "sessionIdGenerator" in options && options.sessionIdGenerator === void 0;
3027
+ if (isStatelessMode) {
3028
+ this.logger.debug("startHTTP: Running in stateless mode (serverless or sessionIdGenerator: undefined)");
3029
+ await this.handleServerlessRequest(req, res);
3030
+ return;
3031
+ }
3006
3032
  const mergedOptions = {
3007
3033
  sessionIdGenerator: () => randomUUID(),
3008
3034
  // default: enabled
@@ -3144,6 +3170,74 @@ Provided arguments: ${JSON.stringify(request.params.arguments, null, 2)}`
3144
3170
  }
3145
3171
  }
3146
3172
  }
3173
+ /**
3174
+ * Handles a stateless, serverless HTTP request without session management.
3175
+ *
3176
+ * This method bypasses all session/transport state and handles each request independently.
3177
+ * For serverless environments (Cloudflare Workers, Vercel Edge, etc.) where
3178
+ * persistent connections and session state cannot be maintained across requests.
3179
+ *
3180
+ * Each request gets a fresh transport and server instance that are discarded after the response.
3181
+ *
3182
+ * @param req - Incoming HTTP request
3183
+ * @param res - HTTP response object
3184
+ * @private
3185
+ */
3186
+ async handleServerlessRequest(req, res) {
3187
+ try {
3188
+ this.logger.debug(`handleServerlessRequest: Received ${req.method} request`);
3189
+ const body = req.method === "POST" ? await new Promise((resolve, reject) => {
3190
+ let data = "";
3191
+ req.on("data", (chunk) => data += chunk);
3192
+ req.on("end", () => {
3193
+ try {
3194
+ resolve(JSON.parse(data));
3195
+ } catch (e) {
3196
+ reject(new Error(`Invalid JSON in request body: ${e instanceof Error ? e.message : String(e)}`));
3197
+ }
3198
+ });
3199
+ req.on("error", reject);
3200
+ }) : void 0;
3201
+ this.logger.debug(`handleServerlessRequest: Processing ${req.method} request`, {
3202
+ method: body?.method,
3203
+ id: body?.id
3204
+ });
3205
+ const transientServer = this.createServerInstance();
3206
+ const tempTransport = new StreamableHTTPServerTransport({
3207
+ sessionIdGenerator: void 0,
3208
+ enableJsonResponse: true
3209
+ });
3210
+ await transientServer.connect(tempTransport);
3211
+ await tempTransport.handleRequest(req, res, body);
3212
+ this.logger.debug(`handleServerlessRequest: Completed ${body?.method} request`, { id: body?.id });
3213
+ } catch (error) {
3214
+ const mastraError = new MastraError(
3215
+ {
3216
+ id: "MCP_SERVER_SERVERLESS_REQUEST_FAILED",
3217
+ domain: ErrorDomain.MCP,
3218
+ category: ErrorCategory.USER,
3219
+ text: "Failed to handle serverless MCP request"
3220
+ },
3221
+ error
3222
+ );
3223
+ this.logger.trackException(mastraError);
3224
+ this.logger.error("handleServerlessRequest: Error handling request:", { error: mastraError });
3225
+ if (!res.headersSent) {
3226
+ res.writeHead(500, { "Content-Type": "application/json" });
3227
+ res.end(
3228
+ JSON.stringify({
3229
+ jsonrpc: "2.0",
3230
+ error: {
3231
+ code: -32603,
3232
+ message: "Internal server error",
3233
+ data: error instanceof Error ? error.message : String(error)
3234
+ },
3235
+ id: null
3236
+ })
3237
+ );
3238
+ }
3239
+ }
3240
+ }
3147
3241
  /**
3148
3242
  * Establishes the SSE connection for the MCP server.
3149
3243
  *