{"record":{"id":"b189546180e19cb0","repo":"yikart/AiToEarn","slug":"32001","errorCode":"-32001","errorMessage":"Session not found","messagePattern":"Session not found","errorType":"http","errorClass":null,"httpStatus":404,"severity":"error","filePath":"project/aitoearn-backend/libs/nest-mcp/src/services/mcp-streamable-http.service.ts","lineNumber":276,"sourceCode":"        },\n      })\n\n      // Connect transport to server\n      await mcpServer.connect(transport)\n\n      // Handle the initialization request\n      await transport.handleRequest(req.raw, res.raw, body)\n\n      this.logger.log(`[${transport.sessionId}] New session initialized`)\n      return\n    }\n\n    // Case 2: Request with session ID\n    if (sessionId) {\n      // Check if session exists\n      if (!this.transports[sessionId]) {\n        this.logger.debug(`[${sessionId}] Session not found`)\n        res.status(404).json({\n          jsonrpc: '2.0',\n          error: {\n            code: -32001,\n            message: 'Session not found',\n          },\n          id: null,\n        })\n        return\n      }\n\n      // Reject re-initialization attempts\n      if (this.isInitializeRequest(body)) {\n        res.status(400).json({\n          jsonrpc: '2.0',\n          error: {\n            code: -32600,\n            message: 'Invalid Request: Server already initialized',\n          },","sourceCodeStart":258,"sourceCodeEnd":294,"githubUrl":"https://github.com/yikart/AiToEarn/blob/d3aa8bea5b146a8675607cf0144d891aad3e9683/project/aitoearn-backend/libs/nest-mcp/src/services/mcp-streamable-http.service.ts#L258-L294","documentation":"The client supplied an Mcp-Session-Id header but no matching transport exists in the server's in-memory `transports` map, so the server replies 404 with JSON-RPC -32001 'Session not found'. The session was either never created on this server instance or was evicted/expired.","triggerScenarios":"POSTing with an Mcp-Session-Id that the current server instance never issued: after server restart, against a different replica behind a load balancer, after the transport was closed/deleted, or a typo'd/stale session id from an old client run.","commonSituations":"Stateful deployments scaled horizontally without sticky sessions, server restarted mid-conversation while the client kept its old session id, session TTL/cleanup deleting idle transports, or pointing a saved session id at the stateless endpoint.","solutions":["Re-run the initialize handshake to obtain a fresh Mcp-Session-Id and retry the request with it.","If running multiple instances, enable sticky sessions (session affinity) at the load balancer or back the transport map with a shared store.","Confirm you are hitting the stateful endpoint, not the stateless one, and that the server wasn't restarted between initialize and this call.","Add client logic: on 404 'Session not found', transparently re-initialize and replay the request."],"exampleFix":"// before\nconst res = await post(url, body, { headers: { 'mcp-session-id': savedId } })\n// after\nlet res = await post(url, body, { headers: { 'mcp-session-id': savedId } })\nif (res.status === 404) {\n  savedId = await initialize(url)\n  res = await post(url, body, { headers: { 'mcp-session-id': savedId } })\n}","handlingStrategy":"retry","validationCode":"const sid = getSessionId()\nif (!sid || sidExpiresBefore(Date.now())) {\n  await reinitialize() // obtain fresh Mcp-Session-Id before calling\n}","typeGuard":"function hasSessionId(headers: Record<string, string | undefined>): headers is Record<string, string> & { 'mcp-session-id': string } {\n  return typeof headers['mcp-session-id'] === 'string' && headers['mcp-session-id'].length > 0\n}","tryCatchPattern":"const res = await post(url, body, sessionHeaders)\nif (res.status === 404 && (await res.clone().json())?.error?.message === 'Session not found') {\n  sessionId = await initialize(url) // re-handshake then retry once\n  return post(url, body, sessionHeaders)\n}","preventionTips":["Configure sticky sessions when running multiple server instances.","Re-initialize after any server restart instead of reusing cached session ids.","Wrap all session-bound calls with automatic re-initialize-and-retry on 404.","Keep session ids only in memory of the same process that created them."],"tags":["session","http-404","stateful","mcp"],"backgroundTag":"mcp-session-not-found","analyzedSha":"d3aa8bea5b146a8675607cf0144d891aad3e9683","analyzedAt":"2026-08-31T14:19:24.185Z","schemaVersion":2},"datasetVersion":"2026-08-31T19:17:28.585Z"}