DEV Community

nmorestd
nmorestd

Posted on

5 Real Bugs We Fixed Hardening a Zero-Dependency Node.js MCP Client

While building a zero-dependency Node.js client for the OpenAgentForum Streamable HTTP MCP endpoint (https://openagentforum.com/mcp), five subtle transport and protocol bugs surfaced during code review and live testing.

Here is what broke in practice and how to fix each one cleanly using only built-in node:http / node:https.

1. data += chunk Corrupts Multibyte UTF-8 Across TCP Chunks

Reading an http.IncomingMessage with let data = ""; res.on("data", chunk => { data += chunk; }) calls Buffer.prototype.toString() on each chunk independently. If a 4-byte emoji or Cyrillic character is split across two TCP packets, both halves turn into U+FFFD (``).

Fix: Collect raw Buffer chunks with a hard byte cap, then decode once at end:

`js
const chunks = [];
let totalBytes = 0;

res.on("data", (chunk) => {
totalBytes += chunk.length;
if (totalBytes > this.maxBytes) {
req.destroy();
return done(new Error(Response exceeded maximum size of ${this.maxBytes} bytes));
}
chunks.push(chunk);
});

res.on("end", () => {
const bodyText = Buffer.concat(chunks).toString("utf8");
// ...
});
`

2. Fragile SSE Regex Breaks on CRLF, id:, and Keepalives

Production Streamable HTTP MCP servers respond with content-type: text/event-stream. A naive /^event:\s*message\s*\ndata:\s*/ regex breaks on \r\n\r\n frame separators, id: lines, multi-line data: blocks, or non-JSON keepalive events.

Fix: Split frames on /\r?\n\r?\n/, join data: lines per frame, skip non-JSON keepalives, and match the JSON-RPC id:

`js
for (const ev of parseSseEvents(bodyText)) {
let candidate = null;
try {
candidate = JSON.parse(ev.data);
} catch {
continue; // skip keepalives or non-JSON comments
}
if (candidate && candidate.id === reqId) {
msg = candidate;
break;
}
}
`

3. Socket Idle Timeout Is Not a Request Deadline

Node's timeout option on http.request only fires on socket inactivity. A slow-drip server sending 1 byte per second keeps the socket alive indefinitely. Always pair it with an explicit setTimeout(() => req.destroy(), this.timeoutMs) deadline cleared on completion.

4. Verify protocolVersion, notifications/initialized, and isError

  • Check that the server's negotiated result.protocolVersion matches your expected version (e.g. 2025-11-25) and result.capabilities.tools is present.
  • Send notifications/initialized and handle 202 Accepted empty bodies.
  • Surface MCP tool-level failures (result.isError === true) instead of returning them as silent successes.

5. Pin Allowed Endpoints & Tool Allowlists

When connecting to untrusted public MCP servers, pin the allowed origin/loopback fixture and enforce an explicit tool allowlist before tools/call, and never echo raw upstream response bodies in thrown error messages.


If you want your AI coding agent to automatically audit and harden MCP clients/servers or write deterministic loopback regression tests, check out my skills on Agensi.

Top comments (0)