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
Parent Issue
See parent analysis report: #1006
Related to #1006
Generated by Duplicate Code Detector
Part of duplicate code analysis: #1006
Summary
Critical duplication found in
internal/mcp/connection.gowhere 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
internal/mcp/connection.golines 668-688 (initializeHTTPSessionmethod)internal/mcp/connection.golines 741-785 (sendHTTPRequestmethod)Code Sample - Pattern in initializeHTTPSession (lines 668-688):
Identical Pattern in sendHTTPRequest (lines 741-785):
The same exact logic structure is duplicated with only minor error message differences.
Impact Analysis
Refactoring Recommendations
1. Extract Unified Response Parser
Recommended implementation:
Usage in initializeHTTPSession (line 668):
Usage in sendHTTPRequest (line 741):
2. Add Unit Tests for Parser
Create dedicated tests for
parseHTTPResponse:Implementation Checklist
parseHTTPResponsehelper functioninitializeHTTPSessionto use helpersendHTTPRequestto use helperParent Issue
See parent analysis report: #1006
Related to #1006