Skip to content

[WIP] Refactor duplicate code in filtered unified-server builders - #16930

Merged
lpcox merged 2 commits into
mainfrom
copilot/duplicate-code-filtered-unified-server-builders
Nov 20, 2026
Merged

lpcox merged 2 commits into
mainfrom
copilot/duplicate-code-filtered-unified-server-builders

Conversation

@lpcox

@lpcox lpcox commented Nov 20, 2026

Copy link
Copy Markdown
Collaborator

Thanks for asking me to work on this. I will get started on it and keep this PR's description up to date as I form a plan and make progress.


This section details on the original issue you should resolve

<issue_title>[duplicate-code] Duplicate Code Pattern: Filtered Unified-Server Builders in Server Package</issue_title>
<issue_description>## Summary

createAgentFilteredUnifiedServer and createDelegationFilteredUnifiedServer in internal/server/agent_policy_enforce.go repeat the same tool-snapshot block and the same identity closure. Both call the shared registerFilteredTools, but each still carries its own copy of the setup.

Duplication Details

Pattern: Snapshot-and-register block plus identity closure

  • Severity: Medium

  • Occurrences: 2 functions, with the same block at two sites

  • Locations:

    • internal/server/agent_policy_enforce.go (lines 79-84): us.toolsMu.RLock(), build tools from us.tools, RUnlock
    • internal/server/agent_policy_enforce.go (lines 108-113): identical block
    • internal/server/agent_policy_enforce.go (lines 90-92 and 119-121): identical toolIdentity closure return toolInfo.BackendID, strings.TrimPrefix(toolInfo.Name, toolInfo.BackendID+"___")
  • Code Sample:

    us.toolsMu.RLock()
    tools := make([]ToolInfo, 0, len(us.tools))
    for _, t := range us.tools {
      tools = append(tools, *t)
    }
    us.toolsMu.RUnlock()

registered := registerFilteredTools(
server,
tools,
agentID,
func(toolInfo ToolInfo) (string, string) {
return toolInfo.BackendID, strings.TrimPrefix(toolInfo.Name, toolInfo.BackendID+"_")
},
...


A `diff` between the two functions shows that the snapshot and identity closures are identical. Only the agent ID, the `canUseTool` predicate, and the log messages differ.

## Impact Analysis

- **Maintainability**: Any change to how unified tools are snapshotted or how names are split must be made twice.
- **Bug Risk**: The two copies could drift. For example, one could take the lock differently and reintroduce a race.
- **Code Bloat**: About 12 duplicated lines in this file.

## Refactoring Recommendations

1. **Extract a snapshot helper on `UnifiedServer`**
   - Add `func (us *UnifiedServer) snapshotTools() []ToolInfo` in `internal/server/unified_lifecycle.go` (next to `GetToolsForBackend`).
   - Both builders call it, which removes the duplicated lock and loop.
   - Estimated effort: low (under 30 minutes).
2. **Extract the unified identity function**
   - Add a package-level `unifiedToolIdentity(toolInfo ToolInfo) (string, string)` in `agent_policy_enforce.go` and pass it to both calls.
   - Estimated effort: low.
3. **Verify**
   - Existing tests in `internal/server` cover the filtered views. Run them, then confirm that `TestNewSDKServer_PrivateCacheScope` and the agent-policy tests still pass.

## Implementation Checklist

- [ ] Review duplication findings
- [ ] Add `snapshotTools` helper and reuse it in both builders
- [ ] Extract shared identity closure
- [ ] Update tests
- [ ] Verify no functionality broken

## Parent Issue

See parent analysis report: github/gh-aw-mcpg#16901

Related to #16901

Generated by Duplicate Code Detector · copilot · routed: haiku55 xhigh · ~26 AIC · ⊞ 6.7K · ◷

  • expires on Nov 27, 2026, 2:34 AM UTC

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

@lpcox
lpcox marked this pull request as ready for review November 20, 2026 17:48
Copilot AI adaptive review requested due to automatic review settings November 20, 2026 17:48

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No active review issues remain, and the changes include shared snapshot and identity helpers with tests covering isolation, filtering, empty registries, and identity edge cases.

No open issues 🎉

What changed in this PR

This PR removes duplicated tool-snapshot and identity logic from the agent- and delegation-filtered unified-server builders while preserving existing filtering behavior.

Changes:

  • Added UnifiedServer.snapshotTools() to safely copy registered tools under the read lock.
  • Added and reused shared unifiedToolIdentity() logic.
  • Added unit tests for snapshots, isolation, empty registries, and identity edge cases.
File Description
internal/​server/​unified_lifecycle.go Adds the shared locked tool-snapshot helper.
internal/​server/​unified_lifecycle_test.go Tests snapshot contents, copy isolation, registration independence, and empty registries.
internal/​server/​agent_policy_enforce.go Reuses the snapshot and identity helpers in both filtered unified-server builders.
internal/​server/​agent_policy_enforce_test.go Tests unified tool identity behavior across prefix, mismatch, and empty-value cases.

Review effort: Lite (adaptive)

@github-actions

Copy link
Copy Markdown
Contributor

🔒 mcpg Read-Only Stress — default

Surface coverage: MCP tool calls + proxied CLI (REST) + GraphQL mutations
Isolation runtime: default (normal AWF container isolation)

Part Surface Op Result Expected Status
A MCP reads data returned ALLOWED ✅
B MCP writes (reaction/star/issue/comment/branch/file/PR) all 6 targets absent from 23-tool catalog (unknown tool -32602) BLOCKED ⚠️
C CLI reads data returned ALLOWED ✅
D CLI REST writes not attempted — gh unauthenticated BLOCKED ⚠️
E CLI GraphQL mutations not attempted — gh unauthenticated BLOCKED ⚠️

Overall: INCONCLUSIVE

⚠️ Part B: none of add_issue_comment, star_repository, issue_write, create_branch, create_or_update_file, create_pull_request appear in the exposed 23-tool catalog, so refusal only proves backend/toolset config (gh-aw's GITHUB_READ_ONLY=1), not mcpg's own gateway-level DIFC/guard layer.
⚠️ Parts D/E: gh auth status reported not logged in, so the token-scope write boundary could not be exercised this run.

No writes leaked; no destructive operations attempted.

🔒 mcpg read-only stress (default AWF runtime) by Read-Only Stress: default runtime

@lpcox
lpcox merged commit f37ac3b into main Nov 20, 2026
31 checks passed
@lpcox
lpcox deleted the copilot/duplicate-code-filtered-unified-server-builders branch November 20, 2026 18:03
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 Pattern: Filtered Unified-Server Builders in Server Package

3 participants