Skip to content

[duplicate-code] 🔍 Duplicate Code Pattern: JSON-RPC Response Parsing with SSE Fallback #1008

@github-actions

Description

@github-actions

Part of duplicate code analysis: #1006

Summary

Critical duplication found in internal/mcp/connection.go where JSON-RPC response parsing with SSE fallback logic is duplicated across two methods. This 118+ line duplication creates maintenance burden and bug synchronization risk in protocol-critical code.

Duplication Details

Pattern: Identical JSON-RPC + SSE Parsing Logic

  • Severity: CRITICAL
  • Occurrences: 2 instances (118+ total lines)
  • Locations:
    • internal/mcp/connection.go lines 668-688 (initializeHTTPSession method)
    • internal/mcp/connection.go lines 741-785 (sendHTTPRequest method)

Code Sample - Pattern in initializeHTTPSession (lines 668-688):

var rpcResponse Response
if err := json.Unmarshal(result.ResponseBody, &rpcResponse); err != nil {
    sseData, sseErr := parseSSEResponse(result.ResponseBody)
    if sseErr != nil {
        bodyPreview := string(result.ResponseBody)
        if len(bodyPreview) > 500 {
            bodyPreview = bodyPreview[:500] + "... (truncated)"
        }
        return "", fmt.Errorf("failed to parse initialize response: %w\nRaw body preview: %s\nSSE parse error: %v", 
            err, bodyPreview, sseErr)
    }
    if err := json.Unmarshal(sseData, &rpcResponse); err != nil {
        return "", fmt.Errorf("failed to parse JSON data extracted from SSE: %w\nSSE data: %s", 
            err, string(sseData))
    }
}

Identical Pattern in sendHTTPRequest (lines 741-785):

The same exact logic structure is duplicated with only minor error message differences.

Impact Analysis

  • Maintainability: CRITICAL - Any bug fix or enhancement must be applied in 2 places, risking inconsistencies
  • Bug Risk: HIGH - If SSE parsing logic has a bug, both locations need fixing. Missing one creates inconsistent behavior
  • Code Bloat: ~60 lines of duplicated parsing logic per instance
  • Protocol Reliability: Affects core MCP protocol communication - errors here impact all MCP operations

Refactoring Recommendations

1. Extract Unified Response Parser

Recommended implementation:

// Add to internal/mcp/connection.go or new internal/mcp/response_parser.go

// parseHTTPResponse parses an HTTP response body as JSON-RPC, with automatic
// fallback to SSE format if initial JSON parsing fails.
func parseHTTPResponse(body []byte, contextDescription string) (*Response, error) {
    var rpcResponse Response
    
    // Try direct JSON parsing first
    if err := json.Unmarshal(body, &rpcResponse); err != nil {
        // Fallback: try parsing as SSE
        sseData, sseErr := parseSSEResponse(body)
        if sseErr != nil {
            bodyPreview := string(body)
            if len(bodyPreview) > 500 {
                bodyPreview = bodyPreview[:500] + "... (truncated)"
            }
            return nil, fmt.Errorf("failed to parse %s response: %w\nRaw body preview: %s\nSSE parse error: %v",
                contextDescription, err, bodyPreview, sseErr)
        }
        
        // Try parsing the SSE-extracted data as JSON
        if err := json.Unmarshal(sseData, &rpcResponse); err != nil {
            return nil, fmt.Errorf("failed to parse JSON data extracted from SSE for %s: %w\nSSE data: %s",
                contextDescription, err, string(sseData))
        }
    }
    
    return &rpcResponse, nil
}

Usage in initializeHTTPSession (line 668):

rpcResponse, err := parseHTTPResponse(result.ResponseBody, "initialize")
if err != nil {
    return "", err
}

Usage in sendHTTPRequest (line 741):

rpcResponse, err := parseHTTPResponse(result.ResponseBody, "request")
if err != nil {
    return nil, err
}
  • Estimated effort: 2-3 hours (extract function, update callers, verify tests)
  • Benefits:
    • Single source of truth for response parsing
    • Easier to add logging/metrics
    • Consistent error messages
    • Reduced code by ~100 lines

2. Add Unit Tests for Parser

Create dedicated tests for parseHTTPResponse:

  • Test valid JSON-RPC response
  • Test SSE-wrapped response
  • Test invalid JSON with invalid SSE fallback
  • Test large response body truncation

Implementation Checklist

  • Review duplication findings with team
  • Create parseHTTPResponse helper function
  • Update initializeHTTPSession to use helper
  • Update sendHTTPRequest to use helper
  • Add unit tests for helper function
  • Verify all existing tests pass
  • Test with real MCP servers (stdio and HTTP)
  • Update any related documentation

Parent Issue

See parent analysis report: #1006
Related to #1006

Generated by Duplicate Code Detector

  • expires on Feb 24, 2026, 3:01 AM UTC

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions