Skip to content

fix(oauth): treat zero ExpiresAt as never-expires in HasPersistedToken - #1

Closed
electrolobzik wants to merge 18 commits into
halo-mainfrom
fix/oauth-zero-expiry
Closed

electrolobzik wants to merge 18 commits into
halo-mainfrom
fix/oauth-zero-expiry

Conversation

@electrolobzik

@electrolobzik electrolobzik commented May 12, 2026 •

Copy link
Copy Markdown
Collaborator

Closing — the branch (fix/oauth-zero-expiry) was forked off upstream/main, not off halo-main, so this PR's diff is halo-main..upstream/main + the actual fix (175 files, 8989 additions). The right scope is just the 3-file oauth fix.

Replaced by a new PR with the commit cherry-picked onto a clean halo-main-based branch.

🤖 Generated with Claude Code

JasonLandbridge and others added 18 commits April 28, 2026 10:19
…-mcp-proxy#435)

* feat: add opencode AI client support

* refactor: Added missing icon to opencode

* fix: fix the missing favicon in the web client

* test: pin %LOCALAPPDATA% under t.TempDir() for OpenCode tests

The Windows-only `Build Binaries (windows-latest, …)` job failed because
ConfigPath("opencode", homeDir) reads %LOCALAPPDATA% from the real
environment on Windows and only falls back to homeDir/AppData/Local when
the env is unset. On the CI runner LOCALAPPDATA points at the runner's
real profile, so the test that asserts "config does not exist" hit a
path outside the t.TempDir() and broke the isolation contract.

Fix is two-fold:

- internal/connect/connect_test.go: t.Setenv LOCALAPPDATA in both
  testService and testServiceWithKey helpers so every test inherits the
  pinned path automatically (and any future opencode test will too).
- internal/httpapi/connect_test.go: same t.Setenv pattern in the two
  TestHandleConnectClient_OpenCode* tests that don't go through the
  service helper.

No production code change. Verified locally on macOS:
  go test ./internal/connect/... ./internal/httpapi/... — both PASS.

---------

Co-authored-by: Claude Code <[email protected]>
…roxy#431)

* docs(install): add Arch Linux (AUR) install instructions

Mirrors the AUR mention added to README.md in smart-mcp-proxy#430 into the docs
site (docs.mcpproxy.app). Adds a dedicated section covering yay and
manual makepkg flows, the systemd unit layout, and an explicit note
on AUR update cadence and the current x86_64-only architecture
support.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Apply suggestions from code review

Co-authored-by: Jason Landbridge <[email protected]>

---------

Co-authored-by: Claude Code <[email protected]>
Co-authored-by: Jason Landbridge <[email protected]>
… uvx/npx (closes smart-mcp-proxy#439) (smart-mcp-proxy#440)

* fix(secureenv): inherit user's interactive PATH so stdio servers find uvx/npx when launched from Finder/LoginItem (smart-mcp-proxy#439)

When MCPProxy launches from a macOS .app bundle (Finder, Dock, Login Item),
launchd hands the process PATH=/usr/bin:/bin:/usr/sbin:/sbin (4 entries).
Stdio MCP servers then can't resolve uvx, npx, node, brew, etc., because
none of those live on the system-bin set.

The existing PATH-enhancement gate `len(pathParts) <= 2` blocked enhancement
for the launchd 4-entry case. Drop that gate (EnhancePath is already an
explicit opt-in for stdio in core/client.go) and merge in the user's
interactive login-shell PATH via shellwrap.LoginShellPATH so non-standard
installs (mise/asdf/Colima/custom shims) are also picked up.

Also harden shellwrap.LoginShellPATH against rc-file banner contamination:
bracket the captured $PATH with unique markers so welcome messages /
oh-my-zsh updates / motd lines on stdout no longer get prepended onto the
PATH value (they previously made exec.LookPath fail to resolve anything).

Tests:
- internal/secureenv/launchd_path_test.go — covers launchd-style 4-entry
  PATH, login-shell merge priority, fallback when login shell is broken,
  and the "already-comprehensive PATH" no-op path.
- internal/shellwrap/shellwrap_test.go — TestLoginShellPATH_StripsBannerContamination
  verifies banner stdout is rejected by the marker parser.

Verified locally: with env -i PATH=/usr/bin:/bin:/usr/sbin:/sbin on macOS,
secureenv.BuildSecureEnvironment now produces a 14-entry PATH that resolves
uvx, npx, node, python3, brew. Without the fix, the same env yields the
unchanged 4-entry launchd PATH and the four GUI tools all fail to resolve.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* test(secureenv): drop /usr/local/bin position assertion in TestDockerPathEnhancement

Post-smart-mcp-proxy#439 the buildEnhancedPath compose order is `login-shell PATH →
discovered → existing`. On hosts where `bash -l -c '…'` does not enrich
the ambient PATH (e.g. Linux CI runners — non-interactive bash does not
read /etc/environment), the captured login-shell PATH equals the test's
ambient `/usr/bin:/bin` and `/usr/local/bin` is added by static discovery
*after* `/usr/bin`. The user-visible guarantee (`/usr/local/bin` is
findable on PATH) is unchanged; only the implementation detail of strict
position relative to `/usr/bin` differs.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Code <[email protected]>
…d import, passive Verify (smart-mcp-proxy#433)

Reframes the first-run wizard as a persistent, idempotent setup surface
driven by the activation funnel telemetry (78.2% → 11.7% cliff at IDE
connect). Replaces the linear v1 flow with three idempotent tabs
(Clients · Servers · Verify), a top-pinned sidebar entry with an
animated badge, and a passive Verify tab that flips green automatically
on the first successful MCP initialize round-trip.

Highlights:
- Backend: /api/v1/onboarding/state extended with first_mcp_client_ever,
  mcp_clients_seen_ever, incomplete_tab_count. Reuses Spec 044's
  ActivationStore — no new BBolt buckets.
- Backend: ImportFromPathRequest gains skip_quarantine + rename map for
  the wizard's bulk-import path with cross-source name disambiguation.
- Frontend: 3-tab modal (Clients · Servers · Verify); Servers tab is a
  sectioned checkbox list with indented rows, sticky non-scrollable
  footer panel exposing global Docker isolation + Quarantine toggles
  with deep links to docs.mcpproxy.app/security/. Conflict pills
  rename "mcpproxy" from multiple sources to mcpproxy_<format>.
- Frontend: top-pinned sidebar Setup entry with badge that mirrors
  incomplete_tab_count; Dashboard's old Run-setup-wizard button removed.
- Verify tab surfaces recent activity records inline + sample prompts
  exercising built-in mcpproxy tools (retrieve_tools, upstream_servers,
  quarantine_security).

Verification: specs/046-local-first-onboarding/verification/report.html
documents 20 Playwright scenarios across the v2 redesign.

Companion docs:
- docs.mcpproxy.app/security/{docker-isolation,quarantine} — separate PR
  on the website repo, already merged.
- CLAUDE.md gains "Verifying Web UI changes" methodology section.
- SynapBus wiki: webui-verification-playwright-rich-report.

Related smart-mcp-proxy#46
… guards (smart-mcp-proxy#434)

Adds five anonymous, fixed-enum heartbeat fields per Spec 046 US3 so we can
measure whether the wizard moves day-2 retention from the 11.8% pre-feature
baseline. Bumps schema_version 3 → 4. Existing v3 consumers ignore the new
fields; v1/v2/v3 clients keep sending the same payload they did before.

Fields added to HeartbeatPayload:
- connected_client_count (int)
- connected_client_ids ([]string, fixed enum from adapter table)
- wizard_engaged (bool)
- wizard_connect_step ("" / "completed" / "skipped")
- wizard_server_step ("" / "completed" / "skipped")

Privacy posture inherits Spec 042 / Spec 044: opt-out, anonymous, off-by-
default in CI/test, no transmission when telemetry is disabled. Two new
privacy regression tests in payload_privacy_test.go assert the wire shape
and that the new fields cannot carry user-entered values.

Wired in internal/server/server.go alongside the existing connect-service
wire-up so a single consultation returns fresh data each heartbeat.

Companion changes (separate repos):
- mcpproxy-telemetry: D1 migration + worker validation
- mcpproxy.app-website: /telemetry page documentation

Related smart-mcp-proxy#46
The Ubuntu 24.04 GitHub runner ships AWS CLI v1, which doesn't recognize
--no-progress (a v2-only flag). publish-linux-repos has been failing on
every release since v0.28.0 with:

    aws: [ERROR]: An error occurred (ParamValidation): Unknown options: --no-progress

--quiet is the v1 equivalent (suppresses transfer progress output) and
is also supported by v2, so this works on both versions.

The main release artifacts (binaries, DMG, RPM/DEB packages) still
publish correctly through the GitHub Releases path; this only fixes
the apt.mcpproxy.app / rpm.mcpproxy.app R2 sync sub-job.
…state (smart-mcp-proxy#441)

When mcpproxy boots from a macOS .app bundle / LoginItem, launchd hands
the parent process PATH=/usr/bin:/bin:/usr/sbin:/sbin. Two bugs combined
to make Docker recovery permanently dead for the lifetime of that boot:

1. checkDockerAvailability used a bare exec.Command("docker", "info").
   Go's exec resolves the bare name via os.Getenv("PATH") — i.e. the
   launchd minimal set — so it failed with `executable file not found in
   $PATH` even though /Applications/Docker.app/Contents/Resources/bin/
   docker is right there. Every other docker call site in the codebase
   already routes through shellwrap.ResolveDockerPath (which probes
   well-known install locations and the user's login-shell PATH); the
   recovery monitor was missed during that migration.

2. startDockerRecoveryMonitor loaded persisted DockerRecoveryState
   verbatim, including FailureCount. After a previous process bled out
   at the retry limit, the new process inherited attempt=10 and the
   recovery loop's `attempt >= maxRetries` guard fired on the first
   probe — exiting in milliseconds without ever sleeping. Logs showed
   the symptom: "Docker recovery max retries exceeded (attempts=10)"
   5 ms after "Docker unavailable on startup".

Fix:
- Route checkDockerAvailability through dockerResolverFn (default:
  shellwrap.ResolveDockerPath, fallback: bare "docker"). Test-overridable.
- Add freshenLoadedDockerRecoveryState helper that resets FailureCount /
  AttemptsSinceUp / RecoveryMode on the loaded state. Telemetry fields
  (LastSuccessfulAt, LastError, LastAttempt) are preserved.

Tests:
- TestCheckDockerAvailability_UsesShellwrapResolver — installs a fake
  docker in a temp dir, sets PATH=launchd-minimal, asserts the resolver
  is consulted (would fail with bare exec).
- TestCheckDockerAvailability_FallbackOnResolverFailure — when the
  resolver errors, bare-name exec via the ambient PATH still works.
- TestFreshenLoadedDockerRecoveryState — counters reset, telemetry kept.
- TestFreshenLoadedDockerRecoveryState_NilSafe — defensive nil guard.

Verified locally with env -i PATH=/usr/bin:/bin:/usr/sbin:/sbin running
mcpproxy serve: shellwrap resolves docker via the well-known
/Applications/Docker.app path on the very first probe; no recovery loop
runs; no max-retries log line. Without the fix, the same env reproduces
the original "stuck Loading + max retries exceeded in 5ms" pattern.

Co-authored-by: Claude Code <[email protected]>
…mart-mcp-proxy#436) (smart-mcp-proxy#442)

KPI summary cards on three pages were passive — the count would change
but the cards weren't clickable, so users (Jason in smart-mcp-proxy#436) tried clicking
them as their first instinct and "nothing happened."

Each card now drives the matching filter:

  Activity page (filterStatus):
    Total (24h)        → ''        (all)
    Success            → 'success'
    Errors             → 'error'
    Blocked            → 'blocked'

  Servers page (filter):
    Total Servers      → 'all'
    Connected          → 'connected'
    Quarantined        → 'quarantined'
    Total Tools        → no filter (intentionally non-clickable, no
                         matching list-state to drive)

  Agent Tokens page (tokenFilter, new):
    Total Tokens       → 'all'
    Active             → 'active'
    Expired / Revoked  → 'expired'

Implementation:
- Clickable cards rendered as <button> with type="button", aria-pressed
  bound to the active state, data-test attribute for stable selection.
- Active card shows bg-base-200 + ring-2 ring-inset ring-primary/40 +
  cursor-pointer + hover:bg-base-200/60 (consistent across all three pages).
- Clicking the already-active card toggles back to 'all' / '' (clearing
  the filter); clicking 'Total' always resets.
- Servers + Activity drive existing filter state; AgentTokens introduces
  a new tokenFilter ref and filteredTokens computed (the page previously
  had no filter, so it also gets a "no tokens match this filter" empty
  state with a 'Show all' shortcut).

Verified end-to-end via the Chrome extension MCP against a live
mcpproxy serve on port 18083:

  Servers (3 servers, 1 quarantined):
    click Quarantined  → kpi-quarantined.aria-pressed=true,
                         filter button "Quarantined (1)" goes btn-primary,
                         all other filter buttons go btn-outline
    click Connected    → kpi-connected.aria-pressed=true
    click Connected ×2 → toggles back to Total/all

  Agent Tokens (2 active + 1 revoked):
    baseline           → 3 rows visible
    click Active       → 2 rows, 0 'Revoked' badges, 2 'Active' badges
    click Expired      → 1 row, 1 'Revoked' badge, 0 'Active' badges
    click Total        → 3 rows

  Activity (1 system_start success):
    click Success      → kpi-success highlighted, status select='success',
                         "Status: success" badge appears in the Active
                         filters chip row
    click Errors       → status select='error', badge shows "Status: error"
    click Errors ×2    → toggles off, no Status badge

Co-authored-by: Claude Code <[email protected]>
) (smart-mcp-proxy#443)

Reported by Jason Landbridge (issue smart-mcp-proxy#438): after clicking "Approve all
tools" on a server, navigating to the Servers overview page kept showing
the "5 pending approval" quarantine badge even though everything was
approved. A hard refresh fixed it.

Root cause is a generalisation of the previously-special-cased
last_error bug:

The Pinia stores/servers.ts mergeServers helper updates each existing
server in place via Object.assign(existingServer, incomingServer). The
backend's enrichServersWithQuarantineStats (internal/httpapi/server.go)
only sets `Quarantine` when `pending > 0 || changed > 0`; once all tools
are approved the field disappears from the JSON entirely. Object.assign
adds and overwrites — it never deletes. The stale `quarantine: { pending_count: 5 }`
therefore survived on the in-place reactive object and ServerCard's
`server.quarantine?.pending_count` kept rendering the badge until a full
page reload replaced the array.

The author had already special-cased `last_error` for this exact reason.
The same pattern affects every conditional optional field — `quarantine`,
`oauth_status`, `token_expires_at`, `user_logged_out`, `health`,
`security_scan`, `diagnostic`, `error_code`, etc. — and Jason flagged
that he sees similar staleness "in several areas of the UI."

Fix: replace the one-field special case with a general key-sync. For
each key on the existing server that is absent on the incoming server,
delete it before Object.assign. This treats the API response as
authoritative (which it is) and works for every conditional field
without enumerating them. The existing object reference is still
preserved, so v-memo on ServerCard keeps its stable identity and the
list does not visually rerender.

Tests in frontend/tests/unit/servers-store.spec.ts:
  * drops the stale quarantine field when the backend stops emitting it
  * drops last_error on recovery (regression coverage for the original
    special case the new code subsumes)
  * drops oauth_status / token_expires_at / user_logged_out together
  * preserves the existing object reference across merges (identity
    stability for v-memo)
  * sanity: still updates and adds present fields

  8 tests, all passing (5 new + 3 existing).

Note: a complementary backend change — emit `servers.changed` SSE on
tool approval — is in a separate PR so a Servers/overview page open in
another tab also reactively updates without depending on the Approve
flow's explicit fetchServers() call. This PR is the primary fix; the
SSE one is the cross-tab improvement.

Co-authored-by: Claude Code <[email protected]>
…xy#438) (smart-mcp-proxy#444)

Companion to PR smart-mcp-proxy#443 (frontend mergeServers stale-field clear).

Background — issue smart-mcp-proxy#438: when a user clicks "Approve all tools" on the
Server Detail page, the Servers/overview page (open in another tab, or
reached via client-side navigation) keeps showing the "N pending
approval" quarantine badge until a manual reload. PR smart-mcp-proxy#443 fixes the
specific case where the user navigates to Servers in the SAME session,
because the click handler explicitly calls serversStore.fetchServers().

This PR fixes the cross-tab / cross-session case: ApproveTools now
publishes a servers.changed runtime event with reason="tools_approved"
after successfully updating tool approval records. The event already
exists for every other server-state mutation (enable/disable, restart,
quarantine toggle, sync, server connected/disconnected, tools indexed —
see internal/runtime/lifecycle.go); this fills in the one missing call
site so any subscribed UI surface (web UI in another tab, tray, future
clients) re-fetches authoritative state without depending on the
acting tab to broadcast.

The emit:
- happens once per ApproveTools call, after the loop, gated on
  approved > 0 — bulk approval of 50 tools doesn't spam 50 events;
  a no-op call (e.g. tools that don't have records) emits nothing
- includes server, approved_count, and approved_by in the payload so
  consumers can render targeted toasts ("3 tools approved on github
  by user@…") without needing a follow-up GET

Tests in internal/runtime/tool_approval_event_test.go:
  * TestApproveTools_EmitsServersChanged — pre-seed a pending record,
    subscribe to the bus, call ApproveTools, assert one
    servers.changed (reason=tools_approved) within 2s, with the
    expected payload fields.
  * TestApproveTools_NoEventOnNoOp — call ApproveTools on a tool with
    no record (warn-and-continue path), assert NO event is published.

Co-authored-by: Claude Code <[email protected]>
…smart-mcp-proxy#445)

The release-notes generator (scripts/generate-release-notes.sh) feeds
commit subjects to Claude with no edition context, and Claude has been
inventing edition annotations from thin air:

- v0.29.0: "*Note: The onboarding improvements primarily affect the
  **Personal Edition** desktop application.*"
- v0.29.1: "**Personal Edition (macOS)**" header
- v0.29.2: "*Note: All changes in this release apply to the Teams
  edition only.*" — wrong, all three PRs (smart-mcp-proxy#442, smart-mcp-proxy#443, smart-mcp-proxy#444) modify
  shared code (internal/runtime/, frontend/) and ship in both editions

This patch updates the prompt to:

1. Briefly explain the two-edition build model so the model doesn't have
   to guess from training data.
2. Forbid edition-only annotations unless a commit subject explicitly
   says so (e.g. contains "(server)", "(teams)", "server-only").
3. Forbid speculation from subject keywords (ui/runtime/oauth/etc).
4. Use "Server edition", not "Teams edition" — Teams is an internal
   package name.
5. Default to BOTH editions when unsure.

The v0.29.2 release body has been hand-corrected separately.

Co-authored-by: Claude Code <[email protected]>
…-proxy#446)

### Summary

This PR fixes an intermittent issue where tools from enabled/connected servers (notably `rider-official`) would sometimes not appear in `retrieve_tools` results, even though upstream `ListTools` calls succeeded.

The fix addresses two core causes:

1. **Concurrent `ListTools` contention** produced transient failures (`ListTools operation already in progress`) during discovery.
2. **Discovery race windows** could temporarily omit connected servers from global discovery output, causing visible tool-set shrink in search results.

---

## Root cause

During server churn (restart/reconnect, reactive discovery, background discovery), multiple discovery paths could call `ListTools` on the same managed client at the same time.

Previously:
- first call proceeded,
- second call failed fast with an “already in progress” error.

At the same time, global discovery accepted partial results from currently successful servers. If one connected server was omitted in that cycle, its tools were temporarily absent from indexed/searchable results.

This produced the observed “sometimes shows, sometimes missing” behavior.

---

## What changed

### 1) Coalesced concurrent `ListTools` calls
**File:** `internal/upstream/managed/client.go`

- Reworked managed client `ListTools` concurrency behavior:
  - one caller performs upstream `ListTools`,
  - concurrent callers wait for the same in-flight operation,
  - all waiters receive the shared result/error.
- Eliminates fail-fast path that previously returned:
  - `ListTools operation already in progress for server ...`

**Impact:** prevents transient per-server tool discovery drops caused by local concurrency collisions.

---

### 2) Added last-good per-server snapshot fallback in global discovery
**Files:** `internal/runtime/runtime.go`, `internal/runtime/lifecycle.go`

- Added runtime cache of last known good tool snapshots per server.
- During `DiscoverAndIndexTools`:
  - fresh per-server snapshots are updated from current discovery results,
  - standard differential updates are applied,
  - for connected servers missing from the current discovery pass, the last-good snapshot is reused and re-applied.

**Impact:** avoids temporary index shrink when a connected server is missed in one discovery cycle.

---

### 3) Regression tests for ListTools coalescing
**File:** `internal/upstream/managed/listtools_coalescing_test.go`

Added tests:
- `TestListTools_CoalescesWaiters`
- `TestListTools_CoalescesWaitersError`

These verify that waiters receive shared success/error instead of being rejected while a list operation is already in progress.

---

## Verification

- `go test ./internal/upstream/managed ./internal/runtime` passed.
- Build check passed (`build_project` success).

---

## Scope and non-goals

- This PR focuses on correctness/stability of discovery and visibility.
- Does **not** change retrieval ranking semantics or hard limits (e.g., `retrieve_tools.limit` max 100).
- Does **not** introduce debounce/metadata enhancements (can be follow-up).

---

## Expected behavior after fix

- Enabled/connected servers should no longer disappear from tool retrieval due to in-process `ListTools` races.
- Transient discovery omissions should be masked by last-good snapshots, reducing inconsistent tool visibility across adjacent queries.

---

## Follow-ups (optional)

- Add explicit discovery health metadata to `retrieve_tools` responses (`fresh/degraded`, missing/stale servers).
- Add event debounce for server churn bursts to reduce redundant discovery passes.
- Add broader integration test simulating reconnect storms with repeated retrieval queries.
…mcp-proxy#447)

Closes smart-mcp-proxy#432
<img width="2188" height="602" alt="image" src="https://github.com/user-attachments/assets/8aef92a4-09de-4caa-acf0-24994c04c113" />
<img width="3281" height="742" alt="image" src="https://github.com/user-attachments/assets/7f445aa8-16f2-461d-8b99-173539b59cb3" />

<img width="3289" height="1483" alt="image" src="https://github.com/user-attachments/assets/a809983d-a61a-4b8c-b000-24da70ea9fd4" />


## Summary
- treat disabled tools as non-callable/non-discoverable via centralized callable checks
- filter disabled tools before retrieve_tools response construction
- return TOOL_BLOCKED with clear message for direct calls to disabled tools
- exclude disabled tools from server status health tool_count displays
- add regression tests for callable predicate, discovery filtering, blocked call error, and re-enable visibility

## Validation
- go test ./internal/server -run 'TestIsToolCallable_DisabledTool|TestRetrieveTools_ExcludesDisabledToolsPreRanking|TestCallBlockedTool_ReturnsToolBlocked|TestReenableTool_VisibleAndCallable|TestHandleListUpstreams_FilteredForAgent'

## Notes
- security/admin introspection remains available via explicit quarantine/security endpoints
- standard discovery and call planning no longer surfaces disabled tools
…rt-mcp-proxy#448)

The first-run wizard only ever called markEngaged() on dismiss — it
never invoked markConnectCompleted/Skipped or markServerCompleted/
Skipped. Production telemetry (D1) confirmed the gap: every install
that engaged the wizard recorded wizard_engaged=true with
wizard_connect_step / wizard_server_step still NULL, making the
funnel queries documented in Spec 046 SC-012/SC-013 unusable.

Wire the four missing call sites:
  - connectOne() success → markConnectCompleted()
  - onServerAdded() (single) → markServerCompleted()
  - onBulkImport() (>0 imported) → markServerCompleted()
  - dismiss() → mark each unfilled step as skipped before markEngaged

Each guarded against re-firing once a status is recorded. Backend,
storage, telemetry payload, and worker schema were already correct;
the bug was purely in the frontend wiring.

Co-authored-by: Claude Code <[email protected]>
…lescer (smart-mcp-proxy#450)

* feat(047): cut idle CPU 92% — scanner cache + SSE payload embed + coalescer

Profile of MCPProxy.app + 30-server config + 1.06 GB BBolt + 91k activity
records showed 47% sustained CPU, with 56% of cycles inside bbolt.(*DB).View
and 50%+ in encoding/json.checkValid. The driver: every tray-triggered
GET /api/v1/servers walked the entire scan-job bucket via
BoltDB.ListScanJobs and JSON-unmarshalled every record before filtering.

This PR ships three fixes that take steady-state CPU from 47% (60s sample)
to 3.78% on the same scenario, without any storage migration:

- A1 (scanner negative cache): cacheScanSummary now stores a nil sentinel
  for servers with no scans, distinguished from "not in map" by the
  existing (value, ok) lookup. findLatestPassJobs returns errNoScans for
  the empty-bucket case so transient I/O failures don't pollute the
  cache. internal/security/scanner/service.go.

- B1 (SSE payload embed): emitServersChanged calls the management service
  once per coalesced event window and embeds the post-redaction server
  list + stats in the payload. Subscribers (Swift tray, Web UI) consume
  directly and skip the GET /api/v1/servers refetch.
  internal/runtime/event_bus.go.

- B2 (event coalescer): a single drainer goroutine + atomic.Pointer
  collapses retry-storm bursts into one publish per ~50ms, last-write-
  wins. internal/runtime/event_bus.go (new serversChangedCoalescer).

Plus a pprof endpoint at /debug/pprof/ on the parent mux (API-key gated;
zero overhead until hit) so future regressions can be diagnosed without
a custom build. internal/server/server.go.

Client wiring: the Swift tray (CoreProcessManager.swift) and the Vue Pinia
servers store consume payload.servers when present and fall back to
GET /api/v1/servers when running against an older core. New
ServersChangedPayload + ServersChangedEnvelope decode structs in
API/Models.swift.

Verification (specs/047-cpu-hotpath-fix/verification/): bbolt.(*DB).View
no longer in top-15 cum. encoding/json.checkValid flat down from 13.05%
to 8.37%. Cumulative cputime delta 19s/60s -> 2.91s/60s. Web UI live
console capture confirms zero refetch after servers.changed events.

Tests: TDD-first across all three sub-changes — TestGetScanSummary_*
(scanner), TestEmitServersChanged_* + TestCoalescer_* (runtime). Full
go test -race ./internal/... green; -tags server suite green; linter
clean. Pre-existing 10 failures in test-api-e2e.sh confirmed identical
on main; unrelated to this PR.

Out of scope (deferred to follow-up specs): in-memory
(serverName, pass)->latestJobID index; activity-log retention/pagination;
scan-job bucket re-keying; encoding/json replacement; PGO build.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* docs(047): add visual + reactivity verification

Live capture against the swap-in MCPProxy-047.app on the user's real
30-server config:

Web UI (Chrome MCP):
  - Toggled context7 disable via REST. Cleared network log first.
  - 10 SSE servers.changed events processed by the new handler.
  - 0 follow-up GET /api/v1/servers requests (network log empty).
  - Visible UI deltas: header counter 14/30 -> 10/30, context7
    card switched from "Connected (2 tools)/Disable" to
    "Disabled/Enable", Total Tools 123 -> 188.

macOS Tray (mcpproxy-ui-test, driven via stdio JSON-RPC since the
MCP server isn't registered in this session):
  - check_accessibility: trusted.
  - context7 menu state captured at three points:
      baseline:           "Connected (2 tools)" / button "Disable"
      after disable + 2s: "Disabled"             / button "Enable"
      after enable + 5s:  "Connected (2 tools)" / button "Disable"
  - The accessibility tree renders directly from appState.servers,
    which is now populated by the embedded SSE payload — no HTTP
    refetch was issued.

Three tray PNGs (baseline + after-disable + after-reenable) are
saved alongside this report; they show the top-level menu (context7
lives in the Servers submenu so the visual deltas live in the
accessibility tree, not the screenshot pixels — see visual.md).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* chore(047): drop verification artifacts; restore web/frontend/dist

Two PR-hygiene fixes:

1. Removed binary verification artifacts that the previous commits
   accidentally bundled into specs/047-cpu-hotpath-fix/verification/:
   pprof *.pb.gz profiles, *.txt dumps, and tray screenshots. Total
   ~6 MB of build output that doesn't belong in git history.
   The textual conclusions remain in report.md and visual.md;
   reproduce the artifacts locally via quickstart.md.

2. Restored web/frontend/dist/ to its main-branch state. The previous
   make build run produced a different set of hash-named asset files
   and orphaned the old ones; git interpreted that as deletions and
   I committed them. That cleanup was unintentional and out of scope
   for this PR — the dist/ contents at this branch tip now match main
   exactly.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Code <[email protected]>
…mcp-proxy#451)

Spec 047 (PR smart-mcp-proxy#450, v0.29.4) eliminated the burst-storm refetch path
(servers.changed -> refetch). This PR addresses the residual: 5 other
call sites in the Swift tray that still hit /api/v1/servers, totaling
~8 GETs per 60 s at idle on a 30-server config.

All 5 sites now read SSE-driven appState.servers in place of fetching:

- CoreProcessManager case "status": no longer refetches on
  connected_count change. Inline stats are merged unconditionally;
  per-server state arrives via the spec 047 servers.changed payload
  within ~50 ms of any actual transition.

- refreshState (30 s periodic) drops the refreshServers() call.
  refreshActivity / refreshSessions / refreshTokenMetrics /
  refreshSecurityStatus stay (SSE doesn't cover those domains).

- refreshSecurityStatus's Docker fallback now reads
  appState.servers synchronously instead of issuing another GET.

- MCPProxyApp's 10 s server-refresh Timer is removed entirely.

- menuWillOpen no longer refetches on every tray click. The menu
  rebuilds from in-memory state only.

In their place: a single 5-minute Combine timer in MCPProxyApp.swift
calls a new CoreProcessManager.refreshServersForSafetyNet() — pure
defense-in-depth in case SSE drops events past the 256-event buffer.

Verification (specs/048-tray-refetch-elimination/verification/report.md)
on the same MCPProxy.app + 30-server scenario as spec 047:
  - 0 GETs / 60 s at idle (was ~8)
  - context7 disable propagates to tray menu in 1 s
  - context7 enable propagates in 2 s
  - 0 GETs during the entire toggle window

Spec, plan, research, data-model, quickstart, tasks all under
specs/048-tray-refetch-elimination/. No core / Go changes.
Backward-compatible with older cores (spec 047 fallback path retained).

Co-authored-by: Claude Code <[email protected]>
Authorization servers that omit `expires_in` from the /token response
(e.g. Atlassian's MCP endpoint at https://mcp.atlassian.com/v1/mcp)
land in BBolt with ExpiresAt = time.Time{}. HasValidToken and mcp-go's
own Token.IsExpired() already treat that as "never expires", but
HasPersistedToken was computing `time.Now().After(time.Time{})` which
is always true — so the persisted token was reported as expired on
every reconnect, skipBrowserFlow stayed false, and the upstream
looped forever asking for re-auth even though a valid access token
sat in storage.

Fix HasPersistedToken to short-circuit on IsZero(), matching
HasValidToken. Also clean up PersistentTokenStore.GetToken so it no
longer logs a spurious "token has expired" warning for those records.

Add three unit tests covering the zero / future / past ExpiresAt
cases against HasPersistedToken so the IsZero branch can't regress.
@coderabbitai

coderabbitai Bot commented May 12, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Adds onboarding wizard and state APIs with persistence and telemetry; enriches servers.changed SSE payload and coalesces bursts; implements tool enable/disable and blocked counts; adds OpenCode connect support; updates Web UI and macOS tray to consume SSE; improves PATH/docker resolution; updates OAS, tests, docs, and scripts.

Changes

Integrated onboarding, SSE, tools, connect, and tray

Layer / File(s) Summary
End-to-end implementation and wiring
contracts/*, internal/httpapi/*, internal/runtime/*, internal/server/*, internal/storage/*, internal/connect/*, frontend/src/**/*, native/macos/*, oas/swagger.yaml, specs/**/*, docs/*, scripts/*, .gitignore
Implements onboarding state APIs/storage/telemetry and UI, SSE payload enrichment and coalescer with Web UI/Swift consumers, tool enable/disable and blocked metrics across backend and UI, OpenCode client support and tests, PATH/docker resolution fixes, and comprehensive docs/spec updates.

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Poem

A rabbit taps keys in a moonlit spree,
Coalescing storms to a gentle sea.
Tools learn to nap when “disabled” signs,
The wizard nods—onboarding aligns.
Swift and Vue sip SSE brew,
OpenCode hops in, config true.
Thump-thump—hot paths cooled anew.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/oauth-zero-expiry

@github-actions

Copy link
Copy Markdown

📦 Build Artifacts

Workflow Run: View Run
Branch: fix/oauth-zero-expiry

Available Artifacts

  • archive-darwin-amd64 (26 MB)
  • archive-darwin-arm64 (23 MB)
  • archive-linux-amd64 (15 MB)
  • archive-linux-arm64 (13 MB)
  • archive-windows-amd64 (26 MB)
  • archive-windows-arm64 (23 MB)
  • frontend-dist-pr (0 MB)
  • installer-dmg-darwin-amd64 (19 MB)
  • installer-dmg-darwin-arm64 (18 MB)

How to Download

Option 1: GitHub Web UI (easiest)

  1. Go to the workflow run page linked above
  2. Scroll to the bottom "Artifacts" section
  3. Click on the artifact you want to download

Option 2: GitHub CLI

gh run download 25749197681 --repo HaloCollar/mcpproxy-go

Note: Artifacts expire in 14 days.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 18

Note

Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/upstream/managed/client.go (1)

424-472: ⚠️ Potential issue | 🟠 Major | ⚖️ Poor tradeoff

Fix race condition: waiter could read nil result after new leader clears it.

The synchronization between acquireListToolsContext (which clears listToolsLastResult) and waiting goroutines has a timing gap. When the channel closes and a waiter wakes up, a new leader could acquire the lock and clear the result before the waiter reads it.

Race timeline:

  1. Leader publishes result via publishListToolsResult, then release() closes waitCh and sets inProgress = false
  2. Waiter wakes from closed channel but hasn't acquired the lock yet
  3. New ListTools call wins the lock race, sets inProgress = true, and clears listToolsLastResult = nil
  4. Original waiter acquires lock and reads nil

This violates the semantic contract stated in the acquireListToolsContext comment ("waiter can safely...read the published result"). The result needs to be stable after the channel is closed, but clearing it in acquireListToolsContext breaks that guarantee.

Solutions:

  • Capture result at wake time: Have waiter copy lastResult and lastErr immediately inside the select case before the lock, or store them atomically alongside the channel
  • Generation counter: Add a generation ID to each round so waiters can detect stale reads
  • Defer clearing: Only clear the cached result after all waiters finish reading (use a reference count or separate result holder per generation)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/upstream/managed/client.go` around lines 424 - 472, The race is that
acquireListToolsContext clears listToolsLastResult when a new leader starts,
allowing a waiter woken by a closed listToolsWaitCh to read nil; fix by adding a
generation id and associating results with that generation: introduce
mc.listToolsGen (uint64) incremented inside acquireListToolsContext when a new
leader is created, have publishListToolsResult store the generation number
alongside listToolsLastResult/listToolsLastErr, and have waiters after the
channel close read both the result and its generation under mc.listToolsMu and
only accept the result if the generation matches the generation they observed
when waking (otherwise treat as no-result and retry/return appropriate error).
This makes the result stable for the waking waiters without delaying clearing in
acquireListToolsContext.
🟡 Minor comments (16)
docs/getting-started/installation.md-90-93 (1)

90-93: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Missing command after “Enable it with:”

Line 92 introduces an action but no command is provided, so the setup flow is incomplete. Add the systemd user-unit command directly below it.

Suggested doc fix
 The package installs `mcpproxy` to `/usr/bin` and ships a systemd user unit at `/usr/lib/systemd/user/mcpproxy.service`.
 
 Enable it with:
+```bash
+systemctl --user daemon-reload
+systemctl --user enable --now mcpproxy.service
+```
 :::note Update cadence
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/getting-started/installation.md` around lines 90 - 93, Add the missing
systemd user commands under the "Enable it with:" line so users can actually
enable and start the mcpproxy unit: include the commands to reload user units
and enable+start the service (systemctl --user daemon-reload and systemctl
--user enable --now mcpproxy.service) formatted as a bash code block immediately
after the "Enable it with:" sentence; reference the mcpproxy.service systemd
unit and ensure the block is properly fenced.
README.md-79-86 (1)

79-86: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Clarify that only apt/dnf packages auto-start the service.

Line 86 claims "Both packages ... start the service automatically," but this is now misleading after adding the AUR option. The Arch AUR mcpproxy-bin package does not automatically enable and start the service—manual systemctl --user enable --now mcpproxy.service is required. Scope the auto-start claim to only the apt/dnf packages.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@README.md` around lines 79 - 86, The README statement “Both packages ship a
hardened `systemd` unit and start the service automatically” is inaccurate for
the Arch AUR `mcpproxy-bin`; update the sentence to scope auto-start behavior
only to the apt/dnf packages and add a note for the AUR package that users must
manually enable/start the service (e.g., via `systemctl --user enable --now
mcpproxy.service`). Locate the sentence containing "Both packages ship a
hardened `systemd` unit..." and replace it with a scoped sentence plus a brief
instruction mentioning the AUR package name `mcpproxy-bin` and the manual
enable/start step.
internal/secureenv/manager.go-294-296 (1)

294-296: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Honor EnhancePath=false when no PATH is present.

At Line 294, buildEnhancedPath returns discovered paths before checking m.config.EnhancePath, so PATH gets enhanced even when explicitly disabled.

Suggested fix
 func (m *Manager) buildEnhancedPath(existingPath string) string {
 	sep := string(os.PathListSeparator)
+
+	if !m.config.EnhancePath {
+		return existingPath
+	}
 
 	if existingPath == "" {
 		return strings.Join(m.pathDiscovery.DiscoveredPaths, sep)
 	}
@@
-	if !m.config.EnhancePath {
-		return existingPath
-	}
-
 	// Compose: login-shell PATH first (highest priority — captures the

Also applies to: 314-316

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/secureenv/manager.go` around lines 294 - 296, In buildEnhancedPath,
when existingPath == "" the function currently returns
strings.Join(m.pathDiscovery.DiscoveredPaths, sep) without checking
m.config.EnhancePath; update the logic to first honor m.config.EnhancePath and
only return the discovered paths when EnhancePath is true (otherwise return an
empty string or the unmodified existingPath), and apply the same guard to the
other branch referenced around the second occurrence (the block handling the
non-empty existingPath at the 314-316 area) so m.config.EnhancePath is
consistently respected.
specs/046-local-first-onboarding/spec.md-243-243 (1)

243-243: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add a language identifier to the fenced code block.

Line 243 uses a bare triple-backtick fence, which triggers markdownlint MD040.

Suggested fix
-```
+```text
 feat(046): adaptive onboarding wizard with state-based steps
 ...
-```
+```
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@specs/046-local-first-onboarding/spec.md` at line 243, The fenced code block
in the spec's markdown uses a bare ``` fence which triggers markdownlint MD040;
update the opening fence used around the onboarding change log (the block
starting with "feat(046): adaptive onboarding wizard with state-based steps") to
include a language identifier (for example use ```text) so the code fence
becomes ```text and keep the closing ``` unchanged; ensure the fence around that
block is updated so linting passes.
frontend/src/views/Dashboard.vue-383-383 (1)

383-383: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add data-test to the new onboarding component mount

Please add a stable test selector on the new OnboardingWizard usage so Playwright can target it reliably.

🔧 Suggested change
-    <OnboardingWizard :show="onboardingStore.wizardOpen" `@close`="onboardingStore.closeWizard" />
+    <OnboardingWizard data-test="onboarding-wizard" :show="onboardingStore.wizardOpen" `@close`="onboardingStore.closeWizard" />

As per coding guidelines frontend/src/**/*.vue: Use data-test attributes on Vue components for Playwright selectors; add them to new components.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@frontend/src/views/Dashboard.vue` at line 383, The OnboardingWizard component
mount lacks a stable Playwright selector; update the JSX/templating where
OnboardingWizard is used (the <OnboardingWizard
:show="onboardingStore.wizardOpen" `@close`="onboardingStore.closeWizard" />
instance) to include a data-test attribute (e.g., data-test="onboarding-wizard")
so tests can reliably target it; ensure the attribute is added on the component
tag and follows the existing data-test naming convention used across other Vue
components.
frontend/src/components/ServerCard.vue-32-38 (1)

32-38: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Blocked-count badge can go stale without memo dependency update

This view now depends on quarantine.blocked_count, but ServerCard is rendered under v-memo in frontend/src/views/Servers.vue and that memo key list doesn’t include blocked_count. The badge may not refresh when only blocked count changes.

🔧 Suggested fix
--- a/frontend/src/views/Servers.vue
+++ b/frontend/src/views/Servers.vue
@@
         v-memo="[
           server.connected,
           server.connecting,
           server.enabled,
           server.quarantined,
           server.tool_count,
           server.last_error,
           server.authenticated,
           server.quarantine?.pending_count,
-          server.quarantine?.changed_count
+          server.quarantine?.changed_count,
+          server.quarantine?.blocked_count
         ]"
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@frontend/src/components/ServerCard.vue` around lines 32 - 38, The badge uses
blockedToolCount (derived from quarantine.blocked_count) but ServerCard is
rendered inside a v-memo in Servers.vue whose memo key list doesn't include
quarantine.blocked_count, so the badge can go stale; update the memo keys in
Servers.vue to include the quarantine.blocked_count (or the computed
blockedToolCount) so ServerCard re-renders when that value changes, and verify
the computed/prop name blockedToolCount in ServerCard still maps to
quarantine.blocked_count correctly.
specs/047-cpu-hotpath-fix/verification/visual.md-24-30 (1)

24-30: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add a language label to the fenced log block.

Line 24 uses an unlabeled code fence, which triggers markdownlint MD040 and can fail doc lint pipelines.

Suggested patch
-```
+```text
 [6:29:04 PM] SSE servers.changed event received: Object
 [6:29:04 PM] Servers changed event received, updating in background... Object
 [6:29:04 PM] SSE servers.changed event received: Object
 [6:29:04 PM] Servers changed event received, updating in background... Object
 …  (10 events total)
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @specs/047-cpu-hotpath-fix/verification/visual.md around lines 24 - 30, The
fenced log block containing the sample SSE log lines (starting with "[6:29:04
PM] SSE servers.changed event received: Object") is an unlabeled code fence and
triggers markdownlint MD040; update that fence to include a language label
(e.g., change totext) so the block becomes a labeled text fence as
suggested.


</details>

</blockquote></details>
<details>
<summary>specs/047-cpu-hotpath-fix/tasks.md-115-123 (1)</summary><blockquote>

`115-123`: _⚠️ Potential issue_ | _🟡 Minor_ | _⚡ Quick win_

**Label the dependency diagram fence with a language.**

Line 115 uses an unlabeled code fence; adding a language (for example `text`) resolves markdownlint MD040.

 

<details>
<summary>Suggested patch</summary>

```diff
-```
+```text
 Phase 1 (Setup)
     └─ Phase 3 (US1) ──┐
                        ├─→ Phase 8 (Polish)
        Phase 4 (US2) ──┤
        Phase 5 (US3) ──┤   (US3 depends on US2's emit path)
        Phase 6 (US4) ──┤   (US4 depends on US2 having shipped)
        Phase 7 (US5) ──┘   (US5 depends on US2 having shipped)
 ```
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @specs/047-cpu-hotpath-fix/tasks.md around lines 115 - 123, The fenced ASCII
dependency diagram is missing a language identifier which triggers markdownlint
MD040; update the unlabeled code fence that wraps the diagram (the
triple-backtick block containing "Phase 1 (Setup) └─ Phase 3 (US1) ──┐ ...") to
include a language such as text (i.e., change totext) so the fence is
labeled and the lint rule is satisfied.


</details>

</blockquote></details>
<details>
<summary>specs/047-cpu-hotpath-fix/quickstart.md-89-94 (1)</summary><blockquote>

`89-94`: _⚠️ Potential issue_ | _🟡 Minor_ | _⚡ Quick win_

**Avoid machine-specific absolute paths in setup steps.**

Line 90 hardcodes a local user path, so the command won’t work for most environments.

 

<details>
<summary>Suggested patch</summary>

```diff
-mkdir -p /tmp/uitest-047 && cd /tmp/uitest-047
-ln -sfn /Users/user/repos/mcpproxy-go/e2e/playwright/node_modules ./node_modules
+REPO_ROOT=/absolute/path/to/mcpproxy-go
+mkdir -p /tmp/uitest-047 && cd /tmp/uitest-047
+ln -sfn "$REPO_ROOT/e2e/playwright/node_modules" ./node_modules
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@specs/047-cpu-hotpath-fix/quickstart.md` around lines 89 - 94, The setup uses
a machine-specific absolute path in the symlink command (ln -sfn
/Users/user/repos/mcpproxy-go/e2e/playwright/node_modules ./node_modules) which
will fail on other machines; change that line to create the symlink from a
relative or repo-root-resolved location instead (for example use ln -sfn
../e2e/playwright/node_modules ./node_modules or ln -sfn "$(git rev-parse
--show-toplevel)/e2e/playwright/node_modules" ./node_modules) so the command
works across environments and CI.
```

</details>

</blockquote></details>
<details>
<summary>specs/047-cpu-hotpath-fix/contracts/sse-events.md-7-9 (1)</summary><blockquote>

`7-9`: _⚠️ Potential issue_ | _🟡 Minor_ | _⚡ Quick win_

**Add fence languages to satisfy markdownlint MD040.**

This file has fenced blocks without language tags, which is currently flagged by static analysis.




<details>
<summary>Proposed patch</summary>

```diff
-```
+```http
 GET /events
 ```

-```
+```text
 event: servers.changed
 data: {
   "payload": {
     "reason": "<string: machine-readable cause>",
     "servers": [
       { /* contracts.Server, identical to GET /api/v1/servers data.servers[i] */ },
       ...
     ],
     "stats": { /* contracts.ServerStats, identical to GET /api/v1/servers data.stats */ }
   },
   "timestamp": <unix-seconds>
 }
 ```

-```
+```text
 event: servers.changed
 data: {
   "payload": { "reason": "<string>" },
   "timestamp": <unix-seconds>
 }
 ```
```
</details>


Also applies to: 19-32, 58-64

<details>
<summary>🤖 Prompt for AI Agents</summary>

Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @specs/047-cpu-hotpath-fix/contracts/sse-events.md around lines 7 - 9, The
markdown fences in specs/047-cpu-hotpath-fix/contracts/sse-events.md are missing
language tags; update each fenced block so the first GET /events fence is
labeled "http" and the SSE payload fences are labeled "text" (the blocks shown
around the "event: servers.changed" payloads and the additional occurrences
referenced at lines 19-32 and 58-64). Locate the fenced blocks in the file
(e.g., the three shown in the diff) and add the appropriate language identifiers
after the opening backticks (```http and ```text) to satisfy
markdownlint MD040.


</details>

</blockquote></details>
<details>
<summary>specs/047-cpu-hotpath-fix/data-model.md-20-25 (1)</summary><blockquote>

`20-25`: _⚠️ Potential issue_ | _🟡 Minor_ | _⚡ Quick win_

**Add a language tag to the state-transition code fence.**

Line 20 uses an untyped fenced block, which triggers MD040. Use ` ```text ` (or ` ```mermaid ` if you want diagram rendering).

<details>
<summary>🤖 Prompt for AI Agents</summary>

Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @specs/047-cpu-hotpath-fix/data-model.md around lines 20 - 25, The fenced
block containing the state-transition diagram (the block that starts with "no
event pending --produce--> pending set" and includes "pending set --drainer
ticks--> swap to nil, publish to bus") is missing a language tag and triggers
MD040; update the opening fence from totext (or ```mermaid if you want
diagram rendering) so the code fence is typed and the linter warning is
resolved.


</details>

</blockquote></details>
<details>
<summary>specs/048-tray-refetch-elimination/verification/report.md-14-19 (1)</summary><blockquote>

`14-19`: _⚠️ Potential issue_ | _🟡 Minor_ | _⚡ Quick win_

**Add language identifiers to fenced blocks to satisfy markdownlint.**

Line 14 and Line 32 use bare triple-backtick blocks; label them (e.g., `text`) to clear MD040.

 


Also applies to: 32-46

<details>
<summary>🤖 Prompt for AI Agents</summary>

Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @specs/048-tray-refetch-elimination/verification/report.md around lines 14 -
19, The markdown contains unlabeled fenced code blocks (the block starting with
the text "window: 2026-05-08T19:56:18 -> 2026-05-08T19:57:18" and the larger
block shown later around lines 32-46); add a language identifier (e.g., ```text)
to each opening triple-backtick fence to satisfy markdownlint MD040 so the
blocks are not bare. Ensure both opening fences are updated consistently and no
other fence backticks are changed.


</details>

</blockquote></details>
<details>
<summary>frontend/src/views/ServerDetail.vue-1408-1451 (1)</summary><blockquote>

`1408-1451`: _⚠️ Potential issue_ | _🟡 Minor_ | _⚡ Quick win_

**Keep blocked-count UI in sync after successful toggle.**

Line 1425 updates local tool approval state, but the stat at Line 127 reads `server.quarantine.blocked_count`, which is not updated here. This can leave “X blocked” stale until a later refresh/SSE.

 

<details>
<summary>Suggested local sync after success</summary>

```diff
   try {
     const response = await api.setToolEnabled(server.value.name, toolName, enabled)
     if (response.success) {
+      if (server.value?.quarantine) {
+        const delta = enabled ? -1 : 1
+        const nextBlocked = Math.max(0, (server.value.quarantine.blocked_count || 0) + delta)
+        server.value = {
+          ...server.value,
+          quarantine: { ...server.value.quarantine, blocked_count: nextBlocked },
+        }
+      }
       systemStore.addToast({
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@frontend/src/views/ServerDetail.vue` around lines 1408 - 1451, The UI updates
toolApprovals optimistically in toggleToolEnabled but doesn't update
server.quarantine.blocked_count, leaving the "X blocked" stat stale; after a
successful API response in toggleToolEnabled, adjust
server.value.quarantine.blocked_count based on the previous approval state
(prev) and the new enabled value: if we enabled a tool that was previously
disabled, decrement blocked_count; if we disabled a tool that was previously
enabled, increment blocked_count. Guard that server.value.quarantine exists and
blocked_count is a number, and only mutate blocked_count on response.success
(rollback to prev in the error paths remains unchanged).
```

</details>

</blockquote></details>
<details>
<summary>internal/security/scanner/service_test.go-1583-1584 (1)</summary><blockquote>

`1583-1584`: _⚠️ Potential issue_ | _🟡 Minor_ | _⚡ Quick win_

**Use per-test temp dirs instead of a shared `/tmp` path**

These tests all use the same hardcoded directory, which can cause interference when tests run concurrently or are retried in parallel CI.

  


<details>
<summary>Suggested fix</summary>

```diff
 func TestGetScanSummary_CachesNegativeResult(t *testing.T) {
     store := newCountingStorage(newMockStorage())
-    svc := NewService(store, NewRegistry("/tmp/scanner-cache-test", zap.NewNop()), nil, "/tmp/scanner-cache-test", zap.NewNop())
+    tmp := t.TempDir()
+    svc := NewService(store, NewRegistry(tmp, zap.NewNop()), nil, tmp, zap.NewNop())
```

Apply the same `t.TempDir()` pattern in the other two tests.
</details>


Also applies to: 1600-1601, 1616-1617

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/security/scanner/service_test.go` around lines 1583 - 1584, The
tests instantiate svc via NewService(..., NewRegistry("/tmp/scanner-cache-test",
...), ..., "/tmp/scanner-cache-test", ...) using a hardcoded shared path;
replace those hardcoded "/tmp/scanner-cache-test" values with a per-test
temporary directory from t.TempDir() (e.g., dir := t.TempDir()) and pass dir
into NewRegistry and NewService so each test gets its own isolated cache; apply
the same change to the other two test instances referenced around lines
1600-1601 and 1616-1617.
```

</details>

</blockquote></details>
<details>
<summary>specs/048-tray-refetch-elimination/tasks.md-100-107 (1)</summary><blockquote>

`100-107`: _⚠️ Potential issue_ | _🟡 Minor_ | _⚡ Quick win_

**Add a language label to the fenced block**

The fenced dependency diagram block is missing a language tag, which triggers MD040.

  


<details>
<summary>Proposed edit</summary>

```diff
-```
+```text
 Phase 1 (Setup)  ──┐
 Phase 2 (Found.) ──┴──→ US1 ──┐
                        US2 ──┤
                        US3 ──┼─→ Phase 8 (Polish: safety-net + verification)
                        US4 ──┤
                        US5 ──┘
 ```
```

</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @specs/048-tray-refetch-elimination/tasks.md around lines 100 - 107, The
fenced ASCII dependency diagram block (the triple-backtick block containing
"Phase 1 (Setup) ──┐" through "US5 ──┘") lacks a language tag which triggers
MD040; fix it by adding a language label (e.g., backticks followed by "text") to
the opening fence so the block becomes a labelled code block (```text) and save
the change.


</details>

</blockquote></details>
<details>
<summary>internal/httpapi/onboarding.go-100-106 (1)</summary><blockquote>

`100-106`: _⚠️ Potential issue_ | _🟡 Minor_ | _⚡ Quick win_

**Swagger failure codes don’t match the actual handler behavior.**

Line 100 and Line 123 document `503`, but the implementation returns `500` (`http.StatusInternalServerError`). This can break generated clients and contract expectations.

 


Also applies to: 123-124

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/httpapi/onboarding.go` around lines 100 - 106, The Swagger failure
annotations for the onboarding handlers are inconsistent with the
implementation: the handler function handleGetOnboardingState (which calls
computeOnboardingState and uses s.writeError to return
http.StatusInternalServerError) documents 503 but actually returns 500; update
the Swagger comment blocks above handleGetOnboardingState and the related
onboarding handler (the other block referencing 503) to document 500
(http.StatusInternalServerError) so the `@Failure` codes match the actual returned
status.
```

</details>

</blockquote></details>

</blockquote></details>

<details>
<summary>🧹 Nitpick comments (6)</summary><blockquote>

<details>
<summary>internal/upstream/managed/listtools_coalescing_test.go (1)</summary><blockquote>

`197-214`: _💤 Low value_

**Consider adding a stress test for the race between new leader and old waiter.**

This test verifies that stale results are cleared on leader acquisition, which is the intended behavior. However, as noted in `client.go`, this clearing could cause a waiter from a previous round to read nil if a new leader starts between the channel close and result read.

Consider adding a stress test that:
1. Has a leader complete and release
2. Immediately has a new leader acquire
3. Verifies that waiters from the first round still see their result

This would help detect the race condition under concurrent load.

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/upstream/managed/listtools_coalescing_test.go` around lines 197 -
214, Add a concurrent/stress test that reproduces the race between a completed
leader and an old waiter: create a new test (e.g.,
TestListTools_LeaderRaceBetweenRounds) that repeatedly runs the sequence using
the same test client mc and its acquireListToolsContext function — have one
goroutine act as the first leader that completes and sets
mc.listToolsLastResult/mc.listToolsLastErr and signals waiters, another
goroutine act as a waiter that reads the result, and a third goroutine rapidly
acquires a new leader (calling acquireListToolsContext and release) to clear
cached state; after each iteration assert the waiter still observes the original
round’s result (not nil) while checking mc.listToolsMu-protected fields
(listToolsLastResult, listToolsLastErr) to ensure the race is detected under
load.
```

</details>

</blockquote></details>
<details>
<summary>specs/048-tray-refetch-elimination/data-model.md (1)</summary><blockquote>

`1-3`: _💤 Low value_

**Consider rewording for readability (optional).**

The static analysis tool notes three consecutive sentences starting with "No":
- "No persistent storage changes. No new `appState` fields. No new types."

While clear and emphatic, you could optionally rephrase as:
- "This is a pure refactor with no persistent storage changes, no new `appState` fields, and no new types."

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@specs/048-tray-refetch-elimination/data-model.md` around lines 1 - 3,
Rephrase the three short sentences under the "Data Model — Tray Refetch
Elimination" header into a single clearer sentence; replace "No persistent
storage changes. No new `appState` fields. No new types." with something like
"This is a pure refactor with no persistent storage changes, no new `appState`
fields, and no new types" so the intent is conveyed in one concise line.
```

</details>

</blockquote></details>
<details>
<summary>specs/048-tray-refetch-elimination/plan.md (1)</summary><blockquote>

`34-42`: _💤 Low value_

**Consider adding language identifiers to fenced code blocks.**

The static analysis tool correctly identifies missing language specifiers on the code blocks at lines 34-42 and 45-53. Adding `text` or `plaintext` identifiers would improve rendering and accessibility.




Based on learnings: Static analysis tools flagged MD040 (fenced-code-language) warnings.


Also applies to: 45-53

<details>
<summary>🤖 Prompt for AI Agents</summary>

Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @specs/048-tray-refetch-elimination/plan.md around lines 34 - 42, The fenced
code blocks in the "Project Structure" section are missing language identifiers
(they currently start with ), which triggers MD040; update each block (the tree listing and any other plain-text blocks in that section) to use a language specifier such as text or ```plaintext so static analysis and renderers treat
them correctly and the MD040 warnings are resolved.


</details>

</blockquote></details>
<details>
<summary>internal/httpapi/server.go (1)</summary><blockquote>

`3800-3806`: _💤 Low value_

**Type assertion pattern is correct but consider a controller interface extension.**

The type assertion `s.controller.(interface { SetToolEnabled(...) })` works but means the handler silently fails (returns 501) when the controller doesn't support the method. This is acceptable for a feature-gated capability, but consider documenting this in the ServerController interface comments or extracting to a named interface for clarity.

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/httpapi/server.go` around lines 3800 - 3806, The inline type
assertion for s.controller checking SetToolEnabled should be made explicit:
extract the method signature into a named interface (e.g., ToolEnabler with
SetToolEnabled(serverName, toolName string, enabled bool, updatedBy string)
error), use that interface in the assertion (controller, ok :=
s.controller.(ToolEnabler)), and add a comment on the ServerController interface
explaining that ToolEnabler is an optional extension implemented by controllers
that support toggling tools; update any related docs/comments to reflect this
optional capability.
```

</details>

</blockquote></details>
<details>
<summary>frontend/src/views/ServerDetail.vue (1)</summary><blockquote>

`452-461`: _⚡ Quick win_

**Add `data-test` selectors to the new enable/disable control.**

The new per-tool toggle button is a primary interaction path but currently has no stable selector for Playwright.

 

<details>
<summary>Suggested selector attributes</summary>

```diff
                     <button
                       v-if="getToolApprovalStatus(tool.name) === 'approved'"
+                      :data-test="`tool-toggle-${tool.name}`"
                       class="btn btn-sm"
                       :class="isToolEnabled(tool.name) ? 'btn-warning' : 'btn-success'"
                       :disabled="isToolToggleLoading(tool.name)"
                       `@click`="toggleToolEnabled(tool.name, !isToolEnabled(tool.name))"
                     >
```
</details>

As per coding guidelines "`frontend/src/**/*.vue`: Use `data-test` attributes on Vue components for Playwright selectors; add them to new components".

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@frontend/src/views/ServerDetail.vue` around lines 452 - 461, Add stable
Playwright selectors by adding data-test attributes to the per-tool
enable/disable button and its loading spinner inside the ServerDetail component;
locate the button guarded by getToolApprovalStatus(tool.name) === 'approved' and
the related helpers isToolEnabled(tool.name), isToolToggleLoading(tool.name),
and toggleToolEnabled(tool.name), then add a data-test like
data-test="tool-toggle-<tool.name>" on the button (use the tool.name or tool.id
sanitized) and a data-test-loading like
data-test="tool-toggle-loading-<tool.name>" on the loading spinner so tests can
reliably select the control and its loading state.
```

</details>

</blockquote></details>
<details>
<summary>internal/httpapi/tool_quarantine_test.go (1)</summary><blockquote>

`123-135`: _⚡ Quick win_

**Assert request-correlation fields in new error-path tests.**

Line 134 and Line 151 only validate status codes. Please also assert `X-Request-Id` and `request_id` in the error JSON to lock the API contract.

 

<details>
<summary>Suggested test assertions</summary>

```diff
 func TestHandleSetToolEnabled_InvalidJSON(t *testing.T) {
@@
 	server.ServeHTTP(w, req)

 	assert.Equal(t, http.StatusBadRequest, w.Code)
+	assert.NotEmpty(t, w.Header().Get("X-Request-Id"))
+	var resp map[string]interface{}
+	require.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp))
+	_, ok := resp["request_id"]
+	assert.True(t, ok, "error response should include request_id")
 }
@@
 func TestHandleSetToolEnabled_ControllerError(t *testing.T) {
@@
 	server.ServeHTTP(w, req)

 	assert.Equal(t, http.StatusInternalServerError, w.Code)
+	assert.NotEmpty(t, w.Header().Get("X-Request-Id"))
+	var resp map[string]interface{}
+	require.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp))
+	_, ok := resp["request_id"]
+	assert.True(t, ok, "error response should include request_id")
 }
```
</details>

As per coding guidelines "`internal/httpapi/**/*.go`: Ensure all API responses include `X-Request-Id` header and error responses include `request_id` in JSON body for log correlation".


Also applies to: 137-152

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/httpapi/tool_quarantine_test.go` around lines 123 - 135, Update the
error-path tests (starting with TestHandleSetToolEnabled_InvalidJSON) to also
assert that the response includes the X-Request-Id header and that the JSON
error body contains a matching request_id field; after calling
server.ServeHTTP(w, req) parse w.Body as JSON, assert
w.Header().Get("X-Request-Id") is non-empty and that the decoded["request_id"]
equals that header, and add the same assertions to the other failing-path test
in this file that validates status codes.
```

</details>

</blockquote></details>

</blockquote></details>

<details>
<summary>🤖 Prompt for all review comments with AI agents</summary>

Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @CLAUDE.md:

  • Around line 160-206: The new "Verifying Web UI changes (Playwright + rich HTML
    report)" section in CLAUDE.md is too long and breaks the CLAUDE.md Size Check;
    move the full workflow (all scripts, example configs, and detailed step-by-step)
    into a separate docs file and replace this section in CLAUDE.md with a short
    summary plus a single link to the new doc; specifically extract the long shell
    snippets and the Playwright config example and put them in the new verification
    doc, keep a brief bullet list in CLAUDE.md, ensure the section header text
    "Verifying Web UI changes (Playwright + rich HTML report)" now points to that
    new doc, and re-run the size check so CLAUDE.md stays under the 40,000-character
    cap.

In @frontend/src/components/ConnectModal.vue:

  • Around line 192-197: Add missing data-test attributes in ConnectModal: add
    data-test identifiers on the modal container (e.g., ConnectModal root element),
    on each client list item (where clients.value and clientId are rendered), on the
    Disconnect and Connect buttons that call api.disconnectClient, and on the
    Connect All button; then run a Playwright sweep that exercises the
    connect/disconnect flows (including the server_name branch used when
    client?.server_name is absent) and captures screenshots into a self-contained
    HTML report to verify selectors and behavior, updating any failing selectors to
    use the new data-test attributes and re-running
    fetchClients/resultMessage/resultSuccess checks after disconnect.

In @frontend/src/components/OnboardingWizard.vue:

  • Around line 808-872: fetchImportSources correctly sets per-source previewError
    but the template only shows importSourcesWithServers so errored sources vanish;
    update the computed/filtering logic (the importSourcesWithServers computation or
    wherever the template derives its list) to include sources that have a non-empty
    previewError in addition to sources with serverCount > 0 (i.e., filter
    importSources for p.exists && (p.serverCount > 0 || p.previewError)), leaving
    fetchImportSources and the previewError assignments unchanged so the UI surfaces
    parse/permission failures instead of collapsing to the empty state.
  • Around line 921-947: The import flow treats any transport-level errors as
    failures but ignores summary-level failures (totalFailed > 0), so the UI still
    marks success, clears selection, shows a success toast and may call
    onboarding.markServerCompleted; update the post-import logic around
    selectionImportOk, selectionImportMessage, onboarding.markServerCompleted and
    systemStore.addToast to treat totalFailed > 0 as a partial/failure: if
    totalFailed > 0 set selectionImportOk.value = false (do not clear
    selection.value), produce an informative failure/partial message (include counts
    and which items failed), avoid calling onboarding.markServerCompleted when
    failures exist, and surface an error/partial toast via systemStore.addToast
    instead of the success toast; ensure existing transport errors handling (errors
    array) remains unchanged.
  • Around line 819-833: The object literal used to build the sources array (const
    sources: ImportSource[] = ...) includes unused properties importBusy,
    importMessage, and importMessageOk that are not part of the ImportSource
    interface and cause TypeScript strict build errors; remove those three
    properties from the mapped object so the created objects match the ImportSource
    shape (keep name, format, path, exists, previewLoading, previewError,
    serverCount, serverNames) in the mapping inside OnboardingWizard.vue.

In @frontend/src/views/Security.vue:

  • Line 700: The code currently sets initialized.value = true inside a finally
    block so failed refreshes mark the app as initialized; change the logic so
    initialized.value is only set to true on successful refresh (e.g., in the
    success/then branch or after a successful await of the refresh call) and remove
    it from the finally; locate the refresh attempt and the finally where
    initialized.value is set and move the assignment into the success path (or set
    an explicit flag like refreshSucceeded before assigning initialized) so failed
    refreshes do not flip initialized.

In @internal/connect/connect.go:

  • Around line 682-690: The function unmarshalLenientJSON and the
    trailingCommaPattern currently use a regex to strip trailing commas which
    corrupts commas inside JSON strings; replace this brittle approach by using a
    proper JSON-with-comments/trailing-commas parser (e.g., hujson or jsonc) inside
    unmarshalLenientJSON so you first sanitize/normalize the raw bytes with that
    library and then call json.Unmarshal on the normalized output, or alternatively
    implement a token-aware removal routine (string-state aware scanner) inside
    unmarshalLenientJSON to only remove commas that are outside string literals;
    update usages of trailingCommaPattern and remove the regex-based ReplaceAll
    logic so string contents are preserved.

In @internal/httpapi/import.go:

  • Around line 395-405: After applying caller renames (the rename map to
    result.Imported[i].Server.Name), run a post-rename validation that checks each
    renamed Server.Name for collisions against existing servers and for duplicates
    within the renamed batch; if any collision or intra-batch duplicate is found,
    mark that entry as failed/skipped (removing it from the list sent to AddServer)
    and populate the failure reason while preserving OriginalName in the response,
    instead of letting AddServer emit warnings for name conflicts. Implement this by
    iterating result.Imported after the rename pass, building a set of existing
    names (querying the same lookup used by AddServer) plus a set for batch-names to
    detect duplicates, and move conflicting entries out of the import-to-add list
    and into the failed/skipped collection with clear messages.

In @internal/httpapi/onboarding.go:

  • Around line 127-132: Remove the ContentLength > 0 guard so chunked requests
    are accepted: change the body-read logic to attempt decoding whenever r.Body !=
    nil (i.e., call json.NewDecoder(r.Body).Decode(&req) and handle the error with
    s.writeError as already done), ensuring requests with Transfer-Encoding: chunked
    (ContentLength == -1) are processed; also update the swagger comment annotations
    for this handler (the @Failure entries above the handler) from 503 to 500 to
    match the actual s.writeError calls that return http.StatusInternalServerError.

In @internal/httpapi/server.go:

  • Around line 3784-3818: Add the new POST
    /api/v1/servers/{id}/tools/{tool}/enabled operation to oas/swagger.yaml (under
    servers paths) with request/response schema matching the handler (body:
    {"enabled": boolean}, 200 response containing server_name, tool_name, enabled
    and request_id). Ensure the handler output includes X-Request-Id by plumbing the
    header into the JSON response path: update writeJSON (and therefore
    writeSuccess) to set the X-Request-Id response header (read from incoming
    r.Header["X-Request-Id"] or generate one if absent) and include a request_id
    field in the success JSON payload emitted by writeSuccess so
    handleSetToolEnabled returns the header and request_id in body consistently.

In @internal/runtime/event_bus.go:

  • Around line 39-45: newServersChangedCoalescer currently accepts any duration
    but start() later calls time.NewTicker(c.interval) which panics for interval <=
    0; update newServersChangedCoalescer to validate the interval argument (in the
    constructor) and coerce non-positive values to a safe default (e.g., time.Second
    or time.Millisecond) before storing it on the serversChangedCoalescer struct so
    start() never calls NewTicker with a non-positive duration; refer to
    newServersChangedCoalescer and serversChangedCoalescer (and ensure any other
    callers that construct this coalescer get the validated interval).
  • Around line 168-192: The code currently calls
    r.managementService.(serversLister).ListServers and builds the full payload
    before checking r.coalescer; move the expensive ListServers/payload population
    behind the coalescer check so coalescing can short-circuit bursts. Concretely:
    in emitServersChanged, first construct a minimal payload (e.g., reason only),
    create evt := newEvent(EventTypeServersChanged, minimalPayload) and if
    r.coalescer != nil submit and return; only when r.coalescer is nil (or when
    actually dispatching the final event) perform the serversLister.ListServers
    call, run r.redactServerHeaders on the results, set payload["servers"] and
    payload["stats"], then create/emit the full event. Ensure you still log
    ListServers errors and reference r.managementService, serversLister,
    ListServers, r.redactServerHeaders, r.coalescer, newEvent and
    EventTypeServersChanged when making the change.

In @internal/runtime/lifecycle.go:

  • Around line 341-371: The current loop treats any knownServer not in
    processedServers as "missing" and reapplies r.lastGoodTools[serverName], but
    that incorrectly reuses snapshots when a server legitimately appeared in
    discovery with zero tools (it wasn't added to toolsByServer/processedServers).
    Update the logic so you only reapply last-good snapshots when the server truly
    did not appear in the latest discovery results: add or use an explicit set that
    records servers seen in the latest discovery pass (e.g., serversSeenInDiscovery
    or toolsByServer map) and skip snapshot re-apply if the server was present in
    discovery even if it reported zero tools; change the conditional around
    processedServers/knownServers accordingly before calling
    r.applyDifferentialToolUpdate and retain the existing checks of
    r.upstreamManager.GetClient and r.lastGoodTools.

In @internal/server/mcp.go:

  • Around line 647-648: The advertised operation enum in mcp.Enum includes
    "quarantine_server" but the dispatcher switch still checks for "quarantine",
    causing unknown-operation errors; update the dispatcher to recognize
    "quarantine_server" (or accept both "quarantine" and "quarantine_server") in the
    switch/case that currently matches the string "quarantine" so it aligns with
    mcp.Description/mcp.Enum and the agent-facing schema (locate the switch that
    branches on the quarantine operation string and modify the case labels
    accordingly).
  • Around line 4553-4583: The isToolCallable helper currently only checks server
    enablement and approval.Disabled, so update isToolCallable to mirror the
    execution path's full guard logic: ensure you check serverConfig.Quarantined
    (match the quarantined check used during execution), and verify the tool
    approval state from storage.GetToolApproval for non-callable states (e.g.,
    pending or changed statuses) rather than only inspection of approval.Disabled;
    use the same status values/enum names and logic that the execution path uses
    (the code around retrieve_tools and getVisibleToolCount and the execution checks
    at lines referenced in the review) so retrieve_tools and getVisibleToolCount
    will only advertise truly callable tools. Ensure you reference and use the same
    functions/fields: p.storage.GetUpstreamServer, p.storage.GetToolApproval,
    serverConfig.Enabled, serverConfig.Quarantined, and the approval.Status/Disabled
    semantics used by the execution path.
  • Around line 2496-2508: In handleSetToolEnabledByName guard
    p.mainServer.runtime for nil before calling SetToolEnabled: check if
    p.mainServer == nil || p.mainServer.runtime == nil and return an
    mcp.NewToolResultError (e.g. "Runtime not initialized" or similar) so the
    handler returns a proper tool error instead of panicking; then proceed to call
    p.mainServer.runtime.SetToolEnabled(serverName, toolName, enabled, "mcp") only
    after the nil check.
  • Around line 2592-2599: The fallback call to client.ListTools uses
    context.Background(), causing unbounded upstream I/O; change it to use the
    request-scoped context (the ctx used by the surrounding management handler) so
    the ListTools call is bounded by the incoming request deadline/cancellation.
    Locate the block referencing toolCount, client.ListTools(...) and
    p.isToolCallable(server.Name, ...) and replace the background context with the
    existing request context (e.g., ctx) so the call is cancellable and respects
    timeouts.

In @internal/server/server.go:

  • Around line 1803-1806: The profiling rates set with
    gruntime.SetBlockProfileRate and gruntime.SetMutexProfileFraction before calling
    pprofMux.ServeHTTP remain enabled process-wide; update the pprof handler so you
    immediately defer resetting both rates to 0 (call
    gruntime.SetBlockProfileRate(0) and gruntime.SetMutexProfileFraction(0)) right
    after setting them and before invoking pprofMux.ServeHTTP(w, r) so the resets
    always run (even on panic) and profiling overhead does not persist after the
    request.

Outside diff comments:
In @internal/upstream/managed/client.go:

  • Around line 424-472: The race is that acquireListToolsContext clears
    listToolsLastResult when a new leader starts, allowing a waiter woken by a
    closed listToolsWaitCh to read nil; fix by adding a generation id and
    associating results with that generation: introduce mc.listToolsGen (uint64)
    incremented inside acquireListToolsContext when a new leader is created, have
    publishListToolsResult store the generation number alongside
    listToolsLastResult/listToolsLastErr, and have waiters after the channel close
    read both the result and its generation under mc.listToolsMu and only accept the
    result if the generation matches the generation they observed when waking
    (otherwise treat as no-result and retry/return appropriate error). This makes
    the result stable for the waking waiters without delaying clearing in
    acquireListToolsContext.

Minor comments:
In @docs/getting-started/installation.md:

  • Around line 90-93: Add the missing systemd user commands under the "Enable it
    with:" line so users can actually enable and start the mcpproxy unit: include
    the commands to reload user units and enable+start the service (systemctl --user
    daemon-reload and systemctl --user enable --now mcpproxy.service) formatted as a
    bash code block immediately after the "Enable it with:" sentence; reference the
    mcpproxy.service systemd unit and ensure the block is properly fenced.

In @frontend/src/components/ServerCard.vue:

  • Around line 32-38: The badge uses blockedToolCount (derived from
    quarantine.blocked_count) but ServerCard is rendered inside a v-memo in
    Servers.vue whose memo key list doesn't include quarantine.blocked_count, so the
    badge can go stale; update the memo keys in Servers.vue to include the
    quarantine.blocked_count (or the computed blockedToolCount) so ServerCard
    re-renders when that value changes, and verify the computed/prop name
    blockedToolCount in ServerCard still maps to quarantine.blocked_count correctly.

In @frontend/src/views/Dashboard.vue:

  • Line 383: The OnboardingWizard component mount lacks a stable Playwright
    selector; update the JSX/templating where OnboardingWizard is used (the
    <OnboardingWizard :show="onboardingStore.wizardOpen"
    @close="onboardingStore.closeWizard" /> instance) to include a data-test
    attribute (e.g., data-test="onboarding-wizard") so tests can reliably target it;
    ensure the attribute is added on the component tag and follows the existing
    data-test naming convention used across other Vue components.

In @frontend/src/views/ServerDetail.vue:

  • Around line 1408-1451: The UI updates toolApprovals optimistically in
    toggleToolEnabled but doesn't update server.quarantine.blocked_count, leaving
    the "X blocked" stat stale; after a successful API response in
    toggleToolEnabled, adjust server.value.quarantine.blocked_count based on the
    previous approval state (prev) and the new enabled value: if we enabled a tool
    that was previously disabled, decrement blocked_count; if we disabled a tool
    that was previously enabled, increment blocked_count. Guard that
    server.value.quarantine exists and blocked_count is a number, and only mutate
    blocked_count on response.success (rollback to prev in the error paths remains
    unchanged).

In @internal/httpapi/onboarding.go:

  • Around line 100-106: The Swagger failure annotations for the onboarding
    handlers are inconsistent with the implementation: the handler function
    handleGetOnboardingState (which calls computeOnboardingState and uses
    s.writeError to return http.StatusInternalServerError) documents 503 but
    actually returns 500; update the Swagger comment blocks above
    handleGetOnboardingState and the related onboarding handler (the other block
    referencing 503) to document 500 (http.StatusInternalServerError) so the
    @Failure codes match the actual returned status.

In @internal/secureenv/manager.go:

  • Around line 294-296: In buildEnhancedPath, when existingPath == "" the
    function currently returns strings.Join(m.pathDiscovery.DiscoveredPaths, sep)
    without checking m.config.EnhancePath; update the logic to first honor
    m.config.EnhancePath and only return the discovered paths when EnhancePath is
    true (otherwise return an empty string or the unmodified existingPath), and
    apply the same guard to the other branch referenced around the second occurrence
    (the block handling the non-empty existingPath at the 314-316 area) so
    m.config.EnhancePath is consistently respected.

In @internal/security/scanner/service_test.go:

  • Around line 1583-1584: The tests instantiate svc via NewService(...,
    NewRegistry("/tmp/scanner-cache-test", ...), ..., "/tmp/scanner-cache-test",
    ...) using a hardcoded shared path; replace those hardcoded
    "/tmp/scanner-cache-test" values with a per-test temporary directory from
    t.TempDir() (e.g., dir := t.TempDir()) and pass dir into NewRegistry and
    NewService so each test gets its own isolated cache; apply the same change to
    the other two test instances referenced around lines 1600-1601 and 1616-1617.

In @README.md:

  • Around line 79-86: The README statement “Both packages ship a hardened
    systemd unit and start the service automatically” is inaccurate for the Arch
    AUR mcpproxy-bin; update the sentence to scope auto-start behavior only to the
    apt/dnf packages and add a note for the AUR package that users must manually
    enable/start the service (e.g., via systemctl --user enable --now mcpproxy.service). Locate the sentence containing "Both packages ship a
    hardened systemd unit..." and replace it with a scoped sentence plus a brief
    instruction mentioning the AUR package name mcpproxy-bin and the manual
    enable/start step.

In @specs/046-local-first-onboarding/spec.md:

  • Line 243: The fenced code block in the spec's markdown uses a bare fence which triggers markdownlint MD040; update the opening fence used around the onboarding change log (the block starting with "feat(046): adaptive onboarding wizard with state-based steps") to include a language identifier (for example usetext) so the code fence becomes text and keep the closing
    unchanged; ensure the fence around that block is updated so linting passes.

In @specs/047-cpu-hotpath-fix/contracts/sse-events.md:

  • Around line 7-9: The markdown fences in
    specs/047-cpu-hotpath-fix/contracts/sse-events.md are missing language tags;
    update each fenced block so the first GET /events fence is labeled "http" and
    the SSE payload fences are labeled "text" (the blocks shown around the "event:
    servers.changed" payloads and the additional occurrences referenced at lines
    19-32 and 58-64). Locate the fenced blocks in the file (e.g., the three shown in
    the diff) and add the appropriate language identifiers after the opening
    backticks (```http and ```text) to satisfy markdownlint MD040.

In @specs/047-cpu-hotpath-fix/data-model.md:

  • Around line 20-25: The fenced block containing the state-transition diagram
    (the block that starts with "no event pending --produce--> pending set" and
    includes "pending set --drainer ticks--> swap to nil, publish to bus") is
    missing a language tag and triggers MD040; update the opening fence from totext (or ```mermaid if you want diagram rendering) so the code fence is typed
    and the linter warning is resolved.

In @specs/047-cpu-hotpath-fix/quickstart.md:

  • Around line 89-94: The setup uses a machine-specific absolute path in the
    symlink command (ln -sfn
    /Users/user/repos/mcpproxy-go/e2e/playwright/node_modules ./node_modules) which
    will fail on other machines; change that line to create the symlink from a
    relative or repo-root-resolved location instead (for example use ln -sfn
    ../e2e/playwright/node_modules ./node_modules or ln -sfn "$(git rev-parse
    --show-toplevel)/e2e/playwright/node_modules" ./node_modules) so the command
    works across environments and CI.

In @specs/047-cpu-hotpath-fix/tasks.md:

  • Around line 115-123: The fenced ASCII dependency diagram is missing a language
    identifier which triggers markdownlint MD040; update the unlabeled code fence
    that wraps the diagram (the triple-backtick block containing "Phase 1 (Setup) └─
    Phase 3 (US1) ──┐ ...") to include a language such as text (i.e., change ``` to

In `@specs/047-cpu-hotpath-fix/verification/visual.md`:
- Around line 24-30: The fenced log block containing the sample SSE log lines
(starting with "[6:29:04 PM] SSE servers.changed event received: Object") is an
unlabeled code fence and triggers markdownlint MD040; update that fence to
include a language label (e.g., change ``` to ```text) so the block becomes a
labeled text fence as suggested.

In `@specs/048-tray-refetch-elimination/tasks.md`:
- Around line 100-107: The fenced ASCII dependency diagram block (the
triple-backtick block containing "Phase 1 (Setup)  ──┐" through "US5 ──┘") lacks
a language tag which triggers MD040; fix it by adding a language label (e.g.,
backticks followed by "text") to the opening fence so the block becomes a
labelled code block (```text) and save the change.

In `@specs/048-tray-refetch-elimination/verification/report.md`:
- Around line 14-19: The markdown contains unlabeled fenced code blocks (the
block starting with the text "window: 2026-05-08T19:56:18 ->
2026-05-08T19:57:18" and the larger block shown later around lines 32-46); add a
language identifier (e.g., ```text) to each opening triple-backtick fence to
satisfy markdownlint MD040 so the blocks are not bare. Ensure both opening
fences are updated consistently and no other fence backticks are changed.

---

Nitpick comments:
In `@frontend/src/views/ServerDetail.vue`:
- Around line 452-461: Add stable Playwright selectors by adding data-test
attributes to the per-tool enable/disable button and its loading spinner inside
the ServerDetail component; locate the button guarded by
getToolApprovalStatus(tool.name) === 'approved' and the related helpers
isToolEnabled(tool.name), isToolToggleLoading(tool.name), and
toggleToolEnabled(tool.name), then add a data-test like
data-test="tool-toggle-<tool.name>" on the button (use the tool.name or tool.id
sanitized) and a data-test-loading like
data-test="tool-toggle-loading-<tool.name>" on the loading spinner so tests can
reliably select the control and its loading state.

In `@internal/httpapi/server.go`:
- Around line 3800-3806: The inline type assertion for s.controller checking
SetToolEnabled should be made explicit: extract the method signature into a
named interface (e.g., ToolEnabler with SetToolEnabled(serverName, toolName
string, enabled bool, updatedBy string) error), use that interface in the
assertion (controller, ok := s.controller.(ToolEnabler)), and add a comment on
the ServerController interface explaining that ToolEnabler is an optional
extension implemented by controllers that support toggling tools; update any
related docs/comments to reflect this optional capability.

In `@internal/httpapi/tool_quarantine_test.go`:
- Around line 123-135: Update the error-path tests (starting with
TestHandleSetToolEnabled_InvalidJSON) to also assert that the response includes
the X-Request-Id header and that the JSON error body contains a matching
request_id field; after calling server.ServeHTTP(w, req) parse w.Body as JSON,
assert w.Header().Get("X-Request-Id") is non-empty and that the
decoded["request_id"] equals that header, and add the same assertions to the
other failing-path test in this file that validates status codes.

In `@internal/upstream/managed/listtools_coalescing_test.go`:
- Around line 197-214: Add a concurrent/stress test that reproduces the race
between a completed leader and an old waiter: create a new test (e.g.,
TestListTools_LeaderRaceBetweenRounds) that repeatedly runs the sequence using
the same test client mc and its acquireListToolsContext function — have one
goroutine act as the first leader that completes and sets
mc.listToolsLastResult/mc.listToolsLastErr and signals waiters, another
goroutine act as a waiter that reads the result, and a third goroutine rapidly
acquires a new leader (calling acquireListToolsContext and release) to clear
cached state; after each iteration assert the waiter still observes the original
round’s result (not nil) while checking mc.listToolsMu-protected fields
(listToolsLastResult, listToolsLastErr) to ensure the race is detected under
load.

In `@specs/048-tray-refetch-elimination/data-model.md`:
- Around line 1-3: Rephrase the three short sentences under the "Data Model —
Tray Refetch Elimination" header into a single clearer sentence; replace "No
persistent storage changes. No new `appState` fields. No new types." with
something like "This is a pure refactor with no persistent storage changes, no
new `appState` fields, and no new types" so the intent is conveyed in one
concise line.

In `@specs/048-tray-refetch-elimination/plan.md`:
- Around line 34-42: The fenced code blocks in the "Project Structure" section
are missing language identifiers (they currently start with ```), which triggers
MD040; update each block (the tree listing and any other plain-text blocks in
that section) to use a language specifier such as ```text or ```plaintext so
static analysis and renderers treat them correctly and the MD040 warnings are
resolved.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

Comment thread CLAUDE.md
Comment on lines +160 to +206
### Verifying Web UI changes (Playwright + rich HTML report)

When you modify the Web UI (any Vue file under `frontend/src/`), verify it end-to-end with a Playwright sweep that captures screenshots and packages them into a self-contained HTML report. This is the same workflow used to verify Spec 046 v2 — see `specs/046-local-first-onboarding/verification/` for a worked example.

The pattern, in order:

1. **Stand up a fresh mcpproxy.** Use a throwaway data-dir so persisted state doesn't bleed between runs:
```bash
pkill -f 'mcpproxy serve.*<port>' 2>/dev/null; sleep 1
rm -rf /tmp/mcpproxy-uitest/{config.db,index.bleve,logs} 2>/dev/null
cat > /tmp/mcpproxy-uitest/mcp_config.json <<'EOF'
{ "listen": "127.0.0.1:18081", "data_dir": "/tmp/mcpproxy-uitest", "api_key": "uitest", "enable_web_ui": true, "enable_socket": false, "telemetry": {"enabled": false}, "mcpServers": [] }
EOF
./mcpproxy serve --config=/tmp/mcpproxy-uitest/mcp_config.json --listen=127.0.0.1:18081 --log-level=info > /tmp/mcpproxy-uitest/server.log 2>&1 &
until curl -sf -H "X-API-Key: uitest" http://127.0.0.1:18081/api/v1/status >/dev/null; do sleep 1; done
```
2. **Reuse the existing Playwright install.** `e2e/playwright/node_modules` already has Playwright + Chromium 1217. Symlink it into your scratch dir:
```bash
mkdir -p /tmp/uitest && cd /tmp/uitest
ln -sfn /Users/user/repos/mcpproxy-go/e2e/playwright/node_modules ./node_modules
```
3. **Pin the Chromium binary in `playwright.config.ts`** so Playwright doesn't try to download a different version:
```ts
import { defineConfig } from '@playwright/test';
export default defineConfig({
testDir: '.', timeout: 30000, fullyParallel: false, workers: 1, retries: 0,
use: {
headless: true,
viewport: { width: 1440, height: 900 },
launchOptions: {
executablePath: '/Users/user/Library/Caches/ms-playwright/chromium-1217/chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing',
},
},
});
```
4. **Write the spec.** Use `data-test` attributes already on the components (the project convention). For new components, add them. Drive scenarios with `page.locator('[data-test="..."]')`. Always use `page.waitForLoadState('domcontentloaded')` — `networkidle` hangs because of the SSE channel. Snapshot each state with `page.screenshot({ path: ... })`. Number screenshots in execution order so the report renders left-to-right.
5. **Run.** `./node_modules/.bin/playwright test --reporter=list`. Iterate until green.
6. **Build the rich HTML report.** A short Python script that base64-embeds each PNG and wraps it in a styled `<details>` per scenario produces a single self-contained HTML file the user can open offline. Pattern: top summary card with pass/fail counts, then one collapsible per scenario with `Expected` / `Observed` / inline screenshot. The reference implementation is `/tmp/wizard-v2-verify/build-report.py` from the v2 work — clone it and update the `SCENARIOS` list. Output goes to `specs/<feature>/verification/report.html`.
7. **Drop screenshots + report alongside the spec.** Always commit them with the spec changes — they're part of the trace.
8. **Surface the report.** End your reply with `open <path-to-report.html>` so the user can review without re-running the suite.

Key gotchas:
- The wizard's `<dialog>` element renders as `[open]` only when the Vue store sets it. To assert open/closed state robustly, query the dialog property in `page.evaluate()`, not aria-hidden or styling.
- `pkill -f 'mcpproxy ... <port>'` matches the merge-detection regex in user hooks. Ignore the `Merge-detection trigger` notifications when no actual merge happened.
- The default config from a stub file does NOT trigger `applyFirstRunDockerIsolation` — that only runs when the config file is absent at boot. To test the "Docker auto-enabled" path, either let mcpproxy create the config or pre-set `docker_isolation.enabled: true` in your stub.
- For browser-driven verification of subtle states (badge counts, empty/loaded transitions), prefer the Playwright spec over ad-hoc screenshots from the chrome-in-chrome MCP — the spec is reproducible and a CI agent can re-run it.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Trim or relocate this new section — it currently breaks CI size limits.

CLAUDE.md Size Check is failing because this addition pushes the file past the 40,000-character cap. Please move the long workflow to a separate doc (and link it here) or aggressively compress this section so the check passes.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@CLAUDE.md` around lines 160 - 206, The new "Verifying Web UI changes
(Playwright + rich HTML report)" section in CLAUDE.md is too long and breaks the
CLAUDE.md Size Check; move the full workflow (all scripts, example configs, and
detailed step-by-step) into a separate docs file and replace this section in
CLAUDE.md with a short summary plus a single link to the new doc; specifically
extract the long shell snippets and the Playwright config example and put them
in the new verification doc, keep a brief bullet list in CLAUDE.md, ensure the
section header text "Verifying Web UI changes (Playwright + rich HTML report)"
now points to that new doc, and re-run the size check so CLAUDE.md stays under
the 40,000-character cap.

Comment on lines +192 to +197
const client = clients.value.find(c => c.id === clientId)
const response = await api.disconnectClient(clientId, client?.server_name || 'mcpproxy')
if (response.success && response.data) {
resultMessage.value = response.data.message || `Disconnected from ${clientId}`
resultSuccess.value = true
// Update local state
const client = clients.value.find(c => c.id === clientId)
if (client) client.connected = false
await fetchClients()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Check if Playwright tests exist for ConnectModal server_name handling

rg -nP --type=ts -g '**/test/**' -g '**/*.spec.ts' -C3 'disconnectClient.*server.*name|server_name.*disconnect'

Repository: HaloCollar/mcpproxy-go

Length of output: 48


🏁 Script executed:

# Find ConnectModal.vue and examine it
find . -name "ConnectModal.vue" -type f

Repository: HaloCollar/mcpproxy-go

Length of output: 109


🏁 Script executed:

# Search for Playwright test files related to ConnectModal
fd -t f -e spec.ts -e test.ts | xargs rg -l "ConnectModal" 2>/dev/null || echo "No test files found"

Repository: HaloCollar/mcpproxy-go

Length of output: 108


🏁 Script executed:

# Check if there are any Playwright configuration files and test directories
find . -name "playwright.config.*" -o -name ".playwright" -type d | head -20

Repository: HaloCollar/mcpproxy-go

Length of output: 104


🏁 Script executed:

# Look at the ConnectModal.vue file to check for data-test attributes and actual code
cat frontend/src/components/ConnectModal.vue

Repository: HaloCollar/mcpproxy-go

Length of output: 7624


Add data-test attributes and verify end-to-end with Playwright.

The coding guidelines require data-test attributes on Vue components for Playwright selectors. The ConnectModal component is missing these on interactive elements (modal dialog, buttons, client items). Additionally, per guidelines, all Web UI modifications—including the server_name parameter addition to the disconnect flow—must be verified with a Playwright sweep that captures screenshots into a self-contained HTML report. Add the missing attributes first to enable proper Playwright testing.

Key elements needing data-test attributes:

  • Modal dialog
  • Disconnect/Connect buttons
  • Client list items
  • Connect All button
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@frontend/src/components/ConnectModal.vue` around lines 192 - 197, Add missing
data-test attributes in ConnectModal: add data-test identifiers on the modal
container (e.g., ConnectModal root element), on each client list item (where
clients.value and clientId are rendered), on the Disconnect and Connect buttons
that call api.disconnectClient, and on the Connect All button; then run a
Playwright sweep that exercises the connect/disconnect flows (including the
server_name branch used when client?.server_name is absent) and captures
screenshots into a self-contained HTML report to verify selectors and behavior,
updating any failing selectors to use the new data-test attributes and
re-running fetchClients/resultMessage/resultSuccess checks after disconnect.

Comment on lines +808 to +872
async function fetchImportSources() {
// Spec 046 v2: parity with the Clients tab. Discover canonical client
// config paths, then for each existing one, run a no-side-effect preview
// to count importable servers.
loadingImportSources.value = true
try {
const res = await api.getCanonicalConfigPaths()
if (!res.success || !res.data) {
importSources.value = []
return
}
const sources: ImportSource[] = res.data.paths
.filter(p => p.exists)
.map(p => ({
name: p.name,
format: p.format,
path: p.path,
exists: true,
previewLoading: true,
previewError: '',
serverCount: 0,
serverNames: [],
importBusy: '',
importMessage: '',
importMessageOk: false,
}))
importSources.value = sources

// Run previews in parallel — each is bounded by the user's local file
// size, so this is safe even with many sources.
await Promise.all(
sources.map(async (src, idx) => {
try {
const r = await api.importServersFromPath({
path: src.path,
format: src.format,
preview: true,
})
if (r.success && r.data) {
const imported = r.data.imported ?? []
importSources.value[idx] = {
...src,
previewLoading: false,
serverCount: imported.length,
serverNames: imported.map(s => s.name),
}
} else {
importSources.value[idx] = {
...src,
previewLoading: false,
previewError: r.error ?? 'preview failed',
}
}
} catch (err) {
importSources.value[idx] = {
...src,
previewLoading: false,
previewError: (err as Error).message,
}
}
})
)
} finally {
loadingImportSources.value = false
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Surface per-source preview failures instead of collapsing them into the empty state.

previewError is populated here, but the template only renders importSourcesWithServers, so errored sources disappear and the user just sees “No client configs with importable servers detected.” A parse/permission failure on every source will look like a clean empty result and block the import flow without any recovery path.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@frontend/src/components/OnboardingWizard.vue` around lines 808 - 872,
fetchImportSources correctly sets per-source previewError but the template only
shows importSourcesWithServers so errored sources vanish; update the
computed/filtering logic (the importSourcesWithServers computation or wherever
the template derives its list) to include sources that have a non-empty
previewError in addition to sources with serverCount > 0 (i.e., filter
importSources for p.exists && (p.serverCount > 0 || p.previewError)), leaving
fetchImportSources and the previewError assignments unchanged so the UI surfaces
parse/permission failures instead of collapsing to the empty state.

Comment on lines +819 to +833
const sources: ImportSource[] = res.data.paths
.filter(p => p.exists)
.map(p => ({
name: p.name,
format: p.format,
path: p.path,
exists: true,
previewLoading: true,
previewError: '',
serverCount: 0,
serverNames: [],
importBusy: '',
importMessage: '',
importMessageOk: false,
}))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

# First, let's check if the file exists and examine the interface definition
fd -t f "OnboardingWizard.vue" frontend/src/

Repository: HaloCollar/mcpproxy-go

Length of output: 111


🏁 Script executed:

# Read the file to inspect the ImportSource interface definition and the problematic code
cat -n frontend/src/components/OnboardingWizard.vue | sed -n '533,542p'

Repository: HaloCollar/mcpproxy-go

Length of output: 323


🏁 Script executed:

# Now check the actual object literal around lines 819-833
cat -n frontend/src/components/OnboardingWizard.vue | sed -n '819,833p'

Repository: HaloCollar/mcpproxy-go

Length of output: 560


🏁 Script executed:

# Search for usage of the extra properties
rg "importBusy|importMessage|importMessageOk" frontend/src/components/OnboardingWizard.vue

Repository: HaloCollar/mcpproxy-go

Length of output: 363


🏁 Script executed:

# Also check the tsconfig to see TypeScript settings
cat frontend/tsconfig.json 2>/dev/null || cat tsconfig.json 2>/dev/null || echo "No tsconfig found in expected locations"

Repository: HaloCollar/mcpproxy-go

Length of output: 396


🏁 Script executed:

# Check if there are any other references to these properties in other files
rg "importBusy|importMessage|importMessageOk" frontend/src/ --type vue --type ts --type tsx

Repository: HaloCollar/mcpproxy-go

Length of output: 94


🏁 Script executed:

# Let's search for where 'sources' is used and if these properties are accessed
rg "sources\[|sources\.|sources:" frontend/src/components/OnboardingWizard.vue -A 2 -B 2

Repository: HaloCollar/mcpproxy-go

Length of output: 740


🏁 Script executed:

# Also search more broadly for these property names
rg "\.importBusy|\.importMessage|\.importMessageOk" frontend/src/

Repository: HaloCollar/mcpproxy-go

Length of output: 48


🏁 Script executed:

# Let's also check the context around where sources is used - look for iterations
rg "for.*sources|sources.*for|sources\.forEach" frontend/src/components/OnboardingWizard.vue -A 3

Repository: HaloCollar/mcpproxy-go

Length of output: 48


🏁 Script executed:

# Let's check if there's strict TypeScript checking enabled by examining the base config
cat frontend/tsconfig.json | grep -A 20 "compilerOptions"

Repository: HaloCollar/mcpproxy-go

Length of output: 255


🏁 Script executed:

# Let's look at what the `@vue/tsconfig/tsconfig.dom.json` contains for strictness
fd -t f "tsconfig.dom.json" 2>/dev/null | head -5

Repository: HaloCollar/mcpproxy-go

Length of output: 48


🏁 Script executed:

# Let's verify by looking at more context around the sources initialization to see if these properties are ever assigned values later
cat -n frontend/src/components/OnboardingWizard.vue | sed -n '810,850p'

Repository: HaloCollar/mcpproxy-go

Length of output: 1617


🏁 Script executed:

# Check where importSources.value is used and if these properties are accessed
rg "importSources\.value" frontend/src/components/OnboardingWizard.vue -A 3 -B 1

Repository: HaloCollar/mcpproxy-go

Length of output: 1513


🏁 Script executed:

# Let's see if there are v-for loops or other template usage that accesses these properties
cat -n frontend/src/components/OnboardingWizard.vue | grep -i "importsources\|sources\." | head -20

Repository: HaloCollar/mcpproxy-go

Length of output: 1238


🏁 Script executed:

# Check the entire context around line 848-900 to see how the properties are being used
cat -n frontend/src/components/OnboardingWizard.vue | sed -n '845,900p'

Repository: HaloCollar/mcpproxy-go

Length of output: 2178


🏁 Script executed:

# Check the template to see if any of these properties are used in v-for or template expressions
cat -n frontend/src/components/OnboardingWizard.vue | sed -n '160,200p'

Repository: HaloCollar/mcpproxy-go

Length of output: 2648


🏁 Script executed:

# Also let's check if there's any usage in the template section by looking around the v-for that iterates sources
rg "src\.|source\." frontend/src/components/OnboardingWizard.vue -B 2 -A 2 | head -40

Repository: HaloCollar/mcpproxy-go

Length of output: 1963


🏁 Script executed:

# Let's verify one more time - search for ANY reference to importBusy, importMessage, or importMessageOk being read from the sources array
rg "src\.importBusy|src\.importMessage|src\.importMessageOk|\[.*\]\.importBusy|\[.*\]\.importMessage|\[.*\]\.importMessageOk" frontend/src/

Repository: HaloCollar/mcpproxy-go

Length of output: 48


🏁 Script executed:

# Let's also check if there's a build output or if TypeScript is reporting errors
fd -t f "package.json" frontend/ | head -1 | xargs cat | grep -A 5 '"scripts"' || echo "No scripts section"

Repository: HaloCollar/mcpproxy-go

Length of output: 299


Remove the unused excess properties from the ImportSource object literal.

The object literal at lines 830-832 adds importBusy, importMessage, and importMessageOk, which are not declared in the ImportSource interface and are never accessed anywhere in the component. TypeScript strict mode (enabled by the @vue/tsconfig/tsconfig.dom.json base config) will reject this during the build step (vue-tsc && vite build).

Fix
     const sources: ImportSource[] = res.data.paths
       .filter(p => p.exists)
       .map(p => ({
         name: p.name,
         format: p.format,
         path: p.path,
         exists: true,
         previewLoading: true,
         previewError: '',
         serverCount: 0,
         serverNames: [],
-        importBusy: '',
-        importMessage: '',
-        importMessageOk: false,
       }))
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const sources: ImportSource[] = res.data.paths
.filter(p => p.exists)
.map(p => ({
name: p.name,
format: p.format,
path: p.path,
exists: true,
previewLoading: true,
previewError: '',
serverCount: 0,
serverNames: [],
importBusy: '',
importMessage: '',
importMessageOk: false,
}))
const sources: ImportSource[] = res.data.paths
.filter(p => p.exists)
.map(p => ({
name: p.name,
format: p.format,
path: p.path,
exists: true,
previewLoading: true,
previewError: '',
serverCount: 0,
serverNames: [],
}))
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@frontend/src/components/OnboardingWizard.vue` around lines 819 - 833, The
object literal used to build the sources array (const sources: ImportSource[] =
...) includes unused properties importBusy, importMessage, and importMessageOk
that are not part of the ImportSource interface and cause TypeScript strict
build errors; remove those three properties from the mapped object so the
created objects match the ImportSource shape (keep name, format, path, exists,
previewLoading, previewError, serverCount, serverNames) in the mapping inside
OnboardingWizard.vue.

Comment on lines +921 to +947
for (const { job, r } of results) {
if (r.success && r.data) {
totalImported += r.data.summary?.imported ?? 0
totalSkipped += r.data.summary?.skipped ?? 0
totalFailed += r.data.summary?.failed ?? 0
} else {
errors.push(`${job.src.name}: ${r.error ?? 'unknown error'}`)
}
}
selectionImportOk.value = errors.length === 0
if (errors.length === 0) {
const dest = quarantine ? 'into quarantine' : 'as active'
let msg = `✓ Imported ${totalImported} server${totalImported === 1 ? '' : 's'} ${dest}`
if (totalSkipped > 0) msg += ` · ${totalSkipped} skipped (already configured)`
if (totalFailed > 0) msg += ` · ${totalFailed} failed`
if (quarantine && totalImported > 0) msg += '. Approve from the Servers page.'
selectionImportMessage.value = msg
selection.value = new Set()
// Spec 046 — bulk-import counts as completing the server step.
if (totalImported > 0 && onboarding.state?.state.server_step_status !== 'completed') {
await onboarding.markServerCompleted()
}
systemStore.addToast({
type: 'success',
title: 'Import complete',
message: `${totalImported} server${totalImported === 1 ? '' : 's'}${conflictCount.value > 0 ? ` (${conflictCount.value} renamed)` : ''}`,
})

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Treat summary-level import failures as partial failure, not full success.

Right now only transport-level errors flip the flow into the error path. If the backend returns summary.failed > 0, this still shows a success alert/toast and clears the current selection, so users lose the failed items they need to retry.

💡 One way to handle it
-    selectionImportOk.value = errors.length === 0
-    if (errors.length === 0) {
+    const hasFailures = errors.length > 0 || totalFailed > 0
+    selectionImportOk.value = !hasFailures
+    if (!hasFailures) {
       const dest = quarantine ? 'into quarantine' : 'as active'
       let msg = `✓ Imported ${totalImported} server${totalImported === 1 ? '' : 's'} ${dest}`
       if (totalSkipped > 0) msg += ` · ${totalSkipped} skipped (already configured)`
       if (totalFailed > 0) msg += ` · ${totalFailed} failed`
       if (quarantine && totalImported > 0) msg += '. Approve from the Servers page.'
       selectionImportMessage.value = msg
       selection.value = new Set()
       // ...
     } else {
-      selectionImportMessage.value = `Some imports failed: ${errors.join(' · ')}`
+      const parts = [...errors]
+      if (totalFailed > 0) parts.unshift(`${totalFailed} import(s) failed`)
+      selectionImportMessage.value = `Some imports failed: ${parts.join(' · ')}`
     }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@frontend/src/components/OnboardingWizard.vue` around lines 921 - 947, The
import flow treats any transport-level errors as failures but ignores
summary-level failures (totalFailed > 0), so the UI still marks success, clears
selection, shows a success toast and may call onboarding.markServerCompleted;
update the post-import logic around selectionImportOk, selectionImportMessage,
onboarding.markServerCompleted and systemStore.addToast to treat totalFailed > 0
as a partial/failure: if totalFailed > 0 set selectionImportOk.value = false (do
not clear selection.value), produce an informative failure/partial message
(include counts and which items failed), avoid calling
onboarding.markServerCompleted when failures exist, and surface an error/partial
toast via systemStore.addToast instead of the success toast; ensure existing
transport errors handling (errors array) remains unchanged.

Comment thread internal/server/mcp.go
Comment on lines +647 to +648
mcp.Description("Security operation: list_quarantined, inspect_quarantined, quarantine_server, inspect_tools, approve_tool, approve_all_tools, enable_tool, disable_tool"),
mcp.Enum("list_quarantined", "inspect_quarantined", "quarantine_server", "inspect_tools", "approve_tool", "approve_all_tools", "enable_tool", "disable_tool"),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Align the advertised quarantine operation with the dispatcher.

The tool schema now exposes quarantine_server, but the switch still handles "quarantine". An agent following the advertised enum will hit Unknown quarantine operation: quarantine_server at runtime.

💡 Minimal fix
-	case "quarantine":
+	case "quarantine_server":
 		result, opErr = p.handleQuarantineUpstream(ctx, request)

Also applies to: 2352-2358

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/server/mcp.go` around lines 647 - 648, The advertised operation enum
in mcp.Enum includes "quarantine_server" but the dispatcher switch still checks
for "quarantine", causing unknown-operation errors; update the dispatcher to
recognize "quarantine_server" (or accept both "quarantine" and
"quarantine_server") in the switch/case that currently matches the string
"quarantine" so it aligns with mcp.Description/mcp.Enum and the agent-facing
schema (locate the switch that branches on the quarantine operation string and
modify the case labels accordingly).

Comment thread internal/server/mcp.go
Comment on lines +2496 to +2508
func (p *MCPProxyServer) handleSetToolEnabledByName(request mcp.CallToolRequest, enabled bool) (*mcp.CallToolResult, error) {
serverName := request.GetString("name", "")
if serverName == "" {
return mcp.NewToolResultError("Missing required parameter 'name' (server name)"), nil
}

toolName := request.GetString("tool_name", "")
if toolName == "" {
return mcp.NewToolResultError("Missing required parameter 'tool_name'"), nil
}

if err := p.mainServer.runtime.SetToolEnabled(serverName, toolName, enabled, "mcp"); err != nil {
return mcp.NewToolResultError(fmt.Sprintf("Failed to update tool enabled state for '%s': %v", toolName, err)), nil

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Guard mainServer.runtime before toggling tool state.

Unlike most management paths in this file, this handler dereferences p.mainServer.runtime unconditionally. If MCPProxyServer is constructed without a runtime, this becomes a nil-pointer panic instead of a tool error.

💡 Minimal fix
 func (p *MCPProxyServer) handleSetToolEnabledByName(request mcp.CallToolRequest, enabled bool) (*mcp.CallToolResult, error) {
+	if p.mainServer == nil || p.mainServer.runtime == nil {
+		return mcp.NewToolResultError("Management service not available"), nil
+	}
+
 	serverName := request.GetString("name", "")
 	if serverName == "" {
 		return mcp.NewToolResultError("Missing required parameter 'name' (server name)"), nil
 	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func (p *MCPProxyServer) handleSetToolEnabledByName(request mcp.CallToolRequest, enabled bool) (*mcp.CallToolResult, error) {
serverName := request.GetString("name", "")
if serverName == "" {
return mcp.NewToolResultError("Missing required parameter 'name' (server name)"), nil
}
toolName := request.GetString("tool_name", "")
if toolName == "" {
return mcp.NewToolResultError("Missing required parameter 'tool_name'"), nil
}
if err := p.mainServer.runtime.SetToolEnabled(serverName, toolName, enabled, "mcp"); err != nil {
return mcp.NewToolResultError(fmt.Sprintf("Failed to update tool enabled state for '%s': %v", toolName, err)), nil
func (p *MCPProxyServer) handleSetToolEnabledByName(request mcp.CallToolRequest, enabled bool) (*mcp.CallToolResult, error) {
if p.mainServer == nil || p.mainServer.runtime == nil {
return mcp.NewToolResultError("Management service not available"), nil
}
serverName := request.GetString("name", "")
if serverName == "" {
return mcp.NewToolResultError("Missing required parameter 'name' (server name)"), nil
}
toolName := request.GetString("tool_name", "")
if toolName == "" {
return mcp.NewToolResultError("Missing required parameter 'tool_name'"), nil
}
if err := p.mainServer.runtime.SetToolEnabled(serverName, toolName, enabled, "mcp"); err != nil {
return mcp.NewToolResultError(fmt.Sprintf("Failed to update tool enabled state for '%s': %v", toolName, err)), nil
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/server/mcp.go` around lines 2496 - 2508, In
handleSetToolEnabledByName guard p.mainServer.runtime for nil before calling
SetToolEnabled: check if p.mainServer == nil || p.mainServer.runtime == nil and
return an mcp.NewToolResultError (e.g. "Runtime not initialized" or similar) so
the handler returns a proper tool error instead of panicking; then proceed to
call p.mainServer.runtime.SetToolEnabled(serverName, toolName, enabled, "mcp")
only after the nil check.

Comment thread internal/server/mcp.go
Comment on lines +2592 to +2599
if toolCount == 0 {
if tools, err := client.ListTools(context.Background()); err == nil {
for _, tool := range tools {
if p.isToolCallable(server.Name, tool.Name) {
toolCount++
}
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Bound the fallback ListTools call with the request context.

This new fallback does live upstream I/O from upstream_servers list, but it uses context.Background() with no deadline. If a server stalls in ListTools, the whole management call can hang.

💡 Minimal fix
-			if toolCount == 0 {
-				if tools, err := client.ListTools(context.Background()); err == nil {
+			if toolCount == 0 {
+				toolsCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
+				defer cancel()
+				if tools, err := client.ListTools(toolsCtx); err == nil {
 					for _, tool := range tools {
 						if p.isToolCallable(server.Name, tool.Name) {
 							toolCount++
 						}
 					}
 				}
 			}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if toolCount == 0 {
if tools, err := client.ListTools(context.Background()); err == nil {
for _, tool := range tools {
if p.isToolCallable(server.Name, tool.Name) {
toolCount++
}
}
}
if toolCount == 0 {
toolsCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
if tools, err := client.ListTools(toolsCtx); err == nil {
for _, tool := range tools {
if p.isToolCallable(server.Name, tool.Name) {
toolCount++
}
}
}
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/server/mcp.go` around lines 2592 - 2599, The fallback call to
client.ListTools uses context.Background(), causing unbounded upstream I/O;
change it to use the request-scoped context (the ctx used by the surrounding
management handler) so the ListTools call is bounded by the incoming request
deadline/cancellation. Locate the block referencing toolCount,
client.ListTools(...) and p.isToolCallable(server.Name, ...) and replace the
background context with the existing request context (e.g., ctx) so the call is
cancellable and respects timeouts.

Comment thread internal/server/mcp.go
Comment on lines +4553 to +4583
func (p *MCPProxyServer) isToolCallable(serverName, toolName string) bool {
if strings.Contains(toolName, ":") {
parts := strings.SplitN(toolName, ":", 2)
if len(parts) == 2 {
if serverName == "" {
serverName = parts[0]
}
toolName = parts[1]
}
}

if serverName == "" || toolName == "" {
return false
}

serverConfig, err := p.storage.GetUpstreamServer(serverName)
if err != nil || serverConfig == nil {
return false
}

if !serverConfig.Enabled {
return false
}

approval, err := p.storage.GetToolApproval(serverName, toolName)
if err == nil && approval != nil && approval.Disabled {
return false
}

return true
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

isToolCallable still returns tools that the call path rejects.

This helper only filters out disabled servers and approval.Disabled, but the actual execution path still blocks quarantined servers (Line 1489) and pending/changed tool approvals (Lines 1503-1544). That means retrieve_tools and getVisibleToolCount() can still advertise tools that are not actually callable.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/server/mcp.go` around lines 4553 - 4583, The isToolCallable helper
currently only checks server enablement and approval.Disabled, so update
isToolCallable to mirror the execution path's full guard logic: ensure you check
serverConfig.Quarantined (match the quarantined check used during execution),
and verify the tool approval state from storage.GetToolApproval for non-callable
states (e.g., pending or changed statuses) rather than only inspection of
approval.Disabled; use the same status values/enum names and logic that the
execution path uses (the code around retrieve_tools and getVisibleToolCount and
the execution checks at lines referenced in the review) so retrieve_tools and
getVisibleToolCount will only advertise truly callable tools. Ensure you
reference and use the same functions/fields: p.storage.GetUpstreamServer,
p.storage.GetToolApproval, serverConfig.Enabled, serverConfig.Quarantined, and
the approval.Status/Disabled semantics used by the execution path.

Comment thread internal/server/server.go
Comment on lines +1803 to +1806
gruntime.SetBlockProfileRate(100_000_000) // 1 sample / 100 ms blocked
gruntime.SetMutexProfileFraction(100) // sample 1% of contention
pprofMux.ServeHTTP(w, r)
})

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

# Check the code around lines 1803-1806 in internal/server/server.go
head -1810 internal/server/server.go | tail -50 | cat -n

Repository: HaloCollar/mcpproxy-go

Length of output: 2535


🏁 Script executed:

# Get the full context of the pprof handler to understand the scope
sed -n '1770,1820p' internal/server/server.go | cat -n

Repository: HaloCollar/mcpproxy-go

Length of output: 2748


🌐 Web query:

Go runtime SetBlockProfileRate SetMutexProfileFraction process scope global behavior

💡 Result:

In the Go runtime, both runtime.SetBlockProfileRate and runtime.SetMutexProfileFraction control process-wide (global) profiling behavior for all goroutines in the program. They are not scoped to individual goroutines or limited to specific parts of the code; once called, they affect the entire runtime profiler across the process [1][2][3][4]. runtime.SetBlockProfileRate(rate int), added in Go 1.1, sets the sampling rate for goroutine blocking events (e.g., on sync primitives, channels). The profiler samples approximately one blocking event every 'rate' nanoseconds of blocked time. rate=1 includes every event (highest overhead), rate<=0 disables it. Default is 0 (disabled), so block profiles via net/http/pprof are empty until explicitly enabled [1][5][3][6][4]. runtime.SetMutexProfileFraction(rate int), added in Go 1.8, sets the fraction of mutex contention events reported (1/rate on average). It returns the previous rate. rate=0 disables, rate<0 reads current without change. Default is 0, making mutex profiles a no-op until set >0 [7][2][3][8]. These functions must be called explicitly in application code (typically in main or init) to enable profiling, as they are off by default to avoid overhead. They take effect immediately and globally for the process lifetime (until changed). Calling from one goroutine affects all [9][10][6][11]. Example usage: runtime.SetBlockProfileRate(1) // Sample all block events old := runtime.SetMutexProfileFraction(10) // Sample ~1/10 mutex events Then access via http://localhost:6060/debug/pprof/block or /mutex [3][6][8].

Citations:


Reset profiling rates after each pprof request to prevent persistent overhead.

Lines 1803-1804 enable process-global profiling with SetBlockProfileRate and SetMutexProfileFraction, but these settings persist indefinitely after the first request hits the handler. Although the code comment states the daemon should stay "zero-overhead until someone actively profiles," once the /debug/pprof/ endpoint is accessed, profiling overhead remains active for the entire process lifetime, contradicting this intent.

Both runtime functions take effect globally and remain enabled until explicitly reset to 0. The handler must restore these settings after serving each request using defer statements to prevent accumulating performance costs.

Suggested fix
		gruntime.SetBlockProfileRate(100_000_000) // 1 sample / 100 ms blocked
		gruntime.SetMutexProfileFraction(100)     // sample 1% of contention
+		defer gruntime.SetBlockProfileRate(0)
+		defer gruntime.SetMutexProfileFraction(0)
		pprofMux.ServeHTTP(w, r)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/server/server.go` around lines 1803 - 1806, The profiling rates set
with gruntime.SetBlockProfileRate and gruntime.SetMutexProfileFraction before
calling pprofMux.ServeHTTP remain enabled process-wide; update the pprof handler
so you immediately defer resetting both rates to 0 (call
gruntime.SetBlockProfileRate(0) and gruntime.SetMutexProfileFraction(0)) right
after setting them and before invoking pprofMux.ServeHTTP(w, r) so the resets
always run (even on panic) and profiling overhead does not persist after the
request.

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.

4 participants