Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions internal/config/connection_equivalent.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package config

import "reflect"

// ConnectionEquivalent reports whether two snapshots of the same server carry
// identical CONNECTION settings — everything that decides how mcpproxy dials or
// spawns the upstream.
//
// It is the supervisor's "did the user change something?" predicate. That used
// to be a five-field comparison (URL, protocol, command, enabled, quarantined),
// which was harmless only because a server that should be connected but wasn't
// eventually got an ActionConnect anyway. Since GH #1145 a permanently failed
// server is parked and that fallback no longer fires, so a missed field is a
// user who fixes their `args` — or points `isolation.image` at an image that
// actually has the toolchain — and never sees the server come back.
//
// Deliberately EXCLUDED: Name (identity, keyed elsewhere), Created, and Updated.
// Updated is rewritten by unrelated config writes (quarantine bookkeeping, tool
// hashes), so including it would reconnect every server on the next tick.
// Also excluded are settings that do not affect the connection itself — trust
// mode, tool allow/deny lists, concurrency limits, output formatting — which are
// applied in place without a redial.
func ConnectionEquivalent(a, b *ServerConfig) bool {
if a == nil || b == nil {
return a == b
}
return a.URL == b.URL &&
a.Protocol == b.Protocol &&
a.Command == b.Command &&
a.WorkingDir == b.WorkingDir &&
a.Enabled == b.Enabled &&
a.Quarantined == b.Quarantined &&
a.LauncherWaitTimeout == b.LauncherWaitTimeout &&
equalStringSlice(a.Args, b.Args) &&
equalStringMap(a.Env, b.Env) &&
equalStringMap(a.Headers, b.Headers) &&
equalDurationPtr(a.InitTimeout, b.InitTimeout) &&
reflect.DeepEqual(a.OAuth, b.OAuth) &&
reflect.DeepEqual(a.Isolation, b.Isolation)
}

func equalStringSlice(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}

func equalStringMap(a, b map[string]string) bool {
if len(a) != len(b) {
return false
}
for k, va := range a {
vb, ok := b[k]
if !ok || va != vb {
return false
}
}
return true
}

func equalDurationPtr(a, b *Duration) bool {
if a == nil || b == nil {
return a == b
}
return *a == *b
}
88 changes: 88 additions & 0 deletions internal/config/connection_equivalent_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package config

import (
"testing"
"time"
)

func baseServer() *ServerConfig {
iso := IsolationConfig{Image: "python:3.11"}
return &ServerConfig{
Name: "srv",
Command: "uvx",
Args: []string{"some-package"},
WorkingDir: "/tmp/a",
Env: map[string]string{"A": "1"},
Headers: map[string]string{"X": "y"},
Protocol: "stdio",
Enabled: true,
Quarantined: false,
Isolation: &iso,
Created: time.Now(),
}
}

// TestConnectionEquivalent_DetectsEveryConnectionField is the recovery half of
// GH #1145: once a permanently failed server stops being re-dialed, the ONLY
// thing that brings it back automatically is the supervisor noticing that the
// user edited its connection settings. A field missing here is a user who fixes
// the problem and sees nothing happen.
func TestConnectionEquivalent_DetectsEveryConnectionField(t *testing.T) {
tests := []struct {
name string
mutate func(*ServerConfig)
}{
{"url", func(c *ServerConfig) { c.URL = "https://example.test/mcp" }},
{"protocol", func(c *ServerConfig) { c.Protocol = "http" }},
{"command", func(c *ServerConfig) { c.Command = "npx" }},
{"args", func(c *ServerConfig) { c.Args = []string{"other-package"} }},
{"args length", func(c *ServerConfig) { c.Args = []string{"some-package", "--flag"} }},
{"working dir", func(c *ServerConfig) { c.WorkingDir = "/tmp/b" }},
{"env value", func(c *ServerConfig) { c.Env = map[string]string{"A": "2"} }},
{"env key added", func(c *ServerConfig) { c.Env = map[string]string{"A": "1", "B": "2"} }},
{"headers", func(c *ServerConfig) { c.Headers = map[string]string{"X": "z"} }},
{"enabled", func(c *ServerConfig) { c.Enabled = false }},
{"quarantined", func(c *ServerConfig) { c.Quarantined = true }},
{"isolation image", func(c *ServerConfig) { c.Isolation = &IsolationConfig{Image: "node:22"} }},
{"isolation removed", func(c *ServerConfig) { c.Isolation = nil }},
{"oauth added", func(c *ServerConfig) { c.OAuth = &OAuthConfig{ClientID: "abc"} }},
{"init timeout", func(c *ServerConfig) { d := Duration(time.Minute); c.InitTimeout = &d }},
{"launcher wait timeout", func(c *ServerConfig) { c.LauncherWaitTimeout = Duration(time.Minute) }},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
a, b := baseServer(), baseServer()
if !ConnectionEquivalent(a, b) {
t.Fatalf("two identical configs must compare equivalent")
}
tt.mutate(b)
if ConnectionEquivalent(a, b) {
t.Errorf("a change to %s must be detected as a connection change", tt.name)
}
})
}
}

// TestConnectionEquivalent_IgnoresVolatileFields is the other half, and the
// trap: Updated is rewritten by unrelated config writes (quarantine decisions,
// tool-hash bookkeeping). A whole-struct fingerprint would therefore reconnect
// EVERY server on the next tick — a reconnect storm dressed up as a bug fix.
func TestConnectionEquivalent_IgnoresVolatileFields(t *testing.T) {
a, b := baseServer(), baseServer()
b.Created = a.Created.Add(-72 * time.Hour)
b.Updated = time.Now()
b.Name = a.Name // identity is keyed elsewhere; not a connection setting
if !ConnectionEquivalent(a, b) {
t.Errorf("created/updated churn must not count as a connection change")
}
}

func TestConnectionEquivalent_NilHandling(t *testing.T) {
if !ConnectionEquivalent(nil, nil) {
t.Errorf("two absent configs are equivalent")
}
if ConnectionEquivalent(nil, baseServer()) || ConnectionEquivalent(baseServer(), nil) {
t.Errorf("appearing/disappearing config is a change")
}
}
9 changes: 9 additions & 0 deletions internal/contracts/converters.go
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,15 @@ func ConvertGenericServersToTyped(genericServers []map[string]interface{}) []Ser
case float64:
server.RetryCount = int(rc)
}
if retryStopped, ok := generic["retry_stopped"].(bool); ok {
server.RetryStopped = retryStopped
}
if code, ok := generic["retry_stopped_code"].(string); ok {
server.RetryStoppedCode = code
}
if reason, ok := generic["retry_stopped_reason"].(string); ok {
server.RetryStoppedReason = reason
}
switch v := generic["last_retry_time"].(type) {
case time.Time:
server.LastRetryTime = &v
Expand Down
19 changes: 15 additions & 4 deletions internal/contracts/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,21 @@ type Server struct {
ShouldRetry bool `json:"should_retry,omitempty"`
RetryCount int `json:"retry_count,omitempty"`
LastRetryTime *time.Time `json:"last_retry_time,omitempty"`
UserLoggedOut bool `json:"user_logged_out,omitempty"` // True if user explicitly logged out (prevents auto-reconnection)
Health *HealthStatus `json:"health,omitempty"` // Unified health status calculated by the backend
Quarantine *QuarantineStats `json:"quarantine,omitempty"` // Tool quarantine metrics for this server
ReconnectOnUse bool `json:"reconnect_on_use,omitempty"` // Attempt reconnection when a tool call targets this disconnected server
// RetryStopped reports that automatic reconnection has been given up for
// good because the failure is deterministic and unrecoverable — a missing
// binary, an image without the interpreter, an unparseable config (GH
// #1145). It is NOT ordinary exponential backoff, which keeps retrying;
// nothing will happen until the user fixes the config or restarts the
// server. RetryStoppedCode is the stable MCPX_* code that proved it and
// RetryStoppedReason the catalog message explaining how to fix it. All three
// are omitted for servers that are healthy or still retrying.
RetryStopped bool `json:"retry_stopped,omitempty"`
RetryStoppedCode string `json:"retry_stopped_code,omitempty"`
RetryStoppedReason string `json:"retry_stopped_reason,omitempty"`
UserLoggedOut bool `json:"user_logged_out,omitempty"` // True if user explicitly logged out (prevents auto-reconnection)
Health *HealthStatus `json:"health,omitempty"` // Unified health status calculated by the backend
Quarantine *QuarantineStats `json:"quarantine,omitempty"` // Tool quarantine metrics for this server
ReconnectOnUse bool `json:"reconnect_on_use,omitempty"` // Attempt reconnection when a tool call targets this disconnected server
// AutoApproveToolChanges mirrors config.ServerConfig.AutoApproveToolChanges
// (MCP-2930): the per-server intent to auto-approve new/changed tools past
// the trust baseline. Tri-state *bool — nil means "never set" (omitted from
Expand Down
51 changes: 51 additions & 0 deletions internal/diagnostics/catalog_contract_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package diagnostics

import (
"bytes"
"encoding/json"
"os"
"path/filepath"
"testing"

"github.com/santhosh-tekuri/jsonschema/v6"
"github.com/stretchr/testify/require"
)

// contractPath is the PUBLISHED output contract for `mcpproxy doctor
// list-codes -o json`. It sets additionalProperties:false, so any field added
// to CatalogEntry without a matching contract update makes the command emit a
// document that fails its own schema.
const contractPath = "../../specs/044-diagnostics-taxonomy/contracts/catalog-schema.json"

// TestCatalog_MatchesPublishedContract validates the real serialized catalog
// against the shipped JSON schema. Nothing in CI did this before, which is how
// the `retry` field (GH #1145) reached the published output without reaching
// the contract.
func TestCatalog_MatchesPublishedContract(t *testing.T) {
abs, err := filepath.Abs(contractPath)
require.NoError(t, err)
raw, err := os.ReadFile(abs)
require.NoError(t, err, "the published catalog contract must exist")

doc, err := jsonschema.UnmarshalJSON(bytes.NewReader(raw))
require.NoError(t, err)

c := jsonschema.NewCompiler()
require.NoError(t, c.AddResource("catalog-schema.json", doc))
schema, err := c.Compile("catalog-schema.json")
require.NoError(t, err)

entries := All()
require.NotEmpty(t, entries)

for _, entry := range entries {
t.Run(string(entry.Code), func(t *testing.T) {
encoded, err := json.Marshal(entry)
require.NoError(t, err)
instance, err := jsonschema.UnmarshalJSON(bytes.NewReader(encoded))
require.NoError(t, err)
require.NoError(t, schema.Validate(instance),
"catalog entry does not satisfy the published contract:\n%s", encoded)
})
}
}
51 changes: 51 additions & 0 deletions internal/diagnostics/hints/hints.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// Package hints builds diagnostics.ClassifierHints from configuration.
//
// It exists so the supervisor and the managed client classify the SAME failure
// the same way. Each used to (or would) hand-roll the Docker-isolation
// predicate, and a hand-rolled mirror has already drifted from the spawn path
// once (GH #1142): a `mode: "docker"` server was Docker-launched but classified
// as a plain host ENOENT. Since GH #1145 the classification decides whether a
// server is parked as terminally failed, a drift now changes retry behaviour and
// not just a help message.
package hints

import (
"github.com/smart-mcp-proxy/mcpproxy-go/internal/config"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/diagnostics"
)

// For builds the classifier hints for one server's failure.
//
// The Docker predicate delegates to config.ResolveIsolation — the SAME resolver
// the spawn path branches on (core.IsolationManager.ShouldIsolate wraps it) — so
// the hint cannot drift from the launch decision. The predicate is
// Mode == docker, not ResolvedIsolation.Isolated: the DOCKER remediation codes
// describe the container LAUNCH path, which runs whenever the mode is docker.
//
// The enrichment fields (command, image override, default images) only feed
// MCP-2909's runtime-aware remediation text; they never change classification.
func For(global *config.Config, srv *config.ServerConfig, transport string) diagnostics.ClassifierHints {
h := diagnostics.ClassifierHints{Transport: transport}
if srv == nil {
return h
}
h.ServerID = srv.Name

var dockerGlobal *config.DockerIsolationConfig
if global != nil {
dockerGlobal = global.DockerIsolation
}
h.DockerIsolated = config.ResolveIsolation(dockerGlobal, srv).Mode == config.IsolationModeDocker
if !h.DockerIsolated {
return h
}

h.DockerCommand = srv.Command
if srv.Isolation != nil {
h.DockerImageOverride = srv.Isolation.Image
}
if dockerGlobal != nil {
h.DockerDefaultImages = dockerGlobal.DefaultImages
}
return h
}
Loading
Loading