Skip to content

feat(observability): config-gated Prometheus + OTLP exporters (MCP-32) - #746

Merged
Dumbris merged 4 commits into
mainfrom
feat/mcp-32-observability-exporters
Jun 22, 2026
Merged

Dumbris merged 4 commits into
mainfrom
feat/mcp-32-observability-exporters

Conversation

@Dumbris

@Dumbris Dumbris commented Jun 22, 2026

Copy link
Copy Markdown
Member

Summary

Ships the observability exporters for the daemon (roadmap #8 / MCP-32). The
internal/observability scaffolding already existed on main but was dead
code
: the manager was created with a hardcoded default and the HTTP API was
constructed with nil observability, so /metrics was never served, tool-call
metrics were never recorded, and the OTLP tracing helpers were never called.

This PR makes it real and operator-configurable, OFF by default.

What's included (exit criteria)

  • /metrics Prometheus endpoint — served on the existing HTTP listener,
    gated by observability.metrics.enabled (default false).
  • OTLP exporter (HTTP and gRPC) with trace spans wrapping tool calls and
    their upstream hop, gated by observability.tracing.enabled (default false).
  • Reference Grafana dashboard committed at contrib/grafana/mcpproxy-dashboard.json.
  • Docs page docs/features/observability.md (scrape config, metric
    reference, OTLP collector setup, dashboard import).
  • Both editions — server edition annotates tool-call spans with user_id
    and profile via a //go:build server seam (span attributes, not Prometheus
    labels, to keep metric cardinality bounded).

Metrics now wired

mcpproxy_tool_calls_total / _duration_seconds (inline at the call site),
mcpproxy_quarantine_events_total{scope,action} (new), upstream-health gauges
(servers_total/connected/quarantined, tools_total, docker_containers_active)
via an event-bus bridge, plus the pre-existing HTTP and OAuth-refresh metrics
that are now actually scrapeable.

Config

{
  "observability": {
    "metrics": { "enabled": true },
    "tracing": { "enabled": true, "protocol": "http", "endpoint": "localhost:4318", "sample_rate": 0.1 }
  }
}

Testing

  • TDD throughout; new unit tests for config validation/repair, OTLP exporter
    transport selection, the quarantine counter, the metrics event bridge, the
    config-gating mapping, and the inline tool-call recorder.
  • go test ./internal/config/ ./internal/observability/ ./internal/server/ green
    (incl. -race); E2E binary-startup tests (TestBinaryStartupAndShutdown,
    TestBinaryAPIEndpoints, TestBinaryHealthAndRecovery) pass with the new
    wiring.
  • golangci-lint v2 clean on both editions; both editions build.
  • OpenAPI spec regenerated for the new config fields.

Notes / follow-ups

  • True W3C traceparent propagation to upstream servers over the wire would
    require instrumenting the upstream transports; this PR creates the local
    spans (tool call + upstream hop). Can be a follow-up.
  • The docs page has a TODO(MCP-32) for a rendered dashboard screenshot, which
    needs a live Grafana instance.

Related MCP-32

Wire the existing observability scaffolding into the running daemon and make
it operator-configurable. Both exporters are OFF by default.

- config: add observability.metrics / observability.tracing blocks
  (enabled, protocol http|grpc, endpoint, sample_rate) with validation/repair.
- server: build the observability config from file config, pass the manager to
  the HTTP API (so /metrics is actually served) and to the MCP proxy; close the
  tracer provider on shutdown. Previously the manager was created but the API
  received nil, so /metrics and tool-call metrics were dead code.
- tracing: support both OTLP/HTTP and OTLP/gRPC transports; attach optional
  resource attributes.
- tool calls: record latency/outcome metrics and open an OTLP span wrapping the
  upstream hop, inline at the call site (no-op when disabled).
- metrics: add mcpproxy_quarantine_events_total{scope,action}.
- bridge: project runtime events (server stats, quarantine changes) onto
  Prometheus gauges/counters, decoupled from business logic.
- server edition: annotate tool-call spans with user_id + profile via a
  build-tagged seam (span attributes, not metric labels, to bound cardinality).
- docs: "Observability for mcpproxy" page (scrape config, metric reference,
  OTLP setup) + reference Grafana dashboard in contrib/grafana/.
- regenerate OpenAPI spec for the new config fields.

Related MCP-32
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jun 22, 2026 •

Copy link
Copy Markdown

@codecov-commenter

codecov-commenter commented Jun 22, 2026 •

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

❌ Patch coverage is 70.12195% with 49 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
internal/server/observability_bridge.go 51.51% 15 Missing and 1 partial ⚠️
internal/server/mcp.go 56.00% 10 Missing and 1 partial ⚠️
internal/server/server.go 84.78% 5 Missing and 2 partials ⚠️
internal/observability/tracing.go 70.00% 6 Missing ⚠️
internal/httpapi/server.go 0.00% 3 Missing and 1 partial ⚠️
internal/config/config.go 87.50% 1 Missing and 2 partials ⚠️
internal/server/observability_edition.go 0.00% 2 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

📦 Build Artifacts

Workflow Run: View Run
Branch: feat/mcp-32-observability-exporters

Available Artifacts

  • archive-darwin-amd64 (28 MB)
  • archive-darwin-arm64 (25 MB)
  • archive-linux-amd64 (16 MB)
  • archive-linux-arm64 (14 MB)
  • archive-windows-amd64 (28 MB)
  • archive-windows-arm64 (25 MB)
  • frontend-dist-pr (0 MB)
  • installer-dmg-darwin-amd64 (21 MB)
  • installer-dmg-darwin-arm64 (19 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 27955262300 --repo smart-mcp-proxy/mcpproxy-go

Note: Artifacts expire in 14 days.

@Dumbris

Dumbris commented Jun 22, 2026

Copy link
Copy Markdown
Member Author

CodexReviewer: changes requested. Substantive: observability health manager is built for every server and replaces the readiness handler even when observability is disabled (server.go:138 + httpapi/server.go:563) → /readyz becomes a vacuous 200 (empty checker list, health.go:160). Config-gated feature must be a no-op when off — only take over /readyz when observability is enabled; add a regression test for OFF. (Codex's CI-not-green note is stale; CI is now fully green.)

…ed (MCP-32)

CodexReviewer finding: passing a non-nil observability manager made the HTTP
API skip its controller-backed health block entirely, so /readyz (and the
/livez,/health aliases) either 404'd or fell back to the observability health
manager's vacuous always-ready handler — a config-gated feature must be a no-op
for readiness when disabled.

- httpapi: register /metrics independently of the health endpoints; only let
  the observability health manager own /healthz+/readyz when it is actually
  enabled, otherwise keep the controller-backed handlers authoritative.
- server: disable the observability health manager in buildObservabilityConfig
  (out of scope for MCP-32; its readiness is vacuous) so controller readiness
  stays authoritative even when metrics are enabled.
- tests: regression test that with metrics ON / health OFF, /readyz reflects
  controller readiness (503 when not ready) and the liveness aliases + /metrics
  are all served; assert buildObservabilityConfig keeps health off.

Related MCP-32

Co-Authored-By: Paperclip <[email protected]>
@Dumbris

Dumbris commented Jun 22, 2026

Copy link
Copy Markdown
Member Author

QATester BLOCK — PR #746 (MCP-32 Observability)

SHA: 09db2610480185b73b36916e165b3f2c316a5cac
qa-gate status: posted as failure

Finding: GET /metrics returns 404 when enabled

Root cause — /metrics is registered on the chi router in httpapi/server.go:570 but the main http.ServeMux in server/server.go only routes /api/, /events, and explicit health endpoints to httpAPIServer. /metrics is missing from that list.

Evidence:

[INFO] Prometheus metrics enabled {"endpoint": "/metrics"}   ← logged
GET /metrics → 404 page not found                              ← BUG  
GET /healthz → 200 {"status":"healthy"}                     ← works (explicitly mounted)

Fix — in internal/server/server.go after the health endpoint mounts (~line 1943):

if s.observability != nil && s.observability.Metrics() != nil {
    mux.Handle("/metrics", httpAPIServer)
}

Also: TestObservabilityManager_ServesMetricsWhenEnabled calls the handler directly (bypasses routing) — add an integration test that hits /metrics through the full server.

All unit tests pass (24/24). The routing surface is the only failure.

@Dumbris

Dumbris commented Jun 22, 2026

Copy link
Copy Markdown
Member Author

CEO/Claude fallback code review (MCP-3137 — GeminiCritic adapter failed, CEO acting as model-diverse fallback per MCP-3066)

VERDICT: REQUEST_CHANGES

Summary: Config-gating logic is correct (exporters off by default), nil-guarding is solid throughout. One blocking resource leak found.

Bug (blocking)

internal/server/observability_bridge.go:28 — runMetricsBridge calls s.runtime.SubscribeEvents() but never calls s.runtime.UnsubscribeEvents(events) on exit — neither the ctx.Done() path nor the channel-close path cleans up. Every other caller in the codebase uses defer rt.UnsubscribeEvents(ch). This leaks an event-bus subscriber slot on every server restart/config-reload when metrics are enabled.

Concerns (non-blocking)

  • internal/server/server.go:574 — s.observability.Close(ctx) runs before HTTP server shutdown. OTLP spans from in-flight requests still being gracefully drained may be dropped. Consider moving observability teardown to after HTTP server shutdown completes.
  • go.mod — github.com/kylelemons/godebug v1.1.0 added as indirect dep (via otlptracegrpc). Last release 2021, stable diff/test util, low risk.

Dumbris added 2 commits June 22, 2026 15:49
…P-3135)

The /metrics handler is registered on the httpapi chi router but the outer
http.ServeMux only forwarded /api/, /events, and the health endpoints, so
GET /metrics returned 404 even with observability.metrics.enabled=true.

Extract the route forwarding into Server.registerHTTPHandlers and add a
gated mux.Handle("/metrics", httpAPIServer) so the endpoint is reachable
only when the Prometheus exporter is enabled. Covered by a unit test on the
real outer mux and a full-binary e2e that scrapes /metrics for 200 +
mcpproxy_uptime_seconds.

Related #746
…idge

runMetricsBridge calls SubscribeEvents() but never UnsubscribeEvents(),
leaking a channel in the runtime's eventSubs map on every call. This
blocks PR #746 from merging (the leak causes a permanent subscriber
that silently drops events after the bridge goroutine exits).

Add defer s.runtime.UnsubscribeEvents(events) right after subscribing,
matching the existing pattern in listenForRoutingModeRefresh.

Related #746

@mcpproxy-gatekeeper mcpproxy-gatekeeper 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.

✅ Gatekeeper approval — MCP-32 observability exporters. Per the approved gate (Codex-first + verification): CodexReviewer's first-review caught a /readyz regression (config-gated feature changing readiness when OFF); BackendEngineer fixed it (51d7264 — keep controller-backed /readyz when health disabled) + a /metrics routing fix, with a regression test. CI fully green (33 checks: unit/E2E/integration/server-edition/CodeQL). Operator-verified the fix in code. Kimi re-review verdict was a CI-timing artifact on the now-green head, not substantive. Author (BackendEngineer) ≠ approver.

@Dumbris
Dumbris merged commit e3ae24a into main Jun 22, 2026
39 checks passed
github-actions Bot pushed a commit that referenced this pull request Jun 24, 2026
…ues (MCP-3207) (#752)

The v0.45.0 QA pass (OBS-05) code-verified the server-edition tool-call
telemetry label injection (editionToolCallAttributes, MCP-32) but never drove
>=2 authenticated users to confirm the emitted user_id/profile VALUES are
distinct and correct. Add deterministic tests that close that gap.

Design correction surfaced while writing these tests: user_id and profile are
OTLP SPAN attributes, not Prometheus metric labels. The tool-call counter
mcpproxy_tool_calls_total carries only {server,tool,status} to bound metric
cardinality (observability_edition_server.go:13-17). So "exercise the label
values" is faithfully and deterministically tested at the span layer; a full
2-user server boot scraping /metrics could never surface these labels and would
only add flakiness.

- internal/server/observability_edition_server_test.go (//go:build server):
  two distinct users (regular + admin_user) yield distinct, correct user_id
  values and the same correct profile; API-key admin and missing/empty auth
  emit no user_id; spans emitted via an in-memory recorder carry the matching
  caller's user_id + active profile.
- internal/server/observability_edition_test.go (//go:build !server):
  personal-edition negative control — no user_id/profile labels even with a
  populated user auth context.
- internal/observability/metrics_test.go: metric-layer negative control — the
  tool-call counter never carries per-user/per-profile labels in either edition.

Provenance: QA report ~/mcpproxy-qa/mcpproxy-qa-v0.45.0.html (OBS-05, partial).

Related #746
nlaurance pushed a commit to nlaurance/mcpproxy-go that referenced this pull request Aug 12, 2026
…S2) (smart-mcp-proxy#555)

* docs(070): Registry — make discovery actual & easy to add to upstream spec

Close the search-to-add loop + reach surface parity across Web UI, MCP, CLI
(all share the unified AddUpstreamServer path, quarantine-by-default). Real
gaps from research: CLI has no registry/search/add commands; Web UI Repositories
searches but can't one-click-add; registry list hardcoded/rebuild-only; key-less
registries error. Adds unified add-from-registry-result, CLI parity, Web UI
loop, MCP convenience, config-driven registry list + cache refresh, and a
cross-surface consistency regression. Roadmap PILLAR A. Paperclip goal da399902.

* docs(070): plan, research, data-model, contracts, tasks for registry easy upstream-add

Phase 0/1/2 speckit design artifacts for spec 070. Research found the
search->add loop is already partially closed (Web UI Add button, CLI
search/list) but via three divergent normalizations; keystone is one
backend AddServerFromRegistry core op all surfaces call, guarded by a
cross-surface consistency regression (CN-004/FR-010).

No implementation yet — submitted for the per-spec design gate (Gate 2).

Related smart-mcp-proxy#746

* docs(070): add registry research-refinement notes for planning

* feat(registries): AddServerFromRegistry keystone core op (spec 070)

Single backend op that turns a registry reference (registryId + serverId +
overrides) into a validated, quarantined upstream server. Every surface
(REST/MCP/CLI) will funnel through this one normalization (CN-001); identical
input yields an identical persisted config (CN-004). The client sends a
reference, never a config blob — the server re-derives it (security D1), so a
buggy/compromised client cannot smuggle command/args or disable quarantine.

- registries.ServerEntry gains RequiredInputs ([]RequiredInput)
- registries.FindServerByID + sentinel errors (registry/server not found)
- registries.DetectRequiredInputs: explicit + ${VAR}/$VAR heuristic scan
- server.AddServerFromRegistry orchestrator + pure buildServerConfigFromEntry
- quarantine-by-default (CN-002, never client-overridable); refusals on
  no_install_info / missing_required_input / duplicate_name
- RegistryAddErrorCode maps errors to stable cross-surface codes

Phase 1+2 of MCP-746. Tests: go test ./internal/server/ -run TestAddFromRegistry
-race (green); registries input/lookup unit tests; build + linter clean.

Co-Authored-By: Paperclip <[email protected]>

* feat(070): Web UI one-flow registry search→add (T015-T017)

Repoint the registry "Add to MCP" button at the backend keystone instead
of parsing install_cmd client-side (CN-001 / issue smart-mcp-proxy#483 class of bug):

- T015: new api.addServerFromRegistry(registryId, serverId, {name,env,enabled})
  POSTs to /api/v1/registries/{id}/servers/{serverId}/add and surfaces the
  structured cross-surface error (code + missing_inputs). Removes the old
  addServerFromRepository install_cmd.split path.
- T016: required-input prompt dialog in Repositories.vue — opens on a
  missing_required_input response, renders one field per missing input
  (rich decl from search required_inputs[] when present, else bare names),
  blocks Add until all are filled, resubmits as env. data-test hooks added
  across the search → add flow.
- T017: e2e/playwright/registry-add.spec.ts (search→Add→quarantined +
  prompt path); pending the live REST route to run green.
- types: RequiredInput + RepositoryServer.required_inputs[].

Verified: 5 vitest unit tests green, vue-tsc clean, vite build green.

Co-Authored-By: Paperclip <[email protected]>

* feat(070): CLI registry list/search/add + REST add-from-registry (US2)

Phase 3 of spec 070 — close the discover→add loop on the CLI, the genuine
net-new gap. After this a user can:
  mcpproxy registry list → registry search <q> -r <reg> → registry add <reg> <id>
and the server appears quarantined in `mcpproxy upstream list`.

- cmd/mcpproxy/registry_cmd.go: `registry list|search|add` Cobra group.
  list/search are daemon-first with an in-process fallback; add requires the
  daemon because the keystone op (config derivation + quarantine) is
  server-side (CN-001 / decision D1). Legacy `search-servers` retained.
- internal/cliclient: ListRegistries, SearchRegistry, AddFromRegistry +
  client-side RegistryAddError carrying the stable code + missing inputs.
- internal/httpapi: POST /api/v1/registries/{id}/servers/{serverId}/add wired
  to the keystone via a new AddServerFromRegistryRef controller method;
  code→HTTP status mapping (404 not-found, 400 derivation/dup/missing-input).
- internal/server: AddServerFromRegistryRef adapter projecting failures onto
  the cross-surface contracts.RegistryAddError (names missing --env keys).
- internal/contracts: AddFromRegistryRequest/Data/AddedServerSummary +
  RegistryAddError.

Tests: cliclient httptest units; server adapter units; CLI e2e against a
running daemon + mock registry (list→search→add→quarantined) and the
missing-required-input actionable-error path.

Note: the REST add route was pulled forward from T014 because the CLI is a
thin REST client and the e2e ("add via running daemon") cannot pass without a
server endpoint; the frontend wiring (T015/T016) remains for US1.

Related smart-mcp-proxy#746

Co-Authored-By: Paperclip <[email protected]>

* test(070): fix registry-add Playwright spec route + decouple prompt-test registry

T017 follow-up after running the e2e green against a live server:
- nav to /ui/repositories (history-mode base /ui/), not a hash route
- default the no-input happy path to docker-mcp-catalog (reliably addable)
- target the required-input server (default fleur/stripe) independently of
  the no-input registry, so both tests run from one invocation

Verified: both tests pass — search→Add→quarantined and
search→Add→prompt→quarantined — against a fresh throwaway core.

Co-Authored-By: Paperclip <[email protected]>

* feat(070): MCP upstream_servers add_from_registry operation (US3)

Adds operation=add_from_registry to the upstream_servers MCP tool so agents
can add an upstream from a registry reference (registry + id) without
hand-constructing command/args/url. Dispatches to the keystone
AddServerFromRegistryRef op: the server re-derives the runnable config from
the registry entry and persists it quarantined (CN-001 / CN-002 / security
decision D1).

New params: registry, id (env_json/name/enabled reuse the existing fields).
Success returns the slim AddedServerSummary; failure returns a structured
error (isError=true) carrying the same stable Code as REST/CLI plus
missing_inputs for missing_required_input (FR-003), so the same failure reads
identically across every surface.

T012/T013 of spec 070 Phase 4. Tests: internal/server/mcp_add_from_registry_test.go
(happy path + missing_required_input structured error).

* fix(070): complete add_from_registry MCP op + working tests

The prior commit added only the upstream_servers enum/param surface; the
dispatch case and handler were missing and the test referenced undefined
helpers, so the package did not compile. This wires it up end-to-end:

- handleAddServerFromRegistry dispatches to the keystone
  mainServer.AddServerFromRegistryRef; success -> AddedServerSummary,
  failure -> structured error (code + missing_inputs, isError=true)
  matching the REST/CLI surfaces (CN-001).
- add_from_registry added to the dispatch switch and the agent-token
  block list (write-op parity).
- Tests use a real runtime-backed mainServer plus an httptest registry
  (SetRegistriesFromConfig): happy path asserts a quarantined stdio
  config, missing-input path asserts the structured missing_required_input
  error with the offending input names.

Verified: go test ./internal/server (incl. the two new tests), go build
./..., golangci-lint run ./internal/server/... all pass.

* fix(070): correct add_from_registry test harness (NewServer(cfg,logger))

* feat(070): merge built-in registry defaults with config by ID (US4 FR-006)

SetRegistriesFromConfig previously replaced the registry list wholesale, so
a user who added one custom registry in their config dropped all built-in
defaults. Change it to merge defaults union config keyed by ID: defaults
first, custom appended, colliding IDs override in place. Extract the five
built-in registries into config.DefaultRegistries() as the single source of
truth shared by DefaultConfig() and the merge. Add RequiresKey to both
RegistryEntry types (plumbing for FR-008).

Related smart-mcp-proxy#765

* feat(070): skip key-requiring registry when key absent (US4 FR-008)

A registry marked RequiresKey is skipped via ErrRegistryKeyMissing when no
API key is configured (env MCPPROXY_REGISTRY_<ID>_API_KEY), instead of
running a doomed fetch. SearchServers short-circuits before the network call;
FindServerByID inherits the behaviour. Calling surfaces map the sentinel to
an 'unavailable' marker so the overall search still succeeds.

Related smart-mcp-proxy#765

* feat(070): add Invalidate/Refresh/InvalidatePrefix/Peek to cache manager (US4 FR-007)

Primitives for registry cache freshness: Invalidate drops a key, Refresh
aliases it (lazy re-fetch), InvalidatePrefix drops all keys under a stable
prefix (one refresh clears every tag/query variant of a registry), and Peek
returns a record without evicting it even when expired so callers can serve
stale data while flagging its age. All stats-accounted.

Related smart-mcp-proxy#765

* feat(070): registry cache freshness + refresh endpoint, surface key-absent (US4 FR-007/FR-008)

Wire the cache primitives into the registry search path: SearchRegistryServers
now caches each (registry,tag,query,limit) result and serves it while flagging
age/staleness via contracts.RegistryCacheInfo. Add RefreshRegistryCache +
POST /api/v1/registries/{id}/refresh to drop a registry's cached lists on
demand. A key-requiring registry with no key configured surfaces as an
'unavailable' marker (HTTP 200) on both the REST search endpoint and the MCP
search_servers tool instead of failing the surface (FR-008). Regenerate the
OpenAPI spec for the new endpoint and response fields.

Related smart-mcp-proxy#765

* docs(070): mark US4 tasks T018-T020 complete

Related smart-mcp-proxy#765

* fix(070): copy-on-write config in AddServer to avoid data race

AddServer mutated the live immutable config snapshot returned by
runtime.Config() in place (currentConfig.Servers = append(...)) before
publishing via UpdateConfig. Background goroutines that range cfg.Servers
concurrently — LoadConfiguredServers during startup and the 2s-delayed
DiscoverAndIndexTools — raced that write, which the -race detector flagged
on TestHandleUpstreamServers_AddFromRegistry_HappyPath in CI.

Clone the config and its server slice, append to the clone, then publish
the new snapshot atomically. Behaviour is unchanged; readers holding the
prior snapshot are now isolated, as the immutable-snapshot contract intends.

Related smart-mcp-proxy#555

* fix(upstream): route concurrent Config reads through GetConfig (MCP-770)

DiscoverTools snapshotted client.Config directly while only holding the
Manager's m.mu, but the reconcile add path (AddServerConfig) releases m.mu
before calling managed.Client.SetConfig, which guards mc.Config with the
client's own mc.mu. The two accesses therefore used different mutexes,
producing a data race the -race detector flagged intermittently in CI
(PR smart-mcp-proxy#555, run 26719908592).

Fix the read side: read config via the mutex-guarded GetConfig() accessor in
DiscoverTools and in the API-facing status readers (GetStats,
GetTotalToolCount, ListServers) that share the identical hazard — they read
client.Config after releasing m.mu and run concurrently with reconcile.
mc.mu is a leaf lock (only Get/SetConfig take it, never while holding m.mu),
so this is deadlock-safe.

Add TestDiscoverTools_ConfigRace: drives AddServerConfig (SetConfig) against
the readers concurrently; trips -race before the fix, green after.

Related: MCP-770

* fix(upstream): make managed.Client config access atomic (MCP-770)

The first MCP-770 fix routed Manager-side reads (DiscoverTools, GetStats,
GetTotalToolCount, ListServers) through GetConfig(), but the underlying
hazard is broader: managed.Client.Config is a pointer field that SetConfig
swaps off m.mu (reconcile add path), while it is read concurrently from many
sites that do NOT hold the client's mc.mu — including Client.Connect's
unlocked phase (client.go:197) and detached state-change callback goroutines
(onStateChange, spawned by StateManager.SetError). The CI -race detector
flagged the Connect-vs-SetConfig variant on PR smart-mcp-proxy#555's macOS unit job after
the first fix was cherry-picked.

A mutex-guarded accessor can't cover this: most internal readers run while
mc.mu is already held, so routing them through an RLock GetConfig() would
deadlock (sync.RWMutex is not reentrant). Instead make the field itself
lock-free and data-race-free:

- Replace the exported `Config *config.ServerConfig` field with an
  unexported `cfg atomic.Pointer[config.ServerConfig]`.
- GetConfig() returns cfg.Load(); SetConfig() does cfg.Store(). Both are
  lock-free and safe whether or not mc.mu is held.
- Route every reader through GetConfig() across the managed client, the
  upstream Manager, and the supervisor actor pool.

Add TestConnect_ConfigRace: drives AddServerConfig (SetConfig) against
Client.Connect concurrently; trips -race on the old field, green after.

Verified: go test -race ./internal/upstream/... ./internal/runtime/... and
the original CI victims TestHandleUpstreamServers_AddFromRegistry_HappyPath /
_AdminAllowed_WriteOps pass x5 under -race; build + linter clean.

Related: MCP-770

* test(070): close mainServer storage so Windows temp-dir cleanup succeeds

newAddFromRegistryTestServer opened a real Server (and its BBolt config.db
under t.TempDir()) but never closed it. On Windows an open file cannot be
unlinked, so t.TempDir's RemoveAll failed the AddFromRegistry tests with
"config.db ... being used by another process". Unix unlinks open files, so
ubuntu/macOS passed and hid it; the failure only surfaced once the MCP-770
race fix stopped aborting the test binary before cleanup ran.

Register t.Cleanup(mainSrv.Shutdown) after t.TempDir() so LIFO cleanup closes
the runtime/storage (releasing the handle) before the temp dir is removed.
Shutdown is nil-httpServer-safe and idempotent.

Related: MCP-770, spec 070

* fix(core): serialize stderr/process monitoring lifecycle (MCP-770)

StartStderrMonitoring (from connectStdio during a reconcile-driven Connect) and
StopStderrMonitoring (from Disconnect during Manager.ShutdownAll) accessed the
monitoring lifecycle fields — stderrMonitoringCtx/Cancel/WaitGroup and the
process-monitoring equivalents — with no synchronization. When a connect and a
shutdown overlap on the same client, the -race detector flags WG.Add (Start)
vs WG.Wait (Stop). CI caught this on PR smart-mcp-proxy#555's ubuntu unit job once the earlier
MCP-770 fixes (atomic Config) + the Windows temp-dir cleanup made the test's
shutdown path actually run concurrently with reconcile.

Add a dedicated monitoringMu that makes the four Start*/Stop*Monitoring methods
mutually exclusive, so Add never overlaps Wait. The mutex is a leaf (monitor
goroutines never acquire it; it is never held across c.mu), so Stop's bounded
WG.Wait under the lock cannot deadlock.

Add TestStderrMonitoring_StartStopRace: hammers Start/Stop concurrently; trips
-race on the unsynchronized fields, green with monitoringMu.

Related: MCP-770, spec 070

* fix(core): per-cycle done channel for monitoring stop (MCP-770)

The monitoringMu serialization (prev commit) was incomplete: StopStderr/
StopProcessMonitoring ran WG.Wait() in a DETACHED goroutine guarded by a 500ms
timeout. When a real child keeps its stderr open, monitorStderr blocks in
scanner.Scan(), the wait times out, Stop returns and releases monitoringMu —
but the detached WG.Wait goroutine lives on and races the next connect's
WG.Add. CI caught this on smart-mcp-proxy#555 (DiscoverTools→Connect StartStderrMonitoring
WG.Add vs the lingering StopStderrMonitoring WG.Wait).

Replace the reused sync.WaitGroup with a per-cycle `done chan struct{}` the
monitor goroutine closes, and pass the context + done as locals so an
abandoned (timed-out) monitor never reads the shared ctx/state a later Start
overwrites. Stop now waits on done directly under monitoringMu (no detached
waiter) and nils the per-cycle fields. monitorStderr/monitorProcess take ctx
as a parameter.

Strengthen TestStderrMonitoring with an AbandonedMonitorNoRace case: a blocking
pipe keeps the monitor alive so Stop hits the timeout/abandon path — the exact
escape the WaitGroup version raced on. AddFromRegistry passes 12x under -race.

Related: MCP-770, spec 070

* docs(070): document registry add/refresh surfaces (MCP-788, ENG-9)

Kimi's dual-AI review of smart-mcp-proxy#555 returned REQUEST_CHANGES on the missing docs per
ENG-9. Add docs for the new registry surfaces:

- docs/features/registry-add.md — cohesive feature guide covering all three
  surfaces (CLI `registry list/search/add`, REST add/refresh/browse endpoints,
  MCP `upstream_servers` add_from_registry op), the CN-001 re-derivation
  security model, quarantine-by-default, and the cross-surface
  missing_required_input error contract.
- docs/api/rest-api.md — new Registries section listing the four endpoints
  (list, search, add, refresh) with request/response shapes, linking the
  feature guide.

Docs only; no code change. Clears Kimi's REQUEST_CHANGES for the Gate-3 merge.

Related: MCP-788, MCP-785, MCP-761, spec 070

* fix(registry): gate add_from_registry behind allow_server_add; merge defaults in ListRegistries

Address the two Codex Gate-3 review findings on PR smart-mcp-proxy#555 (spec 070).

Finding 1 (security): the add_from_registry MCP op persisted a new upstream
without the AllowServerAdd check that the ordinary `add` op enforces, so a user
who set allow_server_add=false could still add a server by registry reference.
Gate add_from_registry behind the same check.

Finding 2 (FR-006 consistency): Runtime.ListRegistries returned a hard-coded
legacy Smithery entry for an empty config, or only cfg.Registries when set —
diverging from the merged defaults+custom source that search/add use. Route it
through registries.SetRegistriesFromConfig so the daemon/API list always shows
built-in defaults merged with custom entries.

Tests-first for both (ENG-1).

Related smart-mcp-proxy#555

---------

Co-authored-by: Paperclip <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants