Skip to content

handlePostMessage fails when reqBody is not passed #223

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Rajesh-Narayanappa87 opened this issue Mar 26, 2025 · 3 comments
Closed

handlePostMessage fails when reqBody is not passed #223

Rajesh-Narayanappa87 opened this issue Mar 26, 2025 · 3 comments
Labels
bug Something isn't working

Comments

@Rajesh-Narayanappa87
Copy link

Describe the bug
When creating mcp using SSE server, await transport.handlePostMessage(req, res); expects reqbody. Not providing is failing run

Machine config:
Tried with node 20 and 22.
Mac M3
@modelcontextprotocol/sdk - 1.7.0

To Reproduce
Steps to reproduce the behavior:

  1. Run node index.js to run mcp server
  2. Run node client.js to run mcp client

index.js


  // Create an MCP server
  const server = new McpServer({
    name: "Demo",
    version: "1.0.0",
    });
  
  // Add an addition tool
  server.tool("add", { a: z.number(), b: z.number() }, async ({ a, b}) => ({
    content: [{ type: "text", text: String(a + b) }],
  }));
  
  
  const axiosInstance = axios.create({
      httpsAgent: new https.Agent({
        rejectUnauthorized: false,
      }),
    });
  
  server.tool("pullTestResults", { a: z.number() }, async ({ a }) => {
    let result = await axiosInstance.get(`https://xyz/test-case/api-result?count=${a}`);
    return {
      content: [{ type: "text", text: JSON.stringify(result.data) }],
    };
  });
  
  
  const app = express();
  app.use(express.json());
  
  const transports = {};


  app.get("/sse", async (req, res) => {
    const transport = new SSEServerTransport('/messages', res);
    transports[transport.sessionId] = transport;
    res.on("close", () => {
      delete transports[transport.sessionId];
    });
    await server.connect(transport);
  });
  
  app.post("/messages", async (req, res) => {
    const sessionId = req.query.sessionId;
    const transport = transports[sessionId];
    if (transport) {
      await transport.handlePostMessage(req, res);
    } else {
      res.status(400).send('No transport found for sessionId');
    }
  });
  
  const port = 3000;
  app.listen(port, () => {
    console.log(`HTTP server listening on port ${port}`);
  });

client.js


// Create an MCP client
const client = new Client(
    {
  name: "DemoClient",
  version: "1.0.0"
    },
    {
        capabilities: {}
      }
);

const transport = new SSEClientTransport(new URL(`http://localhost:3000/sse`));

// Connect to the server using stdio transport
await client.connect(transport);

const tools = await client.listTools();

console.log(tools)


const resp = await client.callTool({
    name: "pullTestResults",
    arguments: {
      a: "2024-12-04_18-13-21-190087751"
    }
  })

  console.log(resp)

Issue exist in both client or api way.

Api way

curl --location 'http://localhost:3000/messages?sessionId=40652e8f-2633-40b8-98f8-5258fbbcb06a' \
--header 'Content-Type: application/json' \
--data '{
        "jsonrpc": "2.0",
        "id": "a29ba38d-fed4-49f0-bbba-6c8b1f4606c9",
        "method": "tools/call",
        "params": {
            "name": "pullTestResults",
            "arguments": {
                "a": "2024-12-04_18-13-21-190087751"
            }
        }
        
    }'

Expected behavior
List out tools and execute pullTestResults tool.

Logs

throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`);
                      ^

Error: Error POSTing to endpoint (HTTP 400): InternalServerError: stream is not readable

Workaround for this issue is to send reqbody to handlePostMessage function.

..... same as index.js
      await transport.handlePostMessage(req, res, req.body);
@Rajesh-Narayanappa87 Rajesh-Narayanappa87 added the bug Something isn't working label Mar 26, 2025
@Rajesh-Narayanappa87
Copy link
Author

Found problem.
Here is handlePostMessage implementation

 async handlePostMessage(req, res, parsedBody) {
        var _a, _b, _c;
        if (!this._sseResponse) {
            const message = "SSE connection not established";
            res.writeHead(500).end(message);
            throw new Error(message);
        }
        let body;
        try {
            const ct = contentType.parse((_a = req.headers["content-type"]) !== null && _a !== void 0 ? _a : "");
            if (ct.type !== "application/json") {
                throw new Error(`Unsupported content-type: ${ct}`);
            }
            body = parsedBody !== null && parsedBody !== void 0 ? parsedBody : await getRawBody(req, {
                limit: MAXIMUM_MESSAGE_SIZE,
                encoding: (_b = ct.parameters.charset) !== null && _b !== void 0 ? _b : "utf-8",
            });
        }
        catch (error) {
            res.writeHead(400).end(String(error));
            (_c = this.onerror) === null || _c === void 0 ? void 0 : _c.call(this, error);
            return;
        }
        try {
            await this.handleMessage(typeof body === 'string' ? JSON.parse(body) : body);
        }
        catch (_d) {
            res.writeHead(400).end(`Invalid message: ${body}`);
            return;
        }
        res.writeHead(202).end("Accepted");
    }

getRawBody expects buffer stream, since our case is json process throws error rightaway.
Actual json handling is done later after throwing error await this.handleMessage .

If dev confirms this is bug and not being looked upon, I can fix this quick

@Rajesh-Narayanappa87
Copy link
Author

Raised PR for above issue: #238

@jspahrsummers
Copy link
Member

This should be handled by removing all middleware on the /message endpoint (i.e., don't parse the body in advance).

@jspahrsummers jspahrsummers closed this as not planned Won't fix, can't repro, duplicate, stale Apr 7, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants