Skip to content

Conversation

Copy link
Contributor

Copilot AI commented Dec 10, 2025

Bootstraps the repository as a Go CLI tool with minimal boilerplate.

Changes

  • Go module: Initialized github.com/githubnext/gh-aw-mcpg with Go 1.24.10
  • CLI entry point: Created main.go with help/version commands using stdlib
  • Documentation: Updated README with build instructions and usage examples
  • Git ignore: Excluded built binary from version control

Usage

$ go build -o gh-aw-mcpg .
$ ./gh-aw-mcpg version
gh-aw-mcpg version 0.1.0

$ ./gh-aw-mcpg
gh-aw-mcpg - Github Agentic Workflows MCP Gateway

Usage:
  gh-aw-mcpg [command]

Available Commands:
  help       Display help information
  version    Display version information

The CLI structure is ready for extension with additional commands and functionality.

Original prompt

Configure as a Go CLI tool.


💡 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.

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
Copilot AI requested a review from pelikhan December 10, 2025 21:53
@pelikhan pelikhan closed this Dec 20, 2025
@pelikhan pelikhan deleted the copilot/configure-go-cli-tool branch January 7, 2026 22:14
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>
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.
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.

2 participants