Skip to content

Fix: JSON-RPC message loss when TCP reads contain heartbeats - #323

Open
bbdu3 wants to merge 4 commits into
modelcontextprotocol:mainfrom
bbdu3:fix/network-heartbeat-framing
Open

bbdu3 wants to merge 4 commits into
modelcontextprotocol:mainfrom
bbdu3:fix/network-heartbeat-framing

Conversation

@bbdu3

@bbdu3 bbdu3 commented Nov 6, 2026 •

Copy link
Copy Markdown

Summary

NetworkTransport previously skipped an entire receive chunk when it began with a heartbeat, discarding any following JSON-RPC messages. Parse buffered frames so the heartbeat is consumed without losing subsequent messages.

Fixes #322.

Changed

  • Move heartbeat detection into the buffered receive loop.
  • Consume only the complete 12-byte heartbeat, then continue processing remaining bytes.
  • Retain incomplete frames for the next read.
  • Add 14 parameterized regression cases covering coalesced heartbeats and messages, plus splits across the heartbeat and following JSON.
  • Preserve public APIs and the existing wire format.

Test

  • Python behavior-model checks: all 14 regression inputs fail under the original logic and pass under the revised logic. Additional fragmentation and control cases passed.
  • git diff --check passed.

Signed-off-by: bbdu3 <ergouyang854@gamil.com>
@bbdu3
bbdu3 requested a review from a team as a code owner November 6, 2026 06:10
bbdu3 and others added 2 commits November 9, 2026 10:36

@1AbdullahButt 1AbdullahButt left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I read this against Heartbeat.isHeartbeat and Heartbeat.from, and the loop is correct for every split:

  • isHeartbeat uses prefix(4) on the buffer, so it works on the Data slices that dropFirst and the newline split produce (no index-0 assumptions).
  • With 1–3 bytes of the magic header buffered, isHeartbeat is false, the newline search finds nothing and the loop breaks to wait for more data. With 4–11 bytes, the count >= 12 guard waits as well. The 0...13 cases cover both.
  • Consuming a fixed 12 bytes for the heartbeat also fixes a quieter problem: the old code could split on a 0x0A byte inside the 8-byte timestamp if a heartbeat ever landed in the buffer.

The marker message in the test is a nice touch: the test still ends on the old code instead of hanging.

Reviewed with help from Claude Code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

NetworkTransport drops a JSON message when a TCP receive contains a heartbeat followed by the message

2 participants