Part of duplicate code analysis: #4711
Summary
The guard initialization / LabelAgent invocation sequence is implemented independently in both the MCP gateway server (internal/server/guard_init.go) and the proxy server (internal/proxy/proxy.go). Both call guard.BuildLabelAgentPayload, invoke g.LabelAgent, check for nil results, and call guard.ApplyLabelAgentResult — the same 4-step pattern, ~30 lines each.
Duplication Details
Pattern: Duplicated LabelAgent initialization pipeline
Impact Analysis
- Maintainability: Any bug fix or behaviour change (e.g. error message wording, nil-check handling) must be manually replicated in two places.
- Bug Risk: High — a divergence already exists:
proxy.go logs via logProxy.Printf while guard_init.go uses logger.LogInfoWithServer, so debugging behavior differs.
- Code Bloat: ~60 duplicated lines with diverging log detail.
Refactoring Recommendations
- Extract a shared helper into
internal/guard/ (e.g. guard/init.go):
- Function signature:
func RunLabelAgent(ctx context.Context, g Guard, policy interface{}, trustedBots, trustedUsers []string, backend BackendCaller, caps *difc.Capabilities, registry *difc.AgentRegistry, agentID string, defaultMode difc.EnforcementMode) (difc.EnforcementMode, *LabelAgentResult, error)
- Both callers reduce to a single call + their own session-caching logic.
- Estimated effort: 2–3 hours
- Benefits: single error-message source, single test surface
Implementation Checklist
Parent Issue
See parent analysis report: #4711
Related to #4711
Generated by Duplicate Code Detector · ● 1M · ◷
Part of duplicate code analysis: #4711
Summary
The guard initialization /
LabelAgentinvocation sequence is implemented independently in both the MCP gateway server (internal/server/guard_init.go) and the proxy server (internal/proxy/proxy.go). Both callguard.BuildLabelAgentPayload, invokeg.LabelAgent, check for nil results, and callguard.ApplyLabelAgentResult— the same 4-step pattern, ~30 lines each.Duplication Details
Pattern: Duplicated LabelAgent initialization pipeline
Severity: High
Occurrences: 2
Locations:
internal/server/guard_init.go—ensureGuardInitialized()(lines ~323–396)internal/proxy/proxy.go—initGuardPolicy()(lines ~149–213)Code Sample (server/guard_init.go):
Code Sample (proxy/proxy.go):
Impact Analysis
proxy.gologs vialogProxy.Printfwhileguard_init.gouseslogger.LogInfoWithServer, so debugging behavior differs.Refactoring Recommendations
internal/guard/(e.g.guard/init.go):func RunLabelAgent(ctx context.Context, g Guard, policy interface{}, trustedBots, trustedUsers []string, backend BackendCaller, caps *difc.Capabilities, registry *difc.AgentRegistry, agentID string, defaultMode difc.EnforcementMode) (difc.EnforcementMode, *LabelAgentResult, error)Implementation Checklist
internal/guard/init.gowith sharedRunLabelAgenthelperserver/guard_init.goto use shared helperproxy/proxy.goto use shared helperParent Issue
See parent analysis report: #4711
Related to #4711