From e072f091e5f547a9dae1baeb621c26fd570e787d Mon Sep 17 00:00:00 2001 From: Felipe Santos Date: Fri, 20 Nov 2026 15:48:37 -0300 Subject: [PATCH 1/5] fix(tray): make Quit stop the core promptly on Windows Quit from the tray took ~30s on Windows and flashed a console window: - The tray asked the core to stop with `taskkill /T` (no /F). That only sends WM_CLOSE, which the windowless core never receives, so the tray waited out its timeout and force-killed it, skipping the core's cleanup. The core now starts in its own process group and the tray sends it CTRL_BREAK, which Go delivers as SIGINT, so the normal graceful shutdown runs. - taskkill/tasklist were started without CREATE_NO_WINDOW, so each one flashed a console from the GUI tray. - Once the core got the signal, http.Server.Shutdown still waited the full 30s for the long-lived SSE (/events) and MCP streams, which never end on their own. Request contexts are now cancelled 2s after shutdown starts, so ordinary requests get a short grace and the streams return. --- .../internal/monitor/process_windows.go | 52 +++++++++++++++---- .../internal/monitor/process_windows_test.go | 51 ++++++++++++++++++ cmd/mcpproxy-tray/main_windows.go | 12 +++-- internal/server/info_shutdown_e2e_test.go | 15 +++++- internal/server/server.go | 5 ++ 5 files changed, 117 insertions(+), 18 deletions(-) create mode 100644 cmd/mcpproxy-tray/internal/monitor/process_windows_test.go diff --git a/cmd/mcpproxy-tray/internal/monitor/process_windows.go b/cmd/mcpproxy-tray/internal/monitor/process_windows.go index b786b88b6..261639c28 100644 --- a/cmd/mcpproxy-tray/internal/monitor/process_windows.go +++ b/cmd/mcpproxy-tray/internal/monitor/process_windows.go @@ -14,6 +14,7 @@ import ( "time" "go.uber.org/zap" + "golang.org/x/sys/windows" "github.com/smart-mcp-proxy/mcpproxy-go/cmd/mcpproxy-tray/internal/state" ) @@ -142,10 +143,9 @@ func (pm *ProcessMonitor) Start() error { "env_vars", pm.maskSensitiveEnv(pm.config.Env)) } - // Hide console window on Windows - // CREATE_NO_WINDOW = 0x08000000 + // Hide the console window; a process group of its own lets Stop() send it CTRL_BREAK. pm.cmd.SysProcAttr = &syscall.SysProcAttr{ - CreationFlags: 0x08000000, // CREATE_NO_WINDOW + CreationFlags: windows.CREATE_NO_WINDOW | windows.CREATE_NEW_PROCESS_GROUP, } // Set up output capture if enabled @@ -198,9 +198,13 @@ func (pm *ProcessMonitor) Stop() error { pm.logger.Infow("Stopping process", "pid", pid) - // Try graceful stop via taskkill without /F first - killCmd := exec.Command("taskkill", "/PID", fmt.Sprint(pid), "/T") - _ = killCmd.Run() + // Force kill after 45 seconds to allow core time to clean up Docker containers + // (typically 10-30s for 7 containers). + grace := 45 * time.Second + if err := requestGracefulStop(pid); err != nil { + pm.logger.Warnw("Could not ask process to stop gracefully, force killing", "pid", pid, "error", err) + grace = 0 + } // Wait for monitor goroutine to detect exit (via doneCh) // This avoids the cmd.Wait() race condition @@ -218,11 +222,9 @@ func (pm *ProcessMonitor) Stop() error { pm.logger.Infow("Process stopped (no exit info)", "pid", pid) return nil - case <-time.After(45 * time.Second): - // Force kill after 45 seconds to allow core time to clean up Docker containers - // Core needs time for parallel container cleanup (typically 10-30s for 7 containers) - pm.logger.Warn("Process did not stop gracefully after 45s, sending force kill", "pid", pid) - killCmd := exec.Command("taskkill", "/PID", fmt.Sprint(pid), "/T", "/F") + case <-time.After(grace): + pm.logger.Warnw("Process did not stop gracefully, sending force kill", "pid", pid, "grace", grace) + killCmd := HiddenCommand("taskkill", "/PID", fmt.Sprint(pid), "/T", "/F") _ = killCmd.Run() // Wait for monitor to detect the kill @@ -232,6 +234,34 @@ func (pm *ProcessMonitor) Stop() error { } } +var ( + kernel32 = windows.NewLazySystemDLL("kernel32.dll") + procAttachConsole = kernel32.NewProc("AttachConsole") + procFreeConsole = kernel32.NewProc("FreeConsole") + consoleMu sync.Mutex // the console a process is attached to is process-wide +) + +// requestGracefulStop sends CTRL_BREAK to the process group led by pid; Go turns it into +// SIGINT, so the core runs its normal graceful shutdown. taskkill without /F cannot do this: +// it only sends WM_CLOSE, which a windowless console process never receives. +func requestGracefulStop(pid int) error { + consoleMu.Lock() + defer consoleMu.Unlock() + _, _, _ = procFreeConsole.Call() // a tray started from a terminal must leave it to attach + if r, _, err := procAttachConsole.Call(uintptr(pid)); r == 0 { + return fmt.Errorf("attach to console of pid %d: %w", pid, err) + } + defer procFreeConsole.Call() + return windows.GenerateConsoleCtrlEvent(windows.CTRL_BREAK_EVENT, uint32(pid)) +} + +// HiddenCommand is exec.Command without the console window a GUI process would otherwise flash. +func HiddenCommand(name string, args ...string) *exec.Cmd { + cmd := exec.Command(name, args...) + cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: windows.CREATE_NO_WINDOW} + return cmd +} + // setupOutputCapture sets up stdout/stderr capture (Windows shares POSIX impl) func (pm *ProcessMonitor) setupOutputCapture() error { stdoutPipe, err := pm.cmd.StdoutPipe() diff --git a/cmd/mcpproxy-tray/internal/monitor/process_windows_test.go b/cmd/mcpproxy-tray/internal/monitor/process_windows_test.go new file mode 100644 index 000000000..3003c5be4 --- /dev/null +++ b/cmd/mcpproxy-tray/internal/monitor/process_windows_test.go @@ -0,0 +1,51 @@ +//go:build windows + +package monitor + +import ( + "os" + "os/signal" + "testing" + "time" + + "go.uber.org/zap" +) + +// TestHelperWaitForInterrupt is the child process: it exits cleanly only on SIGINT. +func TestHelperWaitForInterrupt(t *testing.T) { + if os.Getenv("MONITOR_HELPER") != "1" { + t.Skip("helper process") + } + ch := make(chan os.Signal, 1) + signal.Notify(ch, os.Interrupt) + select { + case <-ch: + os.Exit(0) + case <-time.After(time.Minute): + os.Exit(7) + } +} + +// Stop must reach a windowless child gracefully instead of waiting out the force-kill timeout. +func TestStopIsGracefulForWindowlessProcess(t *testing.T) { + pm := NewProcessMonitor(&ProcessConfig{ + Binary: os.Args[0], + Args: []string{"-test.run=^TestHelperWaitForInterrupt$"}, + Env: append(os.Environ(), "MONITOR_HELPER=1"), + }, zap.NewNop().Sugar(), nil) + if err := pm.Start(); err != nil { + t.Fatal(err) + } + time.Sleep(time.Second) // let the child install its signal handler + + started := time.Now() + if err := pm.Stop(); err != nil { + t.Fatalf("Stop() = %v, want graceful exit", err) + } + if d := time.Since(started); d > 10*time.Second { + t.Fatalf("Stop() took %s", d) + } + if code := pm.GetExitInfo().Code; code != 0 { + t.Fatalf("exit code %d, want 0", code) + } +} diff --git a/cmd/mcpproxy-tray/main_windows.go b/cmd/mcpproxy-tray/main_windows.go index 4d8429bc7..ae38b1cf0 100644 --- a/cmd/mcpproxy-tray/main_windows.go +++ b/cmd/mcpproxy-tray/main_windows.go @@ -9,6 +9,8 @@ import ( "time" "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/cmd/mcpproxy-tray/internal/monitor" ) // Windows doesn't have POSIX signals, so we create dummy constants for compatibility @@ -28,7 +30,7 @@ func (cpl *CoreProcessLauncher) forceKillCore() { cpl.logger.Warn("Force killing core process", zap.Int("pid", pid)) // Kill the entire process tree using taskkill /T /F - killCmd := exec.Command("taskkill", "/PID", fmt.Sprint(pid), "/T", "/F") + killCmd := monitor.HiddenCommand("taskkill", "/PID", fmt.Sprint(pid), "/T", "/F") if err := killCmd.Run(); err != nil { cpl.logger.Error("Failed to force kill process", zap.Int("pid", pid), zap.Error(err)) } @@ -46,10 +48,10 @@ func (cpl *CoreProcessLauncher) signalProcessTree(pid int, sig syscall.Signal) e // Map Unix signals to Windows taskkill behavior if sig == _SIGKILL { // Force kill - killCmd = exec.Command("taskkill", "/PID", fmt.Sprint(pid), "/T", "/F") + killCmd = monitor.HiddenCommand("taskkill", "/PID", fmt.Sprint(pid), "/T", "/F") } else { // Graceful shutdown (SIGTERM equivalent) - killCmd = exec.Command("taskkill", "/PID", fmt.Sprint(pid), "/T") + killCmd = monitor.HiddenCommand("taskkill", "/PID", fmt.Sprint(pid), "/T") } if err := killCmd.Run(); err != nil { @@ -68,7 +70,7 @@ func (cpl *CoreProcessLauncher) waitForProcessExit(pid int, timeout time.Duratio deadline := time.Now().Add(timeout) for time.Now().Before(deadline) { // Check if process exists using tasklist - checkCmd := exec.Command("tasklist", "/FI", fmt.Sprintf("PID eq %d", pid), "/FO", "CSV", "/NH") + checkCmd := monitor.HiddenCommand("tasklist", "/FI", fmt.Sprintf("PID eq %d", pid), "/FO", "CSV", "/NH") output, err := checkCmd.Output() if err != nil || len(output) == 0 { return true // Process doesn't exist @@ -89,7 +91,7 @@ func (cpl *CoreProcessLauncher) isProcessAlive(pid int) bool { return false } - checkCmd := exec.Command("tasklist", "/FI", fmt.Sprintf("PID eq %d", pid), "/FO", "CSV", "/NH") + checkCmd := monitor.HiddenCommand("tasklist", "/FI", fmt.Sprintf("PID eq %d", pid), "/FO", "CSV", "/NH") output, err := checkCmd.Output() if err != nil || len(output) == 0 { return false diff --git a/internal/server/info_shutdown_e2e_test.go b/internal/server/info_shutdown_e2e_test.go index 2ae8ce26a..0c4fe8400 100644 --- a/internal/server/info_shutdown_e2e_test.go +++ b/internal/server/info_shutdown_e2e_test.go @@ -211,6 +211,17 @@ func TestGracefulShutdownNoPanic(t *testing.T) { time.Sleep(100 * time.Millisecond) } + // Hold an SSE stream open, like the Web UI or an MCP client does: it must not + // make the HTTP shutdown wait out its 30s timeout. + streamReq, err := http.NewRequest("GET", serverURL+"/events", nil) + require.NoError(t, err) + streamReq.Header.Set("X-API-Key", "e2e-test-api-key-12345") + streamResp, err := http.DefaultClient.Do(streamReq) + require.NoError(t, err) + defer streamResp.Body.Close() + require.Equal(t, http.StatusOK, streamResp.StatusCode) + go func() { _, _ = io.Copy(io.Discard, streamResp.Body) }() + // Send SIGINT (Ctrl+C) to the process t.Log("Sending SIGINT to server process...") require.NoError(t, cmd.Process.Signal(syscall.SIGINT)) @@ -236,8 +247,8 @@ func TestGracefulShutdownNoPanic(t *testing.T) { t.Log("No stderr output captured") } - case <-time.After(15 * time.Second): - t.Fatal("Server did not shut down within 15 seconds") + case <-time.After(10 * time.Second): + t.Fatal("Server did not shut down within 10 seconds") cmd.Process.Kill() } } diff --git a/internal/server/server.go b/internal/server/server.go index 85c6d2d0b..a4ffd8b16 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -3795,6 +3795,7 @@ func (s *Server) startCustomHTTPServer(ctx context.Context, streamableServer *se // /events) clear it per-request via streamingNoDeadline so slow tool calls // and SSE streams survive without weakening the rest of the surface. readTimeout, writeTimeout, idleTimeout := httpServerTimeouts(cfg) + requestsCtx, cancelRequests := context.WithCancel(context.Background()) s.mu.Lock() s.httpServer = &http.Server{ @@ -3809,7 +3810,11 @@ func (s *Server) startCustomHTTPServer(ctx context.Context, streamableServer *se ConnState: s.logConnectionState, // Tag connections with their source (TCP vs Tray) ConnContext: taggedConnContext, + BaseContext: func(net.Listener) context.Context { return requestsCtx }, } + // Shutdown waits for every active request, and the SSE / MCP streams never end on their + // own: after a short grace for ordinary requests, cancel their context so they return. + s.httpServer.RegisterOnShutdown(func() { time.AfterFunc(2*time.Second, cancelRequests) }) s.running = true s.runtime.SetRunning(true) s.listenAddr = displayAddr From 8bd7b4d47efda190a47170bf44d77013cce8b29c Mon Sep 17 00:00:00 2001 From: Felipe Santos Date: Fri, 20 Nov 2026 16:47:01 -0300 Subject: [PATCH 2/5] test(tray): wait for the helper's signal handler instead of sleeping The Windows stop test slept 1s before sending CTRL_BREAK; a slow runner could deliver it before the child's handler was installed, killing the child outright. The helper now prints "ready" after signal.Notify and the test waits for it. Also drop the TestGracefulShutdownNoPanic stream change: every CI job skips that test, so it added no coverage. --- .../internal/monitor/process_windows_test.go | 20 +++++++++++++++---- internal/server/info_shutdown_e2e_test.go | 15 ++------------ 2 files changed, 18 insertions(+), 17 deletions(-) diff --git a/cmd/mcpproxy-tray/internal/monitor/process_windows_test.go b/cmd/mcpproxy-tray/internal/monitor/process_windows_test.go index 3003c5be4..56c199697 100644 --- a/cmd/mcpproxy-tray/internal/monitor/process_windows_test.go +++ b/cmd/mcpproxy-tray/internal/monitor/process_windows_test.go @@ -3,8 +3,10 @@ package monitor import ( + "fmt" "os" "os/signal" + "strings" "testing" "time" @@ -18,6 +20,7 @@ func TestHelperWaitForInterrupt(t *testing.T) { } ch := make(chan os.Signal, 1) signal.Notify(ch, os.Interrupt) + fmt.Println("ready") select { case <-ch: os.Exit(0) @@ -29,14 +32,23 @@ func TestHelperWaitForInterrupt(t *testing.T) { // Stop must reach a windowless child gracefully instead of waiting out the force-kill timeout. func TestStopIsGracefulForWindowlessProcess(t *testing.T) { pm := NewProcessMonitor(&ProcessConfig{ - Binary: os.Args[0], - Args: []string{"-test.run=^TestHelperWaitForInterrupt$"}, - Env: append(os.Environ(), "MONITOR_HELPER=1"), + Binary: os.Args[0], + Args: []string{"-test.run=^TestHelperWaitForInterrupt$"}, + Env: append(os.Environ(), "MONITOR_HELPER=1"), + CaptureOutput: true, }, zap.NewNop().Sugar(), nil) if err := pm.Start(); err != nil { t.Fatal(err) } - time.Sleep(time.Second) // let the child install its signal handler + // A CTRL_BREAK that lands before the child's handler kills it outright. + for deadline := time.Now().Add(30 * time.Second); ; time.Sleep(50 * time.Millisecond) { + if out, _ := pm.GetOutput(); strings.Contains(out, "ready") { + break + } + if time.Now().After(deadline) { + t.Fatal("child never reported ready") + } + } started := time.Now() if err := pm.Stop(); err != nil { diff --git a/internal/server/info_shutdown_e2e_test.go b/internal/server/info_shutdown_e2e_test.go index 0c4fe8400..2ae8ce26a 100644 --- a/internal/server/info_shutdown_e2e_test.go +++ b/internal/server/info_shutdown_e2e_test.go @@ -211,17 +211,6 @@ func TestGracefulShutdownNoPanic(t *testing.T) { time.Sleep(100 * time.Millisecond) } - // Hold an SSE stream open, like the Web UI or an MCP client does: it must not - // make the HTTP shutdown wait out its 30s timeout. - streamReq, err := http.NewRequest("GET", serverURL+"/events", nil) - require.NoError(t, err) - streamReq.Header.Set("X-API-Key", "e2e-test-api-key-12345") - streamResp, err := http.DefaultClient.Do(streamReq) - require.NoError(t, err) - defer streamResp.Body.Close() - require.Equal(t, http.StatusOK, streamResp.StatusCode) - go func() { _, _ = io.Copy(io.Discard, streamResp.Body) }() - // Send SIGINT (Ctrl+C) to the process t.Log("Sending SIGINT to server process...") require.NoError(t, cmd.Process.Signal(syscall.SIGINT)) @@ -247,8 +236,8 @@ func TestGracefulShutdownNoPanic(t *testing.T) { t.Log("No stderr output captured") } - case <-time.After(10 * time.Second): - t.Fatal("Server did not shut down within 10 seconds") + case <-time.After(15 * time.Second): + t.Fatal("Server did not shut down within 15 seconds") cmd.Process.Kill() } } From c1301dde7c689f094489ee2630cb08fb6c3be7aa Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Tue, 24 Nov 2026 13:26:20 +0200 Subject: [PATCH 3/5] fix(tray): never force-kill a core that already exited on Windows Stop() with no graceful signal possible uses grace 0, so time.After(0) and a closed doneCh were both ready and select picked at random: an already-exited child could be taskkill /T /F'd and reported as force killed. Check doneCh first, and again when the grace timer fires. Co-Authored-By: Claude Sonnet 5.5 --- .../internal/monitor/process_windows.go | 229 ++++++++++-------- .../internal/monitor/process_windows_test.go | 26 ++ 2 files changed, 151 insertions(+), 104 deletions(-) diff --git a/cmd/mcpproxy-tray/internal/monitor/process_windows.go b/cmd/mcpproxy-tray/internal/monitor/process_windows.go index 261639c28..89a3ddd67 100644 --- a/cmd/mcpproxy-tray/internal/monitor/process_windows.go +++ b/cmd/mcpproxy-tray/internal/monitor/process_windows.go @@ -25,74 +25,74 @@ import ( type ProcessStatus string const ( - ProcessStatusStopped ProcessStatus = "stopped" - ProcessStatusStarting ProcessStatus = "starting" - ProcessStatusRunning ProcessStatus = "running" - ProcessStatusFailed ProcessStatus = "failed" - ProcessStatusCrashed ProcessStatus = "crashed" + ProcessStatusStopped ProcessStatus = "stopped" + ProcessStatusStarting ProcessStatus = "starting" + ProcessStatusRunning ProcessStatus = "running" + ProcessStatusFailed ProcessStatus = "failed" + ProcessStatusCrashed ProcessStatus = "crashed" ) // ProcessEvent represents events from the process monitor type ProcessEvent struct { - Type ProcessEventType - Data map[string]interface{} - Error error - Timestamp time.Time + Type ProcessEventType + Data map[string]interface{} + Error error + Timestamp time.Time } type ProcessEventType string const ( - ProcessEventStarted ProcessEventType = "started" - ProcessEventExited ProcessEventType = "exited" - ProcessEventError ProcessEventType = "error" - ProcessEventOutput ProcessEventType = "output" + ProcessEventStarted ProcessEventType = "started" + ProcessEventExited ProcessEventType = "exited" + ProcessEventError ProcessEventType = "error" + ProcessEventOutput ProcessEventType = "output" ) // ExitInfo contains information about process exit type ExitInfo struct { - Code int - Signal string - Timestamp time.Time - Error error + Code int + Signal string + Timestamp time.Time + Error error } // ProcessConfig contains configuration for process monitoring type ProcessConfig struct { - Binary string - Args []string - Env []string - WorkingDir string - StartTimeout time.Duration - CaptureOutput bool + Binary string + Args []string + Env []string + WorkingDir string + StartTimeout time.Duration + CaptureOutput bool } // ProcessMonitor monitors a subprocess and reports its status (Windows) type ProcessMonitor struct { - config ProcessConfig - logger *zap.SugaredLogger - stateMachine *state.Machine - - mu sync.RWMutex - cmd *exec.Cmd - status ProcessStatus - pid int - exitInfo *ExitInfo - startTime time.Time - - // Channels - eventCh chan ProcessEvent - shutdownCh chan struct{} - doneCh chan struct{} // Closed when monitor() exits - - // Output capture - stdoutBuf strings.Builder - stderrBuf strings.Builder - outputMu sync.Mutex - - // Context for cancellation - ctx context.Context - cancel context.CancelFunc + config ProcessConfig + logger *zap.SugaredLogger + stateMachine *state.Machine + + mu sync.RWMutex + cmd *exec.Cmd + status ProcessStatus + pid int + exitInfo *ExitInfo + startTime time.Time + + // Channels + eventCh chan ProcessEvent + shutdownCh chan struct{} + doneCh chan struct{} // Closed when monitor() exits + + // Output capture + stdoutBuf strings.Builder + stderrBuf strings.Builder + outputMu sync.Mutex + + // Context for cancellation + ctx context.Context + cancel context.CancelFunc } // NewProcessMonitor creates a new process monitor (Windows) @@ -208,8 +208,7 @@ func (pm *ProcessMonitor) Stop() error { // Wait for monitor goroutine to detect exit (via doneCh) // This avoids the cmd.Wait() race condition - select { - case <-pm.doneCh: + exited := func() error { // Monitor has detected process exit pm.mu.RLock() exitInfo := pm.exitInfo @@ -221,8 +220,27 @@ func (pm *ProcessMonitor) Stop() error { } pm.logger.Infow("Process stopped (no exit info)", "pid", pid) return nil + } + + // select picks at random when both cases are ready, and with grace == 0 the timer is ready + // at once: look at doneCh first so an already-exited child is never force-killed (its PID + // may even have been reused). + select { + case <-pm.doneCh: + return exited() + default: + } + + select { + case <-pm.doneCh: + return exited() case <-time.After(grace): + select { + case <-pm.doneCh: // exited just as the timer fired + return exited() + default: + } pm.logger.Warnw("Process did not stop gracefully, sending force kill", "pid", pid, "grace", grace) killCmd := HiddenCommand("taskkill", "/PID", fmt.Sprint(pid), "/T", "/F") _ = killCmd.Run() @@ -265,9 +283,14 @@ func HiddenCommand(name string, args ...string) *exec.Cmd { // setupOutputCapture sets up stdout/stderr capture (Windows shares POSIX impl) func (pm *ProcessMonitor) setupOutputCapture() error { stdoutPipe, err := pm.cmd.StdoutPipe() - if err != nil { return fmt.Errorf("failed to create stdout pipe: %w", err) } + if err != nil { + return fmt.Errorf("failed to create stdout pipe: %w", err) + } stderrPipe, err := pm.cmd.StderrPipe() - if err != nil { stdoutPipe.Close(); return fmt.Errorf("failed to create stderr pipe: %w", err) } + if err != nil { + stdoutPipe.Close() + return fmt.Errorf("failed to create stderr pipe: %w", err) + } go pm.captureOutput(stdoutPipe, &pm.stdoutBuf, "stdout") go pm.captureOutput(stderrPipe, &pm.stderrBuf, "stderr") return nil @@ -379,85 +402,83 @@ func (pm *ProcessMonitor) Shutdown() { // GetStatus returns the current process status (Windows) func (pm *ProcessMonitor) GetStatus() ProcessStatus { - pm.mu.RLock() - defer pm.mu.RUnlock() - return pm.status + pm.mu.RLock() + defer pm.mu.RUnlock() + return pm.status } // sendEvent sends an event to the channel (Windows) func (pm *ProcessMonitor) sendEvent(event ProcessEvent) { - select { - case pm.eventCh <- event: - default: - pm.logger.Warn("Process event channel full, dropping event", "event_type", event.Type) - } + select { + case pm.eventCh <- event: + default: + pm.logger.Warn("Process event channel full, dropping event", "event_type", event.Type) + } } // maskSensitiveArgs masks sensitive data in command arguments (Windows) func (pm *ProcessMonitor) maskSensitiveArgs(args []string) []string { - masked := make([]string, len(args)) - copy(masked, args) - for i, arg := range masked { - low := strings.ToLower(arg) - if strings.Contains(low, "key") || strings.Contains(low, "secret") || strings.Contains(low, "token") || strings.Contains(low, "password") { - if len(arg) > 8 { - masked[i] = arg[:4] + "****" + arg[len(arg)-4:] - } else { - masked[i] = "****" - } - } - } - return masked + masked := make([]string, len(args)) + copy(masked, args) + for i, arg := range masked { + low := strings.ToLower(arg) + if strings.Contains(low, "key") || strings.Contains(low, "secret") || strings.Contains(low, "token") || strings.Contains(low, "password") { + if len(arg) > 8 { + masked[i] = arg[:4] + "****" + arg[len(arg)-4:] + } else { + masked[i] = "****" + } + } + } + return masked } // maskSensitiveEnv masks sensitive data in environment variables (Windows) func (pm *ProcessMonitor) maskSensitiveEnv(env []string) []string { - masked := make([]string, len(env)) - for i, envVar := range env { - parts := strings.SplitN(envVar, "=", 2) - if len(parts) != 2 { - masked[i] = envVar - continue - } - keyLower := strings.ToLower(parts[0]) - value := parts[1] - if strings.Contains(keyLower, "key") || strings.Contains(keyLower, "secret") || strings.Contains(keyLower, "token") || strings.Contains(keyLower, "password") { - if len(value) > 8 { - masked[i] = parts[0] + "=" + value[:4] + "****" + value[len(value)-4:] - } else { - masked[i] = parts[0] + "=****" - } - } else { - masked[i] = envVar - } - } - return masked + masked := make([]string, len(env)) + for i, envVar := range env { + parts := strings.SplitN(envVar, "=", 2) + if len(parts) != 2 { + masked[i] = envVar + continue + } + keyLower := strings.ToLower(parts[0]) + value := parts[1] + if strings.Contains(keyLower, "key") || strings.Contains(keyLower, "secret") || strings.Contains(keyLower, "token") || strings.Contains(keyLower, "password") { + if len(value) > 8 { + masked[i] = parts[0] + "=" + value[:4] + "****" + value[len(value)-4:] + } else { + masked[i] = parts[0] + "=****" + } + } else { + masked[i] = envVar + } + } + return masked } - - // GetPID returns the process ID (Windows) func (pm *ProcessMonitor) GetPID() int { - pm.mu.RLock() - defer pm.mu.RUnlock() - return pm.pid + pm.mu.RLock() + defer pm.mu.RUnlock() + return pm.pid } // GetExitInfo returns information about process exit (Windows) func (pm *ProcessMonitor) GetExitInfo() *ExitInfo { - pm.mu.RLock() - defer pm.mu.RUnlock() - return pm.exitInfo + pm.mu.RLock() + defer pm.mu.RUnlock() + return pm.exitInfo } // GetOutput returns captured stdout and stderr (Windows) func (pm *ProcessMonitor) GetOutput() (stdout, stderr string) { - pm.outputMu.Lock() - defer pm.outputMu.Unlock() - return pm.stdoutBuf.String(), pm.stderrBuf.String() + pm.outputMu.Lock() + defer pm.outputMu.Unlock() + return pm.stdoutBuf.String(), pm.stderrBuf.String() } // EventChannel returns a channel for receiving process events (Windows) func (pm *ProcessMonitor) EventChannel() <-chan ProcessEvent { - return pm.eventCh + return pm.eventCh } diff --git a/cmd/mcpproxy-tray/internal/monitor/process_windows_test.go b/cmd/mcpproxy-tray/internal/monitor/process_windows_test.go index 56c199697..53a93216f 100644 --- a/cmd/mcpproxy-tray/internal/monitor/process_windows_test.go +++ b/cmd/mcpproxy-tray/internal/monitor/process_windows_test.go @@ -15,6 +15,9 @@ import ( // TestHelperWaitForInterrupt is the child process: it exits cleanly only on SIGINT. func TestHelperWaitForInterrupt(t *testing.T) { + if os.Getenv("MONITOR_HELPER") == "exit" { + os.Exit(0) + } if os.Getenv("MONITOR_HELPER") != "1" { t.Skip("helper process") } @@ -61,3 +64,26 @@ func TestStopIsGracefulForWindowlessProcess(t *testing.T) { t.Fatalf("exit code %d, want 0", code) } } + +// Stop on a child that has already exited must report that exit, never force-kill: with no +// graceful signal possible the grace is 0, and a random select used to pick the force-kill. +func TestStopDoesNotForceKillExitedProcess(t *testing.T) { + for i := 0; i < 20; i++ { + pm := NewProcessMonitor(&ProcessConfig{ + Binary: os.Args[0], + Args: []string{"-test.run=^TestHelperWaitForInterrupt$"}, + Env: append(os.Environ(), "MONITOR_HELPER=exit"), + }, zap.NewNop().Sugar(), nil) + if err := pm.Start(); err != nil { + t.Fatal(err) + } + select { + case <-pm.doneCh: + case <-time.After(30 * time.Second): + t.Fatal("child never exited") + } + if err := pm.Stop(); err != nil && strings.Contains(err.Error(), "force killed") { + t.Fatalf("iteration %d: exited child was force-killed: %v", i, err) + } + } +} From 50e784506eebe440b48eeeddf568fce57b7ca452 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Tue, 24 Nov 2026 14:57:05 +0200 Subject: [PATCH 4/5] fix(server): give in-flight requests 5s before shutdown cancels them Raise the post-Shutdown request-context grace from 2s to 5s so short tool calls can finish, name it requestShutdownGrace, and document that tool calls on the request context are cancelled after it on every OS. Co-Authored-By: Claude Sonnet 5.5 --- internal/server/server.go | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/internal/server/server.go b/internal/server/server.go index e34558827..510ac56d0 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -3261,6 +3261,10 @@ func (s *Server) extendedDeadline(d time.Duration, next http.Handler) http.Handl }) } +// requestShutdownGrace is how long http.Server.Shutdown lets in-flight requests finish before +// their context is cancelled. +const requestShutdownGrace = 5 * time.Second + // httpServerTimeouts resolves the Read/Write/Idle deadlines applied to the // main http.Server (GH #965). Extracted as a pure function so the policy is // unit-testable without binding a socket. A nil config yields the built-in @@ -3823,7 +3827,10 @@ func (s *Server) startCustomHTTPServer(ctx context.Context, streamableServer *se } // Shutdown waits for every active request, and the SSE / MCP streams never end on their // own: after a short grace for ordinary requests, cancel their context so they return. - s.httpServer.RegisterOnShutdown(func() { time.AfterFunc(2*time.Second, cancelRequests) }) + // This applies on every OS. Tool calls run on the request context, so an in-flight tool + // call still running when the grace expires is cancelled too (Docker cleanup in + // runtime.Close is not on this context and still runs afterwards). + s.httpServer.RegisterOnShutdown(func() { time.AfterFunc(requestShutdownGrace, cancelRequests) }) s.running = true s.runtime.SetRunning(true) s.listenAddr = displayAddr From 911ac67e045125caefec5e3d85b5725e535f5867 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Tue, 24 Nov 2026 14:57:41 +0200 Subject: [PATCH 5/5] test(tray): require a clean stop for an exited core; correct the Stop comment Co-Authored-By: Claude Sonnet 5.5 --- cmd/mcpproxy-tray/internal/monitor/process_windows.go | 5 +++-- cmd/mcpproxy-tray/internal/monitor/process_windows_test.go | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/cmd/mcpproxy-tray/internal/monitor/process_windows.go b/cmd/mcpproxy-tray/internal/monitor/process_windows.go index 89a3ddd67..f1e1a6502 100644 --- a/cmd/mcpproxy-tray/internal/monitor/process_windows.go +++ b/cmd/mcpproxy-tray/internal/monitor/process_windows.go @@ -223,8 +223,9 @@ func (pm *ProcessMonitor) Stop() error { } // select picks at random when both cases are ready, and with grace == 0 the timer is ready - // at once: look at doneCh first so an already-exited child is never force-killed (its PID - // may even have been reused). + // at once: look at doneCh first so a child the monitor has already seen exit is not + // force-killed. A child that exits in the instant before the monitor closes doneCh can + // still get a harmless taskkill (the tray holds its process handle until Wait returns). select { case <-pm.doneCh: return exited() diff --git a/cmd/mcpproxy-tray/internal/monitor/process_windows_test.go b/cmd/mcpproxy-tray/internal/monitor/process_windows_test.go index 53a93216f..f9497f480 100644 --- a/cmd/mcpproxy-tray/internal/monitor/process_windows_test.go +++ b/cmd/mcpproxy-tray/internal/monitor/process_windows_test.go @@ -82,8 +82,8 @@ func TestStopDoesNotForceKillExitedProcess(t *testing.T) { case <-time.After(30 * time.Second): t.Fatal("child never exited") } - if err := pm.Stop(); err != nil && strings.Contains(err.Error(), "force killed") { - t.Fatalf("iteration %d: exited child was force-killed: %v", i, err) + if err := pm.Stop(); err != nil { + t.Fatalf("iteration %d: Stop() on an exited child = %v, want its clean exit", i, err) } } }