Skip to content

fix: support newline-delimited JSON-RPC — Claude Code's actual MCP transport#89

Merged
EtanHey merged 1 commit into
mainfrom
fix/brainbar-newline-json
Mar 18, 2026
Merged

fix: support newline-delimited JSON-RPC — Claude Code's actual MCP transport#89
EtanHey merged 1 commit into
mainfrom
fix/brainbar-newline-json

Conversation

@EtanHey
Copy link
Copy Markdown
Owner

@EtanHey EtanHey commented Mar 18, 2026

Summary

  • Root cause: Claude Code v2.1+ (MCP protocol 2025-11-25) sends newline-delimited JSON-RPC ({json}\n), NOT Content-Length framing. BrainBar always responded with Content-Length: N\r\n\r\n{json}, which Claude Code's line-delimited reader couldn't parse — causing silent disconnect after initialize.
  • Auto-detects client framing mode from the first message: Content-Length header → CL responses; raw JSON+newline → newline responses
  • Per-client tracking via MCPFraming.lastExtractUsedContentLength and ClientState.usesContentLengthFraming
  • Adds file-based debug logging to /tmp/brainbar-debug.log

Evidence

Debug log from real Claude Code v2.1.78 session:

RECV fd=7 (207 bytes)
  HEX: 7b 22 6d 65 74 68 6f 64 22 3a ...  7d 0a
  TEXT: {"method":"initialize",...}\n

No Content-Length: header — bare JSON with trailing \n.

After fix:

EXTRACTED 1 messages (framing=newline-json)
  SENT response for method=initialize
EXTRACTED 2 messages (framing=newline-json)
  notifications/initialized (notification)
  SENT response for method=tools/list

Full handshake completes successfully.

Test plan

  • Real Claude Code v2.1.78 session completes full MCP handshake
  • Content-Length framing still works (backwards compat with socat/older clients)
  • swift build -c release clean
  • Binary deployed and verified

🤖 Generated with Claude Code

Summary by CodeRabbit

Release Notes

  • New Features

    • Implemented dual message framing support, enabling both Content-Length and newline-delimited JSON formats for improved flexibility.
  • Improvements

    • Enhanced debugging infrastructure with comprehensive per-process logging and verbose message tracking for better troubleshooting.

…sport

ROOT CAUSE: Claude Code v2.1+ (MCP protocol 2025-11-25) sends
newline-delimited JSON-RPC ({json}\n), not Content-Length framing.
BrainBar always responded with Content-Length headers, which Claude
Code's line-delimited reader couldn't parse — causing silent
disconnect after the first initialize.

Fix: auto-detect client framing mode from the first message.
- Content-Length header present → respond with Content-Length framing
- Raw JSON with newline → respond with JSON + newline (no headers)

Per-client tracking via MCPFraming.lastExtractUsedContentLength flag
and ClientState.usesContentLengthFraming.

Also adds file-based debug logging to /tmp/brainbar-debug.log for
future diagnosis.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Copy link
Copy Markdown

@greptile-apps greptile-apps Bot left a comment

Choose a reason for hiding this comment

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

Your free trial has ended. If you'd like to continue receiving code reviews, you can add a payment method here.

@EtanHey
Copy link
Copy Markdown
Owner Author

EtanHey commented Mar 18, 2026

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Mar 18, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Mar 18, 2026

Warning

Rate limit exceeded

@EtanHey has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 15 minutes and 11 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 1f4dc247-b657-476b-892d-5f986e6dcd45

📥 Commits

Reviewing files that changed from the base of the PR and between 37b42d0 and 237cad8.

📒 Files selected for processing (2)
  • brain-bar/Sources/BrainBar/BrainBarServer.swift
  • brain-bar/Sources/BrainBar/MCPFraming.swift
📝 Walkthrough

Walkthrough

This PR enhances the MCP server with per-process debugging infrastructure and implements dual message framing support (content-length and newline-delimited JSON) with runtime detection. The changes introduce verbose logging for client connections and message processing, track framing mode per client, and conditionally encode responses based on detected framing format.

Changes

Cohort / File(s) Summary
Debug Logging Infrastructure
brain-bar/Sources/BrainBar/BrainBarServer.swift
Added debugLog and debugLogData utilities writing timestamped entries to /tmp/brainbar-debug.log. Integrated logging at server startup, client connections, message processing, data packet reception (RECV), and disconnect/error events.
Framing Mode Detection and Dual Format Support
brain-bar/Sources/BrainBar/BrainBarServer.swift, brain-bar/Sources/BrainBar/MCPFraming.swift
Extended ClientState with usesContentLengthFraming flag to track per-client framing mode. Updated sendResponse to conditionally apply MCP content-length framing or newline-delimited JSON based on flag. Added MCPFraming.bufferCount (computed property) and lastExtractUsedContentLength (tracked state) to expose buffer size and framing detection results for runtime mode determination.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Server as BrainBarServer
    participant MCPFraming
    
    Client->>Server: Send raw data packet
    Server->>Server: debugLog RECV packet
    Server->>MCPFraming: extractMessages()
    MCPFraming->>MCPFraming: Attempt Content-Length parse
    alt Content-Length succeeds
        MCPFraming->>MCPFraming: lastExtractUsedContentLength = true
        MCPFraming-->>Server: Return messages
    else Falls back to raw JSON
        MCPFraming->>MCPFraming: lastExtractUsedContentLength = false
        MCPFraming-->>Server: Return messages
    end
    Server->>Server: Update ClientState.usesContentLengthFraming
    Server->>Server: debugLog extracted messages + framing mode
    Server->>Server: Process message (method, id)
    Server->>Server: Generate response
    alt usesContentLengthFraming == true
        Server->>Server: Encode with Content-Length framing
    else
        Server->>Server: JSON encode + append newline
    end
    Server->>Client: Send response
    Server->>Server: debugLog response sent
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related PRs

Poem

🐰 A rabbit hops through framing modes,
Content-Length or newlines—both the roads!
With debug logs lighting the way,
Each packet's tracked night and day.
Dual formats dance, detection's keen,
The finest MCP flow you've seen!

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/brainbar-newline-json
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@EtanHey EtanHey merged commit 418630b into main Mar 18, 2026
4 checks passed
@EtanHey EtanHey deleted the fix/brainbar-newline-json branch March 18, 2026 00:47
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.

1 participant