{"record":{"id":"2741aaa37e666fcf","repo":"linshenkx/prompt-optimizer","slug":"32000","errorCode":"-32000","errorMessage":"Bad Request: No valid session ID provided","messagePattern":"Bad Request: No valid session ID provided","errorType":"http","errorClass":null,"httpStatus":400,"severity":"error","filePath":"packages/mcp-server/src/index.ts","lineNumber":424,"sourceCode":"            enableDnsRebindingProtection: false\n          });\n\n          // 清理传输实例\n          httpTransport.onclose = () => {\n            if (httpTransport.sessionId) {\n              delete transports[httpTransport.sessionId];\n            }\n          };\n\n          // 为每个会话创建独立的服务器实例\n          const { server } = await createServerInstance(config);\n          await setupServerHandlers(server, coreServices);\n\n          // 连接到 MCP 服务器\n          await server.connect(httpTransport);\n        } else {\n          // 无效请求\n          res.status(400).json({\n            jsonrpc: '2.0',\n            error: {\n              code: -32000,\n              message: 'Bad Request: No valid session ID provided',\n            },\n            id: null,\n          });\n          return;\n        }\n\n        // 处理请求\n        await httpTransport.handleRequest(req, res, req.body);\n      });\n\n      // 处理 GET 请求（服务器到客户端通知，通过 SSE）\n      app.get('/mcp', async (req, res) => {\n        const sessionId = req.headers['mcp-session-id'] as string | undefined;\n        if (!sessionId || !transports[sessionId]) {","sourceCodeStart":406,"sourceCodeEnd":442,"githubUrl":"https://github.com/linshenkx/prompt-optimizer/blob/3e677b1d9f7e0493c142c175560531e7ae786dce/packages/mcp-server/src/index.ts#L406-L442","documentation":"This JSON-RPC error (code -32000) is returned as HTTP 400 by the MCP server's POST /mcp handler when the request is neither a valid InitializeRequest nor carries a known mcp-session-id. It mirrors the Streamable HTTP transport's requirement that all non-initialize requests reference an existing session.","triggerScenarios":"POST /mcp without an mcp-session-id header and with a body that is not a valid initialize request (e.g. a tools/call sent before initialize, a malformed initialize, or a client that lost/never stored the session ID).","commonSituations":"MCP client (Claude Desktop, Cursor, custom SDK client) reconnecting after a server restart — the old session ID is gone from the in-memory transports map; clients that skip the initialize handshake; proxies stripping the mcp-session-id header.","solutions":["Make the client perform the initialize handshake first and cache the mcp-session-id header returned by the server, sending it on every subsequent request.","If the server restarted (sessions are in-memory), have the client re-initialize on 400/-32000 and retry.","If a proxy/gateway sits in front, verify it forwards the mcp-session-id request and response headers."],"exampleFix":"// before\nawait fetch(MCP_URL + '/mcp', { method: 'POST', body: JSON.stringify({ method: 'tools/list' }) })\n// after\nconst init = await fetch(MCP_URL + '/mcp', { method: 'POST', body: JSON.stringify(initRequest) })\nconst sessionId = init.headers.get('mcp-session-id')\nawait fetch(MCP_URL + '/mcp', { method: 'POST', headers: { 'mcp-session-id': sessionId }, body: JSON.stringify({ method: 'tools/list' }) })","handlingStrategy":"retry","validationCode":"if (!sessionId) {\n  const initRes = await fetch(MCP_URL + '/mcp', {\n    method: 'POST',\n    headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' },\n    body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-03-26', capabilities: {}, clientInfo: { name: 'my-client', version: '1.0.0' } } })\n  })\n  sessionId = initRes.headers.get('mcp-session-id')\n}","typeGuard":"const isNoSessionError = (body: any): boolean =>\n  body?.error?.code === -32000 && /No valid session ID/.test(body?.error?.message ?? '')","tryCatchPattern":"try { await postRpc(method, params) } catch (e) { if (isNoSessionError(e)) { await reinitialize(); await postRpc(method, params) } else throw e }","preventionTips":["Always complete the initialize handshake before other RPCs and persist the returned mcp-session-id.","Re-initialize and retry automatically when a 400/-32000 is received (e.g. after server restart).","Verify proxies forward the mcp-session-id header both ways."],"tags":["mcp","json-rpc","session","http","handshake"],"backgroundTag":"mcp-session-id-invalid","analyzedSha":"3e677b1d9f7e0493c142c175560531e7ae786dce","analyzedAt":"2026-08-27T21:29:16.709Z","schemaVersion":2},"datasetVersion":"2026-08-28T00:17:15.603Z"}