{"record":{"id":"00d8decb586516f2","repo":"mastra-ai/mastra","slug":"bad-request-no-valid-session-id-provided-for-non","errorCode":null,"errorMessage":"Bad Request: No valid session ID provided for non-initialize request","messagePattern":"Bad Request: No valid session ID provided for non-initialize request","errorType":"http","errorClass":null,"httpStatus":400,"severity":"error","filePath":"packages/mcp/src/server/server.ts","lineNumber":2210,"sourceCode":"                // Also clean up the server instance for this session\n                if (this.httpServerInstances.has(closedSessionId)) {\n                  this.httpServerInstances.delete(closedSessionId);\n                  this.logger.debug('Cleaned up server instance for closed session', { sessionId: closedSessionId });\n                }\n              }\n            };\n\n            // Connect the new server instance to the new transport\n            await sessionServerInstance.connect(transport);\n\n            // Handle the initialize request. This assigns the session ID and\n            // triggers onsessioninitialized, which stores the transport and\n            // server instance for the session.\n            return await transport.handleRequest(req, res, body);\n          } else {\n            // POST request but not initialize, and no session ID\n            this.logger.warn('Received non-initialize POST request without session ID');\n            res.writeHead(400, { 'Content-Type': 'application/json' });\n            res.end(\n              JSON.stringify({\n                jsonrpc: '2.0',\n                error: {\n                  code: -32000,\n                  message: 'Bad Request: No valid session ID provided for non-initialize request',\n                },\n                id: (body as any)?.id ?? null, // Include original request ID if available\n              }),\n            );\n          }\n        } else {\n          // Non-POST request (GET/DELETE) without a session ID\n          this.logger.warn('Received request without session ID', { method: req.method });\n          res.writeHead(400, { 'Content-Type': 'application/json' });\n          res.end(\n            JSON.stringify({\n              jsonrpc: '2.0',","sourceCodeStart":2192,"sourceCodeEnd":2228,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/packages/mcp/src/server/server.ts#L2192-L2228","documentation":"For stateful Streamable HTTP, every POST other than the initial initialize request must carry a valid session id header. If a POST arrives without one, the server responds 400 with JSON-RPC code -32000 and message 'Bad Request: No valid session ID provided for non-initialize request', because it cannot route the message to any session transport.","triggerScenarios":"POSTing tools/call, notifications, or any non-initialize JSON-RPC message without the mcp-session-id header; using a hand-rolled HTTP client that never stores and replays the session id returned at initialize; proxy/gateway stripping the session header.","commonSituations":"Custom MCP clients built with fetch instead of the SDK; header-filtering middleware or CORS configurations dropping mcp-session-id; calling the endpoint directly (curl/Postman) after copying only an initialize example; stateless serverless callers hitting a stateful server.","solutions":["Send an initialize request first and echo the returned mcp-session-id header on every subsequent request","Use the official MCP SDK client transport, which manages the session id automatically","Check that proxies/middleware/CORS exposed headers preserve the mcp-session-id header","If you don't need sessions, run the server in stateless mode (serverless: true or sessionIdGenerator: undefined) where this requirement doesn't apply"],"exampleFix":"// before\nawait fetch('http://localhost:4111/mcp', { method: 'POST', body: rpc }); // no session header\n// after\nconst init = await fetch(url, { method: 'POST', headers: jsonHeaders, body: initRpc });\nconst sessionId = init.headers.get('mcp-session-id');\nawait fetch(url, { method: 'POST', headers: { ...jsonHeaders, 'mcp-session-id': sessionId }, body: rpc });","handlingStrategy":"validation","validationCode":"function requireSessionHeader(headers, isInitialize) {\n  if (!isInitialize && !headers['mcp-session-id']) {\n    throw new Error('Non-initialize MCP requests must include the mcp-session-id header');\n  }\n}","typeGuard":null,"tryCatchPattern":"if (res.status === 400) {\n  const body = await res.json();\n  if (body?.error?.code === -32000 && String(body.error.message).includes('session ID')) {\n    // re-run initialize, capture mcp-session-id, then retry the request\n  }\n}","preventionTips":["Always perform initialize first and propagate the returned mcp-session-id to every request","Prefer the official MCP SDK client transport over hand-rolled fetch calls","Ensure CORS exposedHeaders and proxy configs preserve the mcp-session-id header","Use stateless/serverless mode on the server if clients cannot maintain sessions"],"tags":["mcp","http","session","bad-request","headers"],"backgroundTag":"missing-session-id","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T08:17:16.595Z"}