Skip to content

Conversation

Copy link
Contributor

Copilot AI commented Jan 20, 2026

Analysis identified 3 duplication patterns totaling ~80 lines. This PR eliminates patterns #1 and #2 (~70 lines), defers #3 as idiomatic Go.

Changes

Authorization Header Parsing

  • Centralized session extraction logic into auth.ExtractSessionID()
  • Removed duplicate 15-line parsing blocks from routed.go and transport.go
  • Preserves Bearer token whitespace trimming for backward compatibility

Before:

// Duplicated in routed.go and transport.go
authHeader := r.Header.Get("Authorization")
var sessionID string
if strings.HasPrefix(authHeader, "Bearer ") {
    sessionID = strings.TrimPrefix(authHeader, "Bearer ")
    sessionID = strings.TrimSpace(sessionID)
} else if authHeader != "" {
    sessionID = authHeader
}

After:

sessionID := auth.ExtractSessionID(r.Header.Get("Authorization"))

HTTP Transport Connection Boilerplate

  • Extracted common connect logic into trySDKTransport() with function parameter pattern
  • Reduced tryStreamableHTTPTransport and trySSETransport from ~27 lines each to ~9 lines
  • Simplifies future transport additions

Before:

func tryStreamableHTTPTransport(...) (*Connection, error) {
    client := newMCPClient()
    transport := &sdk.StreamableClientTransport{...}
    connectCtx, connectCancel := context.WithTimeout(ctx, 5*time.Second)
    defer connectCancel()
    session, err := client.Connect(connectCtx, transport, nil)
    // ... 15 more lines
}
// Nearly identical function for SSE transport

After:

func tryStreamableHTTPTransport(...) (*Connection, error) {
    return trySDKTransport(ctx, cancel, url, headers, httpClient,
        HTTPTransportStreamable, "streamable HTTP",
        func(url string, httpClient *http.Client) sdk.Transport {
            return &sdk.StreamableClientTransport{...}
        })
}

Error Wrapping Pattern

Evaluated 67 instances of fmt.Errorf("failed to %s: %w", ...) pattern. No changes - this is idiomatic Go where each error provides unique debugging context.

Warning

Firewall rules blocked me from connecting to one or more addresses (expand for details)

I tried to connect to the following addresses, but was blocked by firewall rules:

  • this-host-does-not-exist-12345.com
    • Triggering command: /tmp/go-build486373954/b278/mcp.test /tmp/go-build486373954/b278/mcp.test -test.testlogfile=/tmp/go-build486373954/b278/testlog.txt -test.paniconexit0 -test.timeout=10m0s -test.v=true go riter/tabwriter.-Wl,--no-gc-sections 64/pkg/tool/linu-fmessage-length=0 r (dns block)
    • Triggering command: /tmp/go-build3948523853/b001/mcp.test /tmp/go-build3948523853/b001/mcp.test -test.testlogfile=/tmp/go-build3948523853/b001/testlog.txt -test.paniconexit0 -test.timeout=10m0s -test.v=true ache/go/1.25.5/x64/src/runtime/c-errorsas .cfg x_amd64/link (dns block)

If you need me to access, download, or install something from one of these locations, you can either:

Original prompt

This section details on the original issue you should resolve

<issue_title>[duplicate-code] Duplicate Code Analysis Report - Commit 0ee0a71</issue_title>
<issue_description># 🔍 Duplicate Code Analysis Report

Analysis of commit 0ee0a71

Summary

This analysis identified 3 significant duplication patterns in the MCP Gateway codebase that impact maintainability and increase the risk of inconsistent updates across the codebase. The patterns span authorization handling, HTTP transport connection logic, and error handling, totaling approximately 80+ lines of duplicated code.

Detected Patterns

This analysis found 3 significant duplication patterns:

  1. Authorization Header Parsing - Severity: High - See sub-issue [duplicate-code] Duplicate Code Pattern: Authorization Header Parsing #352
  2. HTTP Transport Connection Boilerplate - Severity: Medium - See sub-issue [duplicate-code] Duplicate Code Pattern: HTTP Transport Connection Boilerplate #353
  3. Repeated Error Wrapping Pattern - Severity: Medium - See sub-issue [duplicate-code] Duplicate Code Pattern: Repeated Error Wrapping Pattern #354

Overall Impact

  • Total Duplicated Lines: ~80+ lines across multiple files
  • Affected Files: 5 core files (routed.go, transport.go, connection.go, config.go, launcher.go)
  • Maintainability Risk: High - Changes to authorization or connection logic require updates in multiple locations
  • Refactoring Priority: High - Authorization parsing should be refactored immediately to ensure consistent security handling

Next Steps

  1. Review individual pattern sub-issues for detailed analysis
  2. Prioritize refactoring based on severity and impact (start with authorization handling)
  3. Create implementation plan for highest priority patterns
  4. Extract shared utilities to reduce duplication

Analysis Metadata

  • Analyzed Files: 20+ Go files in internal/ directory
  • Detection Method: Direct code analysis with grep and pattern matching
  • Commit: 0ee0a71
  • Analysis Date: 2026-01-19
  • Excluded from Analysis: Test files (_test.go), workflow files (.github/workflows/), agent configs (.github/agents/*)</issue_description>

Comments on the Issue (you are @copilot in this section)


💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.

Copilot AI and others added 3 commits January 20, 2026 18:23
- Add ExtractSessionID function to internal/auth/header.go
- Update internal/server/auth.go to delegate to auth.ExtractSessionID
- Add comprehensive tests for ExtractSessionID
- Eliminates duplicate authorization parsing logic (Pattern #1 from issue #352)

Co-authored-by: lpcox <15877973+lpcox@users.noreply.github.com>
- Add generic trySDKTransport function to handle common connection logic
- Refactor tryStreamableHTTPTransport to use trySDKTransport
- Refactor trySSETransport to use trySDKTransport
- Reduces code duplication by ~40 lines (Pattern #2 from issue #353)

Co-authored-by: lpcox <15877973+lpcox@users.noreply.github.com>
Copilot AI changed the title [WIP] Remove duplicate code patterns in MCP Gateway Eliminate duplicate code in authorization parsing and HTTP transport connection Jan 20, 2026
Copilot AI requested a review from lpcox January 20, 2026 18:30
@lpcox lpcox marked this pull request as ready for review January 20, 2026 21:04
@lpcox lpcox merged commit e97f955 into main Jan 20, 2026
3 checks passed
@lpcox lpcox deleted the copilot/remove-duplicate-code-patterns branch January 20, 2026 21:05
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.

[duplicate-code] Duplicate Code Analysis Report - Commit 0ee0a71

2 participants