-
Notifications
You must be signed in to change notification settings - Fork 3
Configure as a Go CLI tool #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Co-authored-by: pelikhan <4175913+pelikhan@users.noreply.github.com>
Copilot
AI
changed the title
[WIP] Configure project as a Go CLI tool
Configure as a Go CLI tool
Dec 10, 2025
This was referenced Jan 13, 2026
22 tasks
Copilot AI
added a commit
that referenced
this pull request
Jan 20, 2026
- 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>
This was referenced Jan 24, 2026
13 tasks
12 tasks
lpcox
added a commit
that referenced
this pull request
Jan 31, 2026
## Refactoring HTTP Server Duplication - COMPLETE ✅ Based on semantic function clustering analysis, successfully addressed HTTP server creation code duplication (Issue #1). ### Summary Eliminated ~85% code similarity between `CreateHTTPServerForRoutedMode()` and `CreateHTTPServerForMCP()` by extracting three reusable helper functions. ### Changes Completed - [x] Create `internal/server/http_helpers.go` with extracted helper functions - [x] Extract `extractAndValidateSession()` - validates Authorization header and extracts session ID - [x] Extract `logHTTPRequestBody()` - logs POST request bodies for debugging - [x] Extract `injectSessionContext()` - stores session ID (and optional backend ID) in request context - [x] Update `CreateHTTPServerForRoutedMode()` in routed.go to use helpers - [x] Update `CreateHTTPServerForMCP()` in transport.go to use helpers - [x] Clean up unused imports in routed.go and transport.go - [x] Add comprehensive tests for http_helpers.go (4 test functions, 15+ test cases) - [x] Code review improvements: removed redundant logging, simplified pointer handling - [x] **Fix linting issues (SA1029, SA4006)** ✅ - [x] Run `make test-unit` - ✅ ALL PASSING (362+ tests) - [x] Run `make agent-finished` - ✅ ALL CHECKS PASSED ### Files Changed (Net: +252 lines, improved maintainability) - ✅ **Created**: `internal/server/http_helpers.go` (66 lines) - ✅ **Created**: `internal/server/http_helpers_test.go` (222 lines) - ✅ **Modified**: `internal/server/routed.go` (reduced by 20 lines, linting fixes) - ✅ **Modified**: `internal/server/transport.go` (reduced by 24 lines, linting fixes) ### Linting Fixes 1. **SA1029**: Defined custom `testContextKey` type instead of using built-in string type for context keys 2. **SA4006**: Restored pointer dereferencing pattern (`*r = *injectSessionContext(...)`) to properly modify request context ### Helper Functions 1. **`extractAndValidateSession(r *http.Request) string`** - Centralized session validation logic - Integrated error logging - Returns empty string on validation failure 2. **`logHTTPRequestBody(r *http.Request, sessionID, backendID string)`** - Unified request body logging - Backend-aware context (routed vs unified modes) - Restores body for subsequent reads 3. **`injectSessionContext(r *http.Request, sessionID, backendID string) *http.Request`** - Context injection for both modes - Optional backend ID support - Returns new request with updated context ### Test Coverage - ✅ Session extraction and validation (5 test cases) - ✅ Request body logging (5 test cases) - ✅ Context injection (4 test cases) - ✅ Context preservation (1 test case) ### Verification Results - ✅ Format: `gofmt` compliant - ✅ Build: Successful compilation - ✅ Lint: `golangci-lint` clean (0 issues) - ✅ Unit tests: 362+ tests passing - ✅ Integration tests: All passing (26.2s) ### Impact - **Maintainability**: Code duplication eliminated (85% → 0%) - **Testability**: Helper functions easily tested in isolation - **Readability**: Server creation functions more concise and clear - **Consistency**: Session handling logic centralized - **No Breaking Changes**: All functionality preserved, behavior identical ### Related Issue Resolves: #1 (Semantic Function Clustering Analysis - HTTP Server Duplication) <!-- START COPILOT ORIGINAL PROMPT --> <details> <summary>Original prompt</summary> ---- *This section details on the original issue you should resolve* <issue_title>[refactor] Semantic Function Clustering Analysis - Excellent Code Organization with Minor Opportunities</issue_title> <issue_description>## 🎯 Executive Summary This automated semantic function clustering analysis examined **50 non-test Go files** (~10,000 lines of code, 362+ functions) in the MCP Gateway repository (`githubnext/gh-aw-mcpg`). **The codebase demonstrates excellent organization** with clear separation of concerns and intentional file structure. ### Analysis Results - **Total Go Files Analyzed**: 50 (excluding test files) - **Total Functions/Methods Cataloged**: 362+ - **Function Clusters Identified**: 11 major clusters - **Critical Issues Found**: 0 - **Minor Refactoring Opportunities**: 3 - **Code Duplication Level**: Very Low (~2-3%) ### Key Findings ✅ **Strengths:** - Clear package-level organization (config, server, logger, launcher, guard, difc) - Well-structured validation logic consolidated in config/validation*.go files - Proper separation of HTTP transport concerns (routed vs unified modes) - Strong semantic clustering by feature (files match their primary purpose) - Excellent use of Go generics for logger initialization (global_helpers.go)⚠️ **Minor Opportunities:** 1. Two nearly-identical HTTP server creation functions with 85% code similarity 2. HTTP connection factory functions could be consolidated 3. Small opportunity to extract common HTTP request body logging pattern <details> <summary><b>Full Analysis Report</b></summary> ## 📊 Function Inventory by Package ### Package Distribution | Package | Files | Primary Functions | LoC | Purpose | |---------|-------|-------------------|-----|---------| | `internal/server/` | 9 | 80+ | 2,770 | HTTP server, routing, transport | | `internal/config/` | 5 | 35+ | 2,390 | Configuration, validation | | `internal/logger/` | 12 | 70+ | 1,870 | Multi-format logging framework | | `internal/mcp/` | 2 | 30+ | 961 | MCP protocol implementation | | `internal/launcher/` | 2 | 25+ | 725 | Backend process management | | `internal/difc/` | 5 | 45+ | 1,350 | Security labels & DIFC | | `internal/guard/` | 4 | 20+ | 310 | Security guards | | `internal/auth/` | 1 | 6+ | 155 | Authentication parsing | | `internal/cmd/` | 2 | 8+ | 490 | CLI commands | | **Other** | 8 | 43+ | 1,014 | Middleware, sys, utilities | ### Top 5 Largest Files 1. **`internal/server/unified.go`** - 968 lines (unified MCP server aggregation) 2. **`internal/mcp/connection.go`** - 961 lines (MCP connections with HTTP fallback) 3. **`internal/cmd/root.go`** - 485 lines (CLI root command) 4. **`internal/config/validation_schema.go`** - 461 lines (JSON schema validation) 5. **`internal/launcher/launcher.go`** - 396 lines (backend launcher) ## 🔍 Semantic Clustering Results ### Cluster 1: Configuration & Validation ✅ **Pattern**: Configuration loading, parsing, and validation **Files**: `internal/config/` **Organization**: **EXCELLENT** - Clear separation by validation type ``` config.go - Core config loading (LoadFromFile, LoadFromStdin) validation.go - Server config validation (validate*, expand*) validation_env.go - Environment validation (ValidateExecutionEnvironment) validation_schema.go - JSON schema validation (validateJSONSchema, format*) rules/rules.go - Validation error types and constructors ``` **Analysis**: Perfect one-file-per-feature organization. Validation logic properly separated by concern (server vs env vs schema). No refactoring needed. --- ### Cluster 2: Server & Transport ✅ **Pattern**: HTTP server creation and request handling **Files**: `internal/server/` **Organization**: **VERY GOOD** - Clear mode separation with minor duplication ``` server.go - Legacy HTTP server (backwards compatibility) unified.go - Unified MCP server (aggregates backends) routed.go - Routed mode HTTP server (/mcp/{serverID}) transport.go - Unified mode HTTP server (/mcp) handlers.go - Common handlers (OAuth, close) auth.go - Auth middleware health.go - Health endpoint response_writer.go - Response capture wrapper sdk_logging.go - SDK logging wrapper ``` **Analysis**: Well-organized by mode and responsibility. Minor duplication between `CreateHTTPServerForRoutedMode` and `CreateHTTPServerForMCP` (see Issue #1 below). --- ### Cluster 3: Logging Framework ✅ **Pattern**: Multi-format logging (file, JSONL, markdown, debug) **Files**: `internal/logger/` **Organization**: **EXCELLENT** - Clear separation by log format ``` logger.go - Debug logger (namespace-based with DEBUG pattern) file_logger.go - Text file logger (operational logs) jsonl_logger.go - JSONL RPC message logger markdown_logger.go - Markdown logger (GitHub workflow previews) rpc_logger.go - RPC message ... </details> > **Custom agent used: agentic-workflows** > GitHub Agentic Workflows (gh-aw) - Create, debug, and upgrade AI-powered workflows with intelligent prompt routing <!-- START COPILOT CODING AGENT SUFFIX --> - Fixes #548 <!-- START COPILOT CODING AGENT TIPS --> --- ✨ Let Copilot coding agent [set things up for you](https://github.com/githubnext/gh-aw-mcpg/issues/new?title=✨+Set+up+Copilot+instructions&body=Configure%20instructions%20for%20this%20repository%20as%20documented%20in%20%5BBest%20practices%20for%20Copilot%20coding%20agent%20in%20your%20repository%5D%28https://gh.io/copilot-coding-agent-tips%29%2E%0A%0A%3COnboard%20this%20repo%3E&assignees=copilot) — coding agent works faster and does higher quality work when set up for your repo.
This was referenced Feb 2, 2026
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Bootstraps the repository as a Go CLI tool with minimal boilerplate.
Changes
github.com/githubnext/gh-aw-mcpgwith Go 1.24.10main.gowith help/version commands using stdlibUsage
The CLI structure is ready for extension with additional commands and functionality.
Original prompt
💡 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.