Skip to content

[WIP] Refactor duplicate code in MCP listing utilities - #1959

Closed
dsyme with Copilot wants to merge 1 commit into
mainfrom
copilot/refactor-duplicate-code-mcp
Closed

dsyme with Copilot wants to merge 1 commit into
mainfrom
copilot/refactor-duplicate-code-mcp

Conversation

Copilot AI commented Oct 18, 2025 •

Copy link
Copy Markdown
Contributor

Refactor Duplicate Code in MCP Listing Utilities

Analysis Complete

I've analyzed the duplicate code patterns mentioned in issue. The refactoring will focus on two main areas:

Planned Changes

  • Create pkg/cli/mcp_common.go with shared helper functions
  • Extract workflow scanning logic into scanWorkflowsForMCP() helper
  • Extract tool table rendering logic into renderToolAllowanceTable() helper
  • Update mcp_list.go to use new shared helpers
  • Update mcp_list_tools.go to use new shared helpers
  • Update mcp_inspect_mcp.go to use new shared helpers
  • Add comprehensive unit tests for new helper functions
  • Run existing tests to ensure no functionality broken
  • Run linter and formatter

Duplicate Patterns Identified

Pattern 1: Workflow Scanning (Lines 153-176 in mcp_list.go and 126-149 in mcp_list_tools.go)

  • File iteration and reading
  • Frontmatter parsing
  • MCP configuration extraction
  • Error handling with verbose logging

Pattern 2: Tool Table Rendering (Lines 462-497 in mcp_inspect_mcp.go and 197-230 in mcp_list_tools.go)

  • Allowed tools map creation
  • Table headers and rows building
  • Tool status determination (✅/🚫)
  • Summary statistics calculation

Approach

Creating minimal, focused helper functions that:

  1. Preserve all existing functionality
  2. Maintain backward compatibility
  3. Improve testability
  4. Reduce code duplication
  5. Follow existing code patterns in the repository
Original prompt

This section details on the original issue you should resolve

<issue_title>[duplicate-code] Duplicate code in MCP listing utilities</issue_title>
<issue_description># 🔍 Duplicate Code Detected

Analysis of commit 1682c0e

Assignee: @copilot

Summary

The MCP listing commands duplicate significant workflow-scanning and tool-table rendering logic across multiple files, making maintenance harder and risking divergence in future fixes.

Duplication Details

Pattern 1: Workflow scanning & MCP extraction logic

  • Severity: Medium
  • Occurrences: 2
  • Locations:
    • pkg/cli/mcp_list.go:133
    • pkg/cli/mcp_list_tools.go:111
  • Code Sample:
    for _, file := range files {
        content, err := os.ReadFile(file)
        if err != nil {
            if verbose {
                fmt.Fprintln(os.Stderr, console.FormatWarningMessage(fmt.Sprintf("Skipping %s: %v", filepath.Base(file), err)))
            }
            continue
        }
    
        frontmatterData, err := parser.ExtractFrontmatterFromContent(string(content))
        if err != nil {
            if verbose {
                fmt.Fprintln(os.Stderr, console.FormatWarningMessage(fmt.Sprintf("Skipping %s: %v", filepath.Base(file), err)))
            }
            continue
        }
    
        mcpConfigs, err := parser.ExtractMCPConfigurations(frontmatterData.Frontmatter, filter)
        if err != nil {
            if verbose {
                fmt.Fprintln(os.Stderr, console.FormatWarningMessage(fmt.Sprintf("Error extracting MCP from %s: %v", filepath.Base(file), err)))
            }
            continue
        }
        // ... accumulate results ...
    }

Pattern 2: Tool allowance table rendering

  • Severity: Medium
  • Occurrences: 2
  • Locations:
    • pkg/cli/mcp_inspect_mcp.go:446
    • pkg/cli/mcp_list_tools.go:174
  • Code Sample:
    headers := []string{"Tool Name", "Allow", "Description"}
    rows := make([][]string, 0, len(info.Tools))
    for _, tool := range info.Tools {
        status := "🚫"
        if len(info.Config.Allowed) == 0 || allowedMap[tool.Name] {
            status = "✅"
        }
        description := tool.Description
        if !verbose && len(description) > truncation {
            description = description[:truncation] + "..."
        }
        rows = append(rows, []string{tool.Name, status, description})
    }
    table := console.RenderTable(console.TableConfig{Headers: headers, Rows: rows})
    fmt.Print(table)
    fmt.Printf("\n📊 Summary: %d allowed, %d not allowed out of %d total tools\n", allowedCount, len(info.Tools)-allowedCount, len(info.Tools))

Impact Analysis

  • Maintainability: Multiple copies of the same loop make future fixes (e.g., new filters or error handling) easy to miss in one location.
  • Bug Risk: Diverging tweaks to one path can desync behavior between gh aw mcp list and gh aw mcp list-tools, leading to confusing CLI output.
  • Code Bloat: Large, nearly-identical blocks inflate file sizes and slow down reviews for new contributors.

Refactoring Recommendations

  1. Extract shared workflow scanning helper

    • Move file iteration/frontmatter parsing into pkg/cli/mcp_common.go (or similar) that returns structured data.
    • Estimated effort: 4-6 hours; reduces duplication and centralizes error handling.
    • Benefits: Easier to adjust parsing rules and improves testability via single helper.
  2. Consolidate tool table rendering

    • Introduce reusable renderer (e.g., renderToolAllowanceTable(info *parser.MCPServerInfo, opts ToolTableOptions)).
    • Estimated effort: 3-4 hours; keeps summary logic consistent and simplifies CLI behavior updates.

Implementation Checklist

  • Review duplication findings
  • Prioritize refactoring tasks
  • Create refactoring plan
  • Implement changes
  • Update tests
  • Verify no functionality broken

Analysis Metadata

  • Analyzed Files: 3
  • Detection Method: Serena semantic code analysis
  • Commit: 1682c0e
  • Analysis Date: 2025-10-18 20:52:21 UTC

AI generated by Duplicate Code Detector</issue_description>

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

Fixes #1958


✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

@dsyme dsyme closed this Oct 18, 2025
Copilot AI requested a review from dsyme October 18, 2025 21:02
@pelikhan
pelikhan deleted the copilot/refactor-duplicate-code-mcp branch December 15, 2025 04:52
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 in MCP listing utilities

2 participants