From ba9af18a8a042a87525a41d2f8546bd2f95d50cd Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Mon, 24 Aug 2026 21:37:21 +0300 Subject: [PATCH 1/4] fix(tray): preserve host in normalizeListen + sane port-conflict and core-URL semantics for pinned --listen MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three follow-ups to PR #1015 (tray --listen forwarding): 1. normalizeListen("127.0.0.1:8181") returned ":8181", silently rebinding a loopback-pinned address to every interface — and that value is forwarded verbatim as the core's --listen from both the MCPPROXY_TRAY_LISTEN path and the new CLI path. It now never widens a bind: a pinned host is preserved (IPv6 included), a bare port defaults to loopback (matching listenArgFromURL's rule for derived addresses), an explicit all-interfaces request is honored, and unparseable input passes through for the core to reject. 2. handlePortConflictError bumped the port and relaunched, expecting buildCoreArgs to derive the new one from coreURL — but an explicit CLI --listen always wins, so the retry would re-hit the same busy port forever. An explicitly pinned listen is now treated as a user contract: fail loudly (error log + state-machine error + tray notification) instead of silently retrying or silently moving off the pinned address. Unpinned setups keep the auto-bump. The choice is documented at the call site. 3. resolveCoreURL ignored the CLI listen on the TCP-fallback path, so the core bound the pinned port while the tray probed the default. It now takes the parsed CLI listen (highest priority, above MCPPROXY_TRAY_LISTEN and MCPPROXY_TRAY_PORT); wildcard binds are dialed on loopback. --- cmd/mcpproxy-tray/main.go | 126 +++++++++++++-- cmd/mcpproxy-tray/main_test.go | 171 ++++++++++++++++++++ docs/configuration/environment-variables.md | 2 +- docs/tray-debug.md | 2 +- internal/tray/notifications.go | 16 ++ internal/tray/notifications_stub.go | 7 + 6 files changed, 307 insertions(+), 17 deletions(-) diff --git a/cmd/mcpproxy-tray/main.go b/cmd/mcpproxy-tray/main.go index ecb99d427..f8d11953f 100644 --- a/cmd/mcpproxy-tray/main.go +++ b/cmd/mcpproxy-tray/main.go @@ -40,6 +40,10 @@ import ( const ( platformDarwin = "darwin" platformWindows = "windows" + + // loopbackHost is the bind/dial host the tray falls back to whenever an + // address is derived rather than explicitly pinned by the user. + loopbackHost = "127.0.0.1" ) var ( @@ -127,7 +131,7 @@ func main() { defer cancel() // Resolve core configuration up front - coreURL := resolveCoreURL() + coreURL := resolveCoreURL(trayCLIListen) logger.Info("Resolved core URL", zap.String("core_url", coreURL)) // Determine if we're using socket/pipe communication (which doesn't need API key) @@ -442,7 +446,12 @@ func newTrayJSONEncoder() zapcore.Encoder { }) } -func resolveCoreURL() string { +// resolveCoreURL determines the endpoint the tray uses to talk to the core. +// cliListen is the --listen value parsed from the tray's own command line (see +// trayListenFromArgs); it matters on the TCP fallback path, where the core is +// launched with that pinned address and the tray must probe the SAME address +// instead of the 127.0.0.1:8080 default. +func resolveCoreURL(cliListen string) string { // Priority 1: Explicit override via environment variable if override := strings.TrimSpace(os.Getenv("MCPPROXY_CORE_URL")); override != "" { return override @@ -459,18 +468,31 @@ func resolveCoreURL() string { } // Priority 3: Fall back to TCP (HTTP/HTTPS) + return resolveCoreTCPURL(cliListen) +} + +// resolveCoreTCPURL builds the TCP endpoint for the core, honouring (in order) +// an explicit --listen from the tray's command line, MCPPROXY_TRAY_LISTEN, +// MCPPROXY_TRAY_PORT, and finally the built-in default. +func resolveCoreTCPURL(cliListen string) string { // Determine protocol based on TLS setting protocol := "http" if strings.TrimSpace(os.Getenv("MCPPROXY_TLS_ENABLED")) == "true" { protocol = "https" } - if listen := normalizeListen(strings.TrimSpace(os.Getenv("MCPPROXY_TRAY_LISTEN"))); listen != "" { - return protocol + "://127.0.0.1" + listen + // An explicit --listen on the tray's command line wins: buildCoreArgs always + // forwards it to the core, so the core binds it and nothing else. + if coreURL := coreURLFromListen(protocol, cliListen); coreURL != "" { + return coreURL + } + + if coreURL := coreURLFromListen(protocol, os.Getenv("MCPPROXY_TRAY_LISTEN")); coreURL != "" { + return coreURL } if port := strings.TrimSpace(os.Getenv("MCPPROXY_TRAY_PORT")); port != "" { - return fmt.Sprintf("%s://127.0.0.1:%s", protocol, port) + return fmt.Sprintf("%s://%s", protocol, net.JoinHostPort(loopbackHost, port)) } // Update default URL based on TLS setting @@ -978,28 +1000,66 @@ func listenArgFromURL(raw string) string { return net.JoinHostPort(host, port) } +// normalizeListen canonicalises a listen address before it is handed to the +// core as --listen. Its one hard rule is that it NEVER widens a bind: +// +// - a host the caller pinned is preserved verbatim ("127.0.0.1:8181" stays +// loopback; "localhost" stays localhost — resolving it is the core's job), +// - a bare port with no host at all ("8181") defaults to loopback, mirroring +// listenArgFromURL's "never bind to all interfaces" rule for derived +// addresses, +// - an explicit all-interfaces request (":8181", "0.0.0.0:8181", "[::]:8181") +// is honoured as written — the caller asked for it, and rewriting it would +// break the LAN-exposure use case the tray --listen flag exists for, +// - anything that is not a host:port pair is passed through untouched so the +// core rejects it loudly instead of the tray silently rewriting it. +// +// It used to strip the loopback host ("127.0.0.1:8181" -> ":8181"), which +// silently rebound a loopback-pinned address to every interface. func normalizeListen(listen string) string { + listen = strings.TrimSpace(listen) if listen == "" { return "" } - if strings.HasPrefix(listen, "localhost:") { - return strings.TrimPrefix(listen, "localhost") + // Bare port, e.g. "8181": no host was expressed at all, so pick loopback + // rather than letting the core infer the ":8181" all-interfaces bind. + if !strings.Contains(listen, ":") { + if _, err := strconv.Atoi(listen); err != nil { + return listen // not a port — leave it for the core to reject + } + return net.JoinHostPort(loopbackHost, listen) } - if strings.HasPrefix(listen, "127.0.0.1:") { - return strings.TrimPrefix(listen, "127.0.0.1") + host, port, err := net.SplitHostPort(listen) + if err != nil { + return listen // not a host:port pair — leave it for the core to reject } - if strings.HasPrefix(listen, ":") { - return listen + // JoinHostPort re-adds IPv6 brackets; host "" round-trips to ":". + return net.JoinHostPort(host, port) +} + +// coreURLFromListen converts a --listen address into a URL the tray can dial. +// Wildcard binds are dialed on loopback: the core listens on every interface, +// but the tray always talks to it locally. +func coreURLFromListen(protocol, listen string) string { + listen = normalizeListen(listen) + if listen == "" { + return "" } - if !strings.Contains(listen, ":") { - return ":" + listen + host, port, err := net.SplitHostPort(listen) + if err != nil || port == "" { + return "" + } + + switch host { + case "", "0.0.0.0", "::": + host = loopbackHost } - return listen + return protocol + "://" + net.JoinHostPort(host, port) } // Legacy process termination removed - replaced by monitor.ProcessMonitor @@ -1482,8 +1542,44 @@ func (cpl *CoreProcessLauncher) handleReconnecting(_ context.Context) { // The state machine will handle retry logic automatically } -// handlePortConflictError handles port conflict errors +// pinnedCoreListen returns the listen address the user explicitly pinned on the +// tray's command line (normalized), or "" when nothing was pinned. +// +// Only the CLI flag counts as pinned: buildCoreArgs forwards it unconditionally +// and it beats every other source, so the core can only ever bind that address. +// MCPPROXY_TRAY_LISTEN, by contrast, flows through coreURL (resolveCoreTCPURL), +// so the port-conflict auto-bump can still move it and have the new address +// reach the core. +func pinnedCoreListen() string { + return normalizeListen(trayCLIListen) +} + +// handlePortConflictError handles port conflict errors. +// +// Semantics, decided in the follow-up to PR #1015 (tray --listen forwarding): +// an explicitly pinned --listen is a user contract — the core comes up on THAT +// address or not at all. Auto-bumping the port here only ever worked because +// buildCoreArgs derived --listen from cpl.coreURL; now that an explicit CLI +// --listen always wins, bumping the port would relaunch the core on the very +// same busy address forever. Silently moving off the pinned address would be +// worse still: clients configured for it would talk to nothing. So we fail +// loudly instead — log an error, record it on the state machine, and notify the +// user — and leave the tray in the port-conflict state (the state machine keeps +// error states until the user acts). Unpinned setups keep the old auto-bump. func (cpl *CoreProcessLauncher) handlePortConflictError() { + if pinned := pinnedCoreListen(); pinned != "" { + err := fmt.Errorf("core cannot start: the pinned listen address %s is already in use; "+ + "free the port or restart the tray with a different --listen", pinned) + cpl.logger.Errorw("Port conflict on an explicitly pinned listen address - not auto-selecting another port", + "listen", pinned, + "error", err) + cpl.stateMachine.SetError(err) + if notifyErr := tray.ShowPortConflictPinned(pinned); notifyErr != nil { + cpl.logger.Warnw("Failed to show port conflict notification", "error", notifyErr) + } + return + } + cpl.logger.Warn("Core failed due to port conflict") // Attempt automatic port resolution on Windows/macOS // 1) Parse current coreURL and extract port diff --git a/cmd/mcpproxy-tray/main_test.go b/cmd/mcpproxy-tray/main_test.go index e68a09369..1ab7e8ad6 100644 --- a/cmd/mcpproxy-tray/main_test.go +++ b/cmd/mcpproxy-tray/main_test.go @@ -86,6 +86,177 @@ func TestBuildCoreArgs_ForwardsCLIListenOverSocketEndpoint(t *testing.T) { } } +// TestNormalizeListen is the security-adjacent invariant: normalizeListen must +// never WIDEN a bind. It used to strip the loopback host ("127.0.0.1:8181" -> +// ":8181"), which handed the core an all-interfaces bind for an address the +// user had explicitly pinned to loopback — and that value is forwarded verbatim +// as the core's --listen from both the MCPPROXY_TRAY_LISTEN and the CLI path. +func TestNormalizeListen(t *testing.T) { + tcases := []struct { + name string + input string + expected string + }{ + {"empty", "", ""}, + {"whitespace only", " ", ""}, + {"loopback host is preserved, not stripped", "127.0.0.1:8181", "127.0.0.1:8181"}, + {"loopback host with surrounding space", " 127.0.0.1:8181 ", "127.0.0.1:8181"}, + {"localhost is preserved", "localhost:8181", "localhost:8181"}, + {"explicit LAN host is preserved", "192.168.1.10:8181", "192.168.1.10:8181"}, + {"IPv6 loopback is preserved", "[::1]:8181", "[::1]:8181"}, + {"bare port defaults to loopback, never all interfaces", "8181", "127.0.0.1:8181"}, + {"explicit all-interfaces is honored", "0.0.0.0:8181", "0.0.0.0:8181"}, + {"explicit wildcard port form is honored", ":8181", ":8181"}, + {"IPv6 wildcard is honored", "[::]:8181", "[::]:8181"}, + {"unparseable value passes through for the core to reject", "not a listen addr", "not a listen addr"}, + } + + for _, tc := range tcases { + t.Run(tc.name, func(t *testing.T) { + if got := normalizeListen(tc.input); got != tc.expected { + t.Fatalf("normalizeListen(%q) = %q, expected %q", tc.input, got, tc.expected) + } + }) + } +} + +func TestCoreURLFromListen(t *testing.T) { + tcases := []struct { + name string + protocol string + listen string + expected string + }{ + {"empty", "http", "", ""}, + {"loopback", "http", "127.0.0.1:8181", "http://127.0.0.1:8181"}, + {"bare port", "http", "8181", "http://127.0.0.1:8181"}, + {"wildcard dials loopback", "http", "0.0.0.0:8181", "http://127.0.0.1:8181"}, + {"bare wildcard dials loopback", "http", ":8181", "http://127.0.0.1:8181"}, + {"IPv6 wildcard dials loopback", "http", "[::]:8181", "http://127.0.0.1:8181"}, + {"explicit host is dialed as given", "https", "192.168.1.10:8181", "https://192.168.1.10:8181"}, + {"IPv6 host keeps brackets", "http", "[::1]:8181", "http://[::1]:8181"}, + {"garbage yields no URL", "http", "not a listen addr", ""}, + } + + for _, tc := range tcases { + t.Run(tc.name, func(t *testing.T) { + if got := coreURLFromListen(tc.protocol, tc.listen); got != tc.expected { + t.Fatalf("coreURLFromListen(%q, %q) = %q, expected %q", tc.protocol, tc.listen, got, tc.expected) + } + }) + } +} + +// TestResolveCoreTCPURL covers the no-socket fallback: the core is launched with +// the pinned --listen, so the tray must probe that same address instead of the +// 127.0.0.1:8080 default. +func TestResolveCoreTCPURL(t *testing.T) { + t.Run("CLI listen wins over env and default", func(t *testing.T) { + t.Setenv("MCPPROXY_TLS_ENABLED", "") + t.Setenv("MCPPROXY_TRAY_LISTEN", "127.0.0.1:9000") + t.Setenv("MCPPROXY_TRAY_PORT", "9100") + + if got := resolveCoreTCPURL("0.0.0.0:8181"); got != "http://127.0.0.1:8181" { + t.Fatalf("resolveCoreTCPURL with CLI listen = %q, expected http://127.0.0.1:8181", got) + } + }) + + t.Run("env listen keeps its host", func(t *testing.T) { + t.Setenv("MCPPROXY_TLS_ENABLED", "") + t.Setenv("MCPPROXY_TRAY_LISTEN", "127.0.0.1:9000") + t.Setenv("MCPPROXY_TRAY_PORT", "") + + if got := resolveCoreTCPURL(""); got != "http://127.0.0.1:9000" { + t.Fatalf("resolveCoreTCPURL with env listen = %q, expected http://127.0.0.1:9000", got) + } + }) + + t.Run("port env still honored", func(t *testing.T) { + t.Setenv("MCPPROXY_TLS_ENABLED", "") + t.Setenv("MCPPROXY_TRAY_LISTEN", "") + t.Setenv("MCPPROXY_TRAY_PORT", "9100") + + if got := resolveCoreTCPURL(""); got != "http://127.0.0.1:9100" { + t.Fatalf("resolveCoreTCPURL with port env = %q, expected http://127.0.0.1:9100", got) + } + }) + + t.Run("TLS switches the scheme", func(t *testing.T) { + t.Setenv("MCPPROXY_TLS_ENABLED", "true") + t.Setenv("MCPPROXY_TRAY_LISTEN", "") + t.Setenv("MCPPROXY_TRAY_PORT", "") + + if got := resolveCoreTCPURL("127.0.0.1:8181"); got != "https://127.0.0.1:8181" { + t.Fatalf("resolveCoreTCPURL with TLS = %q, expected https://127.0.0.1:8181", got) + } + if got := resolveCoreTCPURL(""); got != "https://127.0.0.1:8080" { + t.Fatalf("resolveCoreTCPURL default with TLS = %q, expected https://127.0.0.1:8080", got) + } + }) + + t.Run("nothing pinned falls back to the default", func(t *testing.T) { + t.Setenv("MCPPROXY_TLS_ENABLED", "") + t.Setenv("MCPPROXY_TRAY_LISTEN", "") + t.Setenv("MCPPROXY_TRAY_PORT", "") + + if got := resolveCoreTCPURL(""); got != defaultCoreURL { + t.Fatalf("resolveCoreTCPURL fallback = %q, expected %q", got, defaultCoreURL) + } + }) +} + +// TestBuildCoreArgs_LoopbackListenIsNotWidened pins the end-to-end consequence +// of the normalizeListen fix: a loopback-pinned tray must not hand the core an +// all-interfaces --listen. +func TestBuildCoreArgs_LoopbackListenIsNotWidened(t *testing.T) { + t.Setenv("MCPPROXY_TRAY_CONFIG_PATH", "") + t.Setenv("MCPPROXY_TRAY_EXTRA_ARGS", "") + + original := trayCLIListen + defer func() { trayCLIListen = original }() + + // CLI path. + t.Setenv("MCPPROXY_TRAY_LISTEN", "") + trayCLIListen = "127.0.0.1:8181" + args := buildCoreArgs("unix:///tmp/mcpproxy.sock") + expected := []string{"serve", "--listen", "127.0.0.1:8181"} + if strings.Join(args, " ") != strings.Join(expected, " ") { + t.Fatalf("buildCoreArgs (CLI loopback listen) = %v, expected %v", args, expected) + } + + // Env path (TCP core URL, no listen derivable from a hostless URL). + trayCLIListen = "" + t.Setenv("MCPPROXY_TRAY_LISTEN", "127.0.0.1:8181") + args = buildCoreArgs("http://") + if strings.Join(args, " ") != strings.Join(expected, " ") { + t.Fatalf("buildCoreArgs (env loopback listen) = %v, expected %v", args, expected) + } +} + +// TestPinnedCoreListen documents which listen sources are treated as a user +// contract that must not be silently moved on a port conflict. +func TestPinnedCoreListen(t *testing.T) { + original := trayCLIListen + defer func() { trayCLIListen = original }() + + trayCLIListen = "127.0.0.1:8181" + if got := pinnedCoreListen(); got != "127.0.0.1:8181" { + t.Fatalf("pinnedCoreListen() with CLI listen = %q, expected 127.0.0.1:8181", got) + } + + trayCLIListen = "8181" + if got := pinnedCoreListen(); got != "127.0.0.1:8181" { + t.Fatalf("pinnedCoreListen() normalizes bare port = %q, expected 127.0.0.1:8181", got) + } + + // The env listen flows through coreURL, so the auto-bump can still move it. + trayCLIListen = "" + t.Setenv("MCPPROXY_TRAY_LISTEN", "127.0.0.1:8181") + if got := pinnedCoreListen(); got != "" { + t.Fatalf("pinnedCoreListen() with only env listen = %q, expected \"\"", got) + } +} + func TestNewTrayLogConfig_DarwinUsesConsoleAndRotationDefaults(t *testing.T) { cfg := newTrayLogConfig(platformDarwin, "/tmp/tray-logs") diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md index c0805f8a3..c50af6da6 100644 --- a/docs/configuration/environment-variables.md +++ b/docs/configuration/environment-variables.md @@ -131,7 +131,7 @@ The tray application doesn't read the config file directly. It launches the core | Variable | Description | Default | |----------|-------------|---------| | `MCPPROXY_TRAY_PORT` | Port for tray-launched core | `8080` | -| `MCPPROXY_TRAY_LISTEN` | Listen address for core (e.g., `:8080`) | - | +| `MCPPROXY_TRAY_LISTEN` | Listen address for core (e.g., `127.0.0.1:8080`; a bare port binds loopback) | - | | `MCPPROXY_CORE_URL` | Full URL override (e.g., `http://127.0.0.1:30080`) | - | | `MCPPROXY_CORE_PATH` | Custom path to mcpproxy core binary | - | | `MCPPROXY_TRAY_CONFIG_PATH` | Custom config file path for core | - | diff --git a/docs/tray-debug.md b/docs/tray-debug.md index 497b9d47b..66a4dc96f 100644 --- a/docs/tray-debug.md +++ b/docs/tray-debug.md @@ -176,7 +176,7 @@ The tray launches `mcpproxy serve` when it detects that no core is running. You - `MCPPROXY_CORE_URL` – full base URL the tray should connect to (e.g. `http://localhost:8085`). This also controls the health checks. - `MCPPROXY_CORE_PATH` – custom path to the mcpproxy core binary (defaults to bundled binary or PATH lookup). -- `MCPPROXY_TRAY_LISTEN` / `MCPPROXY_TRAY_PORT` – override the port passed to `--listen` when the tray launches the core (formats accepted: `:8085` or `8085`). +- `MCPPROXY_TRAY_LISTEN` / `MCPPROXY_TRAY_PORT` – override the address passed to `--listen` when the tray launches the core (formats accepted: `127.0.0.1:8085`, `:8085` or `8085`). The host is never widened: a pinned host is forwarded as written, and a bare port (`8085`) binds loopback. A `--listen` on the tray's own command line takes precedence over both; when it is set and the port is busy, the tray reports the conflict instead of moving the core to another port. - `MCPPROXY_TRAY_CONFIG_PATH` – absolute path to the `mcp_config.json` the tray should hand to the core via `--config`. - `MCPPROXY_TRAY_EXTRA_ARGS` – optional additional CLI arguments (whitespace separated) appended after `serve`. - `MCPPROXY_TRAY_SKIP_CORE` – set to `1` to prevent the tray from launching the core automatically (useful when attaching to an external instance). diff --git a/internal/tray/notifications.go b/internal/tray/notifications.go index a2235a53d..fda1addb8 100644 --- a/internal/tray/notifications.go +++ b/internal/tray/notifications.go @@ -65,6 +65,22 @@ func ShowDockerRecoverySuccess(serverCount int) error { ) } +// ShowPortConflictPinned shows a notification when the core cannot start +// because the listen address the user explicitly pinned is already in use. +// The tray deliberately does not pick another port in that case, so the user +// has to be told. +func ShowPortConflictPinned(listenAddr string) error { + msg := "The address the tray was started with is already in use. Free the port or restart with a different --listen." + if listenAddr != "" { + msg = fmt.Sprintf("%s is already in use. Free the port or restart the tray with a different --listen.", listenAddr) + } + return beeep.Notify( + "mcpproxy: port conflict", + msg, + "", + ) +} + // ShowDockerRecoveryFailed shows a notification when Docker recovery fails func ShowDockerRecoveryFailed(reason string) error { msg := "Unable to reconnect servers. Check Docker status." diff --git a/internal/tray/notifications_stub.go b/internal/tray/notifications_stub.go index 18fd5594e..3963afed7 100644 --- a/internal/tray/notifications_stub.go +++ b/internal/tray/notifications_stub.go @@ -42,6 +42,13 @@ func ShowDockerRecoverySuccess(serverCount int) error { return nil } +// ShowPortConflictPinned shows a notification when the core cannot start on the +// user's pinned listen address (stub) +func ShowPortConflictPinned(listenAddr string) error { + // No-op for headless/linux builds + return nil +} + // ShowDockerRecoveryFailed shows a notification when Docker recovery fails (stub) func ShowDockerRecoveryFailed(reason string) error { // No-op for headless/linux builds From 647efd0f0967228bab5bc6971543f85dfaf90f1e Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Mon, 24 Aug 2026 21:46:55 +0300 Subject: [PATCH 2/4] fix(tray): percent-escape IPv6 zones in the derived core URL MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Cross-model review finding on the new coreURLFromListen(): it built the URL by string concatenation, so a zoned IPv6 listen such as "[fe80::1%en0]:8181" produced "http://[fe80::1%en0]:8181" — which url.Parse rejects outright with `invalid URL escape "%en"`. Every later parse of the core URL (readiness checks, listenArgFromURL, the port-conflict handler) would then fail on an address the function was specifically meant to support, since it already claimed IPv6 handling. Build the URL through url.URL instead, which escapes the zone ("fe80::1%en0" -> "fe80::1%25en0") and round-trips through url.Parse. Adds the zoned case to the coreURLFromListen table plus a TestCoreURLFromListen_AlwaysParseable invariant asserting that every derived core URL survives url.Parse with the expected port. Also tightens docs/tray-debug.md: an all-interfaces value supplied via MCPPROXY_TRAY_LISTEN / MCPPROXY_TRAY_PORT is narrowed to loopback (the core's --listen is derived from the URL the tray dials), so the tray's own --listen flag is the way to ask for a LAN-exposed bind. The previous wording implied the variables forwarded any host as written. --- cmd/mcpproxy-tray/main.go | 8 +++++++- cmd/mcpproxy-tray/main_test.go | 30 ++++++++++++++++++++++++++++++ docs/tray-debug.md | 2 +- 3 files changed, 38 insertions(+), 2 deletions(-) diff --git a/cmd/mcpproxy-tray/main.go b/cmd/mcpproxy-tray/main.go index f8d11953f..0fe07ae09 100644 --- a/cmd/mcpproxy-tray/main.go +++ b/cmd/mcpproxy-tray/main.go @@ -1059,7 +1059,13 @@ func coreURLFromListen(protocol, listen string) string { host = loopbackHost } - return protocol + "://" + net.JoinHostPort(host, port) + // Build via url.URL rather than concatenating: an IPv6 zone must be + // percent-escaped in a URL ("fe80::1%en0" -> "fe80::1%25en0"). Plain + // concatenation emits a string that url.Parse rejects outright with + // "invalid URL escape", which would break every later parse of the core + // URL (health checks, listenArgFromURL, the port-conflict handler). + u := url.URL{Scheme: protocol, Host: net.JoinHostPort(host, port)} + return u.String() } // Legacy process termination removed - replaced by monitor.ProcessMonitor diff --git a/cmd/mcpproxy-tray/main_test.go b/cmd/mcpproxy-tray/main_test.go index 1ab7e8ad6..4ccfb913b 100644 --- a/cmd/mcpproxy-tray/main_test.go +++ b/cmd/mcpproxy-tray/main_test.go @@ -3,6 +3,7 @@ package main import ( + "net/url" "os" "path/filepath" "strings" @@ -135,6 +136,10 @@ func TestCoreURLFromListen(t *testing.T) { {"IPv6 wildcard dials loopback", "http", "[::]:8181", "http://127.0.0.1:8181"}, {"explicit host is dialed as given", "https", "192.168.1.10:8181", "https://192.168.1.10:8181"}, {"IPv6 host keeps brackets", "http", "[::1]:8181", "http://[::1]:8181"}, + // A zone must be percent-escaped in a URL, otherwise url.Parse rejects + // the result with "invalid URL escape" and every later parse of the + // core URL fails. + {"IPv6 zone is percent-escaped", "http", "[fe80::1%en0]:8181", "http://[fe80::1%25en0]:8181"}, {"garbage yields no URL", "http", "not a listen addr", ""}, } @@ -147,6 +152,31 @@ func TestCoreURLFromListen(t *testing.T) { } } +// TestCoreURLFromListen_AlwaysParseable is the invariant behind the escaping: +// whatever coreURLFromListen returns must survive url.Parse, because the tray +// re-parses the core URL for health checks, listenArgFromURL and the +// port-conflict handler. +func TestCoreURLFromListen_AlwaysParseable(t *testing.T) { + listens := []string{ + "8181", "127.0.0.1:8181", "localhost:8181", "192.168.1.10:8181", + ":8181", "0.0.0.0:8181", "[::]:8181", "[::1]:8181", "[fe80::1%en0]:8181", + } + + for _, listen := range listens { + got := coreURLFromListen("http", listen) + if got == "" { + t.Fatalf("coreURLFromListen(http, %q) returned no URL", listen) + } + u, err := url.Parse(got) + if err != nil { + t.Fatalf("url.Parse(coreURLFromListen(http, %q) = %q): %v", listen, got, err) + } + if u.Port() != "8181" { + t.Fatalf("coreURLFromListen(http, %q) = %q, port = %q, expected 8181", listen, got, u.Port()) + } + } +} + // TestResolveCoreTCPURL covers the no-socket fallback: the core is launched with // the pinned --listen, so the tray must probe that same address instead of the // 127.0.0.1:8080 default. diff --git a/docs/tray-debug.md b/docs/tray-debug.md index 66a4dc96f..2e8d3f765 100644 --- a/docs/tray-debug.md +++ b/docs/tray-debug.md @@ -176,7 +176,7 @@ The tray launches `mcpproxy serve` when it detects that no core is running. You - `MCPPROXY_CORE_URL` – full base URL the tray should connect to (e.g. `http://localhost:8085`). This also controls the health checks. - `MCPPROXY_CORE_PATH` – custom path to the mcpproxy core binary (defaults to bundled binary or PATH lookup). -- `MCPPROXY_TRAY_LISTEN` / `MCPPROXY_TRAY_PORT` – override the address passed to `--listen` when the tray launches the core (formats accepted: `127.0.0.1:8085`, `:8085` or `8085`). The host is never widened: a pinned host is forwarded as written, and a bare port (`8085`) binds loopback. A `--listen` on the tray's own command line takes precedence over both; when it is set and the port is busy, the tray reports the conflict instead of moving the core to another port. +- `MCPPROXY_TRAY_LISTEN` / `MCPPROXY_TRAY_PORT` – override the address passed to `--listen` when the tray launches the core (formats accepted: `127.0.0.1:8085`, `:8085` or `8085`). The host is never widened: a pinned host is forwarded as written, and a bare port (`8085`) binds loopback. Note that an all-interfaces value set *through these variables* (`:8085`, `0.0.0.0:8085`) is narrowed to loopback, because the tray derives the core's `--listen` from the URL it dials; use the tray's own `--listen` flag when you actually want a LAN-exposed bind. That flag takes precedence over both variables, and when it is set and the port is busy the tray reports the conflict instead of moving the core to another port. - `MCPPROXY_TRAY_CONFIG_PATH` – absolute path to the `mcp_config.json` the tray should hand to the core via `--config`. - `MCPPROXY_TRAY_EXTRA_ARGS` – optional additional CLI arguments (whitespace separated) appended after `serve`. - `MCPPROXY_TRAY_SKIP_CORE` – set to `1` to prevent the tray from launching the core automatically (useful when attaching to an external instance). From f841368dbfb83245ceddce39ec1f34a9dacb671c Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Mon, 24 Aug 2026 21:53:55 +0300 Subject: [PATCH 3/4] fix(tray): surface an unparseable explicit listen instead of dropping it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Second cross-model review round. Before the resolveCoreURL rework, an unparseable MCPPROXY_TRAY_LISTEN / --listen produced an unparseable core URL, so listenArgFromURL returned "" and buildCoreArgs fell through to the raw env value — handing the core a bad --listen that it rejected loudly. Now coreURLFromListen returns "" for such a value and resolveCoreTCPURL falls through to the valid default endpoint, so listenArgFromURL succeeds and the explicitly configured address is dropped without a trace. Worse, when a core is already listening on that default the tray attaches to it and looks like it honoured an address it actually ignored. Add unparseableListenSources(), which reports every explicitly set listen value that cannot be turned into a dialable endpoint, and log each one at Warn from main() next to the resolved core URL. This keeps normalizeListen's stated contract — unparseable input is surfaced rather than silently rewritten — on the path that no longer reaches the core. Behaviour is otherwise unchanged: valid values (bare port, pinned host, wildcard, IPv6) report nothing, and blank/whitespace values count as unset. --- cmd/mcpproxy-tray/main.go | 38 ++++++++++++++++++++++++++++++ cmd/mcpproxy-tray/main_test.go | 43 ++++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+) diff --git a/cmd/mcpproxy-tray/main.go b/cmd/mcpproxy-tray/main.go index 0fe07ae09..4395b3df6 100644 --- a/cmd/mcpproxy-tray/main.go +++ b/cmd/mcpproxy-tray/main.go @@ -134,6 +134,17 @@ func main() { coreURL := resolveCoreURL(trayCLIListen) logger.Info("Resolved core URL", zap.String("core_url", coreURL)) + // An explicitly configured listen address that cannot be parsed must not + // pass unnoticed. resolveCoreURL falls through to the default endpoint for + // such a value, and if a core is already listening there the tray attaches + // to it — looking as though it honoured an address it actually ignored. + for _, src := range unparseableListenSources(trayCLIListen) { + logger.Warn("Ignoring unparseable listen address - falling back to the default core endpoint", + zap.String("source", src.name), + zap.String("value", src.value), + zap.String("core_url", coreURL)) + } + // Determine if we're using socket/pipe communication (which doesn't need API key) usingSocketCommunication := isSocketEndpoint(coreURL) @@ -471,6 +482,33 @@ func resolveCoreURL(cliListen string) string { return resolveCoreTCPURL(cliListen) } +// listenSource names where an explicitly configured listen address came from. +type listenSource struct { + name string + value string +} + +// unparseableListenSources reports every explicitly configured listen address +// that is set but cannot be turned into an endpoint the tray can dial. Such a +// value is silently dropped by resolveCoreTCPURL's fall-through (and then by +// buildCoreArgs, which derives --listen from the resulting default core URL), +// so callers surface it instead of letting the tray pretend it was honoured. +func unparseableListenSources(cliListen string) []listenSource { + var bad []listenSource + for _, src := range []listenSource{ + {"--listen", cliListen}, + {"MCPPROXY_TRAY_LISTEN", os.Getenv("MCPPROXY_TRAY_LISTEN")}, + } { + if strings.TrimSpace(src.value) == "" { + continue + } + if coreURLFromListen("http", src.value) == "" { + bad = append(bad, src) + } + } + return bad +} + // resolveCoreTCPURL builds the TCP endpoint for the core, honouring (in order) // an explicit --listen from the tray's command line, MCPPROXY_TRAY_LISTEN, // MCPPROXY_TRAY_PORT, and finally the built-in default. diff --git a/cmd/mcpproxy-tray/main_test.go b/cmd/mcpproxy-tray/main_test.go index 4ccfb913b..ac4a3d8d1 100644 --- a/cmd/mcpproxy-tray/main_test.go +++ b/cmd/mcpproxy-tray/main_test.go @@ -263,6 +263,49 @@ func TestBuildCoreArgs_LoopbackListenIsNotWidened(t *testing.T) { } } +// TestUnparseableListenSources covers the loudness regression found in +// cross-model review: before this change an unparseable explicit listen made +// resolveCoreURL produce an unparseable core URL, so buildCoreArgs fell through +// to the env value and the core died on a bad --listen. Now the core URL is a +// valid default, so the bad value would be dropped without a trace — and if a +// core is already up on the default the tray silently attaches to it. +func TestUnparseableListenSources(t *testing.T) { + t.Run("valid listens are not reported", func(t *testing.T) { + t.Setenv("MCPPROXY_TRAY_LISTEN", "127.0.0.1:9000") + for _, listen := range []string{"", "8181", "127.0.0.1:8181", ":8181", "0.0.0.0:8181", "[::1]:8181"} { + if got := unparseableListenSources(listen); len(got) != 0 { + t.Fatalf("unparseableListenSources(%q) = %v, expected none", listen, got) + } + } + }) + + t.Run("a host without a port is reported", func(t *testing.T) { + t.Setenv("MCPPROXY_TRAY_LISTEN", "") + got := unparseableListenSources("localhost") + if len(got) != 1 || got[0].name != "--listen" || got[0].value != "localhost" { + t.Fatalf("unparseableListenSources(\"localhost\") = %v, expected one --listen entry", got) + } + }) + + t.Run("both sources are reported independently", func(t *testing.T) { + t.Setenv("MCPPROXY_TRAY_LISTEN", "not a listen addr") + got := unparseableListenSources("127.0.0.1") + if len(got) != 2 { + t.Fatalf("unparseableListenSources = %v, expected 2 entries", got) + } + if got[0].name != "--listen" || got[1].name != "MCPPROXY_TRAY_LISTEN" { + t.Fatalf("unexpected sources: %v", got) + } + }) + + t.Run("whitespace-only values are treated as unset", func(t *testing.T) { + t.Setenv("MCPPROXY_TRAY_LISTEN", " ") + if got := unparseableListenSources(" "); len(got) != 0 { + t.Fatalf("unparseableListenSources with blank values = %v, expected none", got) + } + }) +} + // TestPinnedCoreListen documents which listen sources are treated as a user // contract that must not be silently moved on a port conflict. func TestPinnedCoreListen(t *testing.T) { From f08960220846ab3ff2c2ce77a2eee52727b63f72 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Mon, 24 Aug 2026 21:57:55 +0300 Subject: [PATCH 4/4] fix(tray): make the unparseable-listen warning state what actually happened MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Third cross-model review round. The warning added in the previous commit claimed the value was "ignored" and that the tray fell back to "the default core endpoint". Both can be wrong: with an invalid --listen and a valid MCPPROXY_TRAY_LISTEN, resolution falls through to the env endpoint rather than the default, and the invalid CLI value is still forwarded to the launched core by buildCoreArgs, so it is not ignored either. Reword to the accurate, neutral claim — the value cannot form an endpoint the tray can dial and therefore did not determine the core URL — and keep the resolved core_url field so the log still shows which endpoint won. No behaviour change. --- cmd/mcpproxy-tray/main.go | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/cmd/mcpproxy-tray/main.go b/cmd/mcpproxy-tray/main.go index 4395b3df6..feb123d93 100644 --- a/cmd/mcpproxy-tray/main.go +++ b/cmd/mcpproxy-tray/main.go @@ -135,11 +135,15 @@ func main() { logger.Info("Resolved core URL", zap.String("core_url", coreURL)) // An explicitly configured listen address that cannot be parsed must not - // pass unnoticed. resolveCoreURL falls through to the default endpoint for - // such a value, and if a core is already listening there the tray attaches - // to it — looking as though it honoured an address it actually ignored. + // pass unnoticed: it cannot contribute to the core URL, so resolution falls + // through to the next source (another listen setting, or the default). If a + // core is already listening on whatever that resolves to, the tray attaches + // to it and looks as though it honoured the address. Report the offending + // value and the endpoint that actually won, without claiming which source + // that was or that the value went unused — a bad CLI --listen is still + // forwarded to the core by buildCoreArgs. for _, src := range unparseableListenSources(trayCLIListen) { - logger.Warn("Ignoring unparseable listen address - falling back to the default core endpoint", + logger.Warn("Listen address cannot be parsed into an endpoint the tray can dial - it did not determine the core URL", zap.String("source", src.name), zap.String("value", src.value), zap.String("core_url", coreURL)) @@ -490,9 +494,10 @@ type listenSource struct { // unparseableListenSources reports every explicitly configured listen address // that is set but cannot be turned into an endpoint the tray can dial. Such a -// value is silently dropped by resolveCoreTCPURL's fall-through (and then by -// buildCoreArgs, which derives --listen from the resulting default core URL), -// so callers surface it instead of letting the tray pretend it was honoured. +// value cannot win resolveCoreTCPURL's precedence chain, so resolution falls +// through to the next source and buildCoreArgs then derives --listen from the +// core URL that source produced. Callers surface these values instead of +// letting the tray look as though it honoured an address it could not use. func unparseableListenSources(cliListen string) []listenSource { var bad []listenSource for _, src := range []listenSource{