Skip to content
Closed
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
9 changes: 9 additions & 0 deletions internal/shellwrap/cmdline_other.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
//go:build !windows

package shellwrap

import "os/exec"

// ApplyCommandLine is a no-op outside Windows: Unix shells get the command
// string as an ordinary argv element, which is exactly what they expect.
func ApplyCommandLine(*exec.Cmd) {}
92 changes: 92 additions & 0 deletions internal/shellwrap/cmdline_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package shellwrap

import (
"os/exec"
"strings"
"testing"

"github.com/stretchr/testify/require"
)

// TestIsCmdExeShell pins the shell detection used by ApplyCommandLine: the
// wrapped command string only needs the explicit command line when the shell
// that will parse it is cmd.exe itself.
func TestIsCmdExeShell(t *testing.T) {
for _, shell := range []string{"cmd", "cmd.exe", "CMD.EXE", "C:\\Windows\\system32\\cmd.exe"} {
require.True(t, isCmdExeShell(shell), shell)
}
for _, shell := range []string{"/bin/bash", "bash", "sh", "powershell.exe", "pwsh", "/bin/zsh"} {
require.False(t, isCmdExeShell(shell), shell)
}
}

// TestCmdExeCommandLineRecoversTheQuotedCommand is the cross-platform half of
// the #1960 fix. cmd.exe /S strips exactly one leading and one trailing quote
// from the text after /c; everything the shell escaping put inside has to come
// out of that strip unchanged, including the quotes around a program path with
// spaces.
func TestCmdExeCommandLineRecoversTheQuotedCommand(t *testing.T) {
cases := []struct{ name, shell, commandString string }{
{
name: "program path with spaces",
shell: "C:\\Windows\\system32\\cmd.exe",
commandString: "\"C:\\Program Files\\HTTP Toolkit\\httptoolkit-mcp.cmd\" --stdio",
},
{
name: "bare command",
shell: "cmd",
commandString: "npx -y @modelcontextprotocol/server-everything",
},
{
// ComSpec can point anywhere; a path with a space cannot be
// prefixed at all, so the line has to be valid without it.
name: "shell path with spaces",
shell: "C:\\My Tools\\cmd.exe",
commandString: "\"C:\\Program Files\\thing.cmd\"",
},
}

for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
line := cmdExeCommandLine(tc.shell, tc.commandString)
require.True(t, strings.HasSuffix(line, "\""), "line must end with the closing quote: %q", line)

// cmd.exe /S: drop the first and last quote after /c, then hand the
// rest to its parser. That rest must be the command string
// WrapWithUserShell built, byte for byte.
at := strings.Index(line, "/s /c ")
require.GreaterOrEqual(t, at, 0, line)
after := line[at+len("/s /c "):]
require.True(t, strings.HasPrefix(after, "\""), after)
require.Equal(t, tc.commandString, after[1:len(after)-1])
})
}
}

// TestApplyCommandLineLeavesOtherShellsAlone guards the no-op cases: Unix
// shells and Git Bash keep the command string as an ordinary argv element,
// and a direct-exec launcher command (docker) has no /c to rewrite.
func TestApplyCommandLineLeavesOtherShellsAlone(t *testing.T) {
cmd := exec.Command("/bin/bash", "-l", "-c", "echo hi")
ApplyCommandLine(cmd)
require.Nil(t, cmd.SysProcAttr, "a POSIX shell keeps the argv form untouched")

cmd = exec.Command("docker", "run", "--rm", "image")
ApplyCommandLine(cmd)
require.Nil(t, cmd.SysProcAttr, "a direct-exec launcher command keeps the argv form untouched")
}

// TestWrapWithUserShellShapeIsWhatApplyCommandLineRewrites guards the coupling
// between the two functions: ApplyCommandLine only rewrites argv shaped
// [cmd.exe, "/c", commandString], so a change to the wrapping shape silently
// restores the broken argv launch on Windows. stubWindows forces the Windows
// branch on any host.
func TestWrapWithUserShellShapeIsWhatApplyCommandLineRewrites(t *testing.T) {
stubWindows(t, "cmd.exe")

shell, args := WrapWithUserShell(nil, "C:\\Program Files\\HTTP Toolkit\\httptoolkit-mcp.cmd", []string{"--stdio"})
require.Equal(t, "cmd.exe", shell)
require.Len(t, args, 2, "cmd.exe wrap must stay [/c, commandString]")
require.Equal(t, "/c", args[0])
require.Equal(t, "\"C:\\Program Files\\HTTP Toolkit\\httptoolkit-mcp.cmd\" --stdio", args[1])
}
35 changes: 35 additions & 0 deletions internal/shellwrap/cmdline_windows.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
//go:build windows

package shellwrap

import (
"os/exec"
"syscall"
)

// ApplyCommandLine hands a shell-wrapped command to cmd.exe through
// SysProcAttr.CmdLine instead of letting os/exec build the command line from
// argv.
//
// Only cmd.exe needs this. A command string produced by WrapWithUserShell is
// already quoted for cmd.exe, and Go escapes an embedded quote as \", which
// cmd.exe reads literally — so a program path containing a space (anything
// under "Program Files", HTTP Toolkit, a user folder with a space) was looked
// up under a name that began with a backslash-quote and never started (#1960).
// CreateProcess uses CmdLine verbatim, so the quoting WrapWithUserShell did
// survives.
//
// Git Bash and PowerShell on Windows keep the argv path: their command string
// uses POSIX quoting, which Go's argv escaping does not damage.
func ApplyCommandLine(cmd *exec.Cmd) {
if cmd == nil || len(cmd.Args) != 3 || cmd.Args[1] != "/c" {
return
}
if !isCmdExeShell(cmd.Args[0]) {
return
}
if cmd.SysProcAttr == nil {
cmd.SysProcAttr = &syscall.SysProcAttr{}
}
cmd.SysProcAttr.CmdLine = cmdExeCommandLine(cmd.Args[0], cmd.Args[2])
}
37 changes: 37 additions & 0 deletions internal/shellwrap/cmdline_windows_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
//go:build windows

package shellwrap

import (
"os"
"os/exec"
"path/filepath"
"testing"

"github.com/stretchr/testify/require"
)

// TestApplyCommandLineRunsAProgramUnderAPathWithSpaces is #1960 end to end: a
// stdio server installed under "Program Files" has to start. Without the
// explicit command line, os/exec escapes the quotes WrapWithUserShell put
// around the path as \", cmd.exe has no backslash escape, and the child dies
// with '"C:\...\httptoolkit-mcp.cmd" is not recognized'.
func TestApplyCommandLineRunsAProgramUnderAPathWithSpaces(t *testing.T) {
shell, shellArgs := WrapWithUserShell(nil, "cmd.exe", nil)
if !isCmdExeShell(shell) || len(shellArgs) == 0 || shellArgs[0] != "/c" {
t.Skipf("the user shell here is %q, not cmd.exe", shell)
}

dir := filepath.Join(t.TempDir(), "Program Files", "HTTP Toolkit")
require.NoError(t, os.MkdirAll(dir, 0o755))
script := filepath.Join(dir, "httptoolkit-mcp.cmd")
require.NoError(t, os.WriteFile(script, []byte("@echo off\r\necho STARTED %1\r\n"), 0o644))

shell, shellArgs = WrapWithUserShell(nil, script, []string{"--stdio"})
cmd := exec.Command(shell, shellArgs...)
ApplyCommandLine(cmd)

out, err := cmd.CombinedOutput()
require.NoErrorf(t, err, "cmd.exe could not start %q: %s", script, out)
require.Contains(t, string(out), "STARTED --stdio")
}
36 changes: 36 additions & 0 deletions internal/shellwrap/shellwrap.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,42 @@ func isBashLikeShell(shell string) bool {
return strings.Contains(lower, "bash") || strings.Contains(lower, "sh")
}

// isCmdExeShell reports whether shell is the Windows command interpreter
// (cmd.exe) rather than a POSIX shell or Git Bash.
//
// It is deliberately independent of goos: callers know from WrapWithUserShell
// which dialect the command string was built for, and a test on any host can
// name a cmd.exe path without pretending to be Windows.
func isCmdExeShell(shell string) bool {
if i := strings.LastIndexAny(shell, "\\/"); i >= 0 {
shell = shell[i+1:]
}
return strings.TrimSuffix(strings.ToLower(shell), ".exe") == "cmd"
}

// cmdExeCommandLine builds the lpCommandLine that hands commandString to
// cmd.exe untouched.
//
// cmd.exe's /S rule is "strip the first and last quote of the string after
// /c, then interpret what is left", so the string is wrapped in one extra
// pair of quotes: the shell-quoted command inside survives intact, whether or
// not it starts with its own quote. This is the part os/exec cannot do for
// us: passing the same string as one argv element makes Go escape every
// embedded quote as \", and cmd.exe has no backslash escape, so it looks for
// a program whose name starts with a backslash-quote (#1960).
//
// shell is prefixed only when it is a bare name or an unquoted path. A path
// that itself needs quoting cannot be prefixed at all — cmd.exe would strip
// the pair around the whole line — and does not need to be: os/exec passes
// the executable separately as lpApplicationName.
func cmdExeCommandLine(shell, commandString string) string {
line := "/s /c \"" + commandString + "\""
if shell != "" && !strings.ContainsAny(shell, " \t") {
line = shell + " " + line
}
return line
}

// resolveLoginShell returns the user's preferred login shell, respecting the
// $SHELL environment variable and falling back to platform defaults.
func resolveLoginShell() string {
Expand Down
5 changes: 5 additions & 0 deletions internal/upstream/core/connection_launcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"github.com/smart-mcp-proxy/mcpproxy-go/internal/config"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/logs"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/oauth"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/shellwrap"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/upstream/launcher"
)

Expand Down Expand Up @@ -350,6 +351,10 @@ func (c *Client) buildLauncherCmd(_ context.Context, willUseDocker bool) (*exec.
zap.String("working_dir", c.config.WorkingDir),
zap.Bool("docker", willUseDocker))

// Windows: cmd.exe cannot take the wrapped command string as one argv
// element; hand it over as the process command line instead (#1960).
shellwrap.ApplyCommandLine(cmd)

return cmd, willUseDocker, cidFile, nil
}

Expand Down
4 changes: 4 additions & 0 deletions internal/upstream/core/process_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (

"go.uber.org/zap"

"github.com/smart-mcp-proxy/mcpproxy-go/internal/shellwrap"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/winjob"
)

Expand Down Expand Up @@ -51,6 +52,9 @@ func createProcessGroupCommandFunc(client *Client, workingDir string, logger *za
// Object (assignProcessTree resumes it), so it cannot fork a
// descendant outside the Job (Spec 116 PR4, T093b).
winjob.MarkSuspended(cmd)
// cmd.exe needs the wrapped command string as an explicit command
// line; argv escaping turns its quotes into literal \" (#1960).
shellwrap.ApplyCommandLine(cmd)

if workingDir != "" {
cmd.Dir = workingDir
Expand Down
Loading