From ddc3c577d26674533619e8d88b3874d6afa31e26 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Thu, 29 Oct 2026 20:48:57 -0500 Subject: [PATCH 1/5] mcpx: ssh:// daemon endpoints over the system ssh binary (#1880) --- pkgs/mcpx/internal/cli/client.go | 47 +++ pkgs/mcpx/internal/cli/dispatch.go | 1 + pkgs/mcpx/internal/cli/manual.go | 18 + pkgs/mcpx/internal/cli/ssh_endpoint_test.go | 210 ++++++++++ pkgs/mcpx/internal/cli/stdio_proxy.go | 71 ++++ pkgs/mcpx/internal/daemon/transport_ssh.go | 360 ++++++++++++++++++ .../internal/daemon/transport_ssh_test.go | 78 ++++ 7 files changed, 785 insertions(+) create mode 100644 pkgs/mcpx/internal/cli/ssh_endpoint_test.go create mode 100644 pkgs/mcpx/internal/cli/stdio_proxy.go create mode 100644 pkgs/mcpx/internal/daemon/transport_ssh.go create mode 100644 pkgs/mcpx/internal/daemon/transport_ssh_test.go diff --git a/pkgs/mcpx/internal/cli/client.go b/pkgs/mcpx/internal/cli/client.go index 48105f0748..3a1727ac96 100644 --- a/pkgs/mcpx/internal/cli/client.go +++ b/pkgs/mcpx/internal/cli/client.go @@ -36,6 +36,11 @@ type Client struct { // endpoint is empty for the local socket, or a base URL for a daemon // somewhere else. endpoint string + // ssh, when set, is the ssh:// endpoint this client dials; sshURL is + // the endpoint as the user wrote it, which is what errors report (the + // http URL the transport uses is an internal placeholder). + ssh *daemon.SSHEndpoint + sshURL string // lazySocket, for an in-process (inline) client, opens the daemon's // socket on first use and returns its path. Inline mode creates no // socket for its own calls; only a script — a child process, which @@ -160,6 +165,36 @@ func NewClientAt(paths daemon.Paths, configPath, endpoint string) *Client { } return c } + // An ssh:// endpoint (issue #1880) tunnels the same HTTP API through + // the operator's own ssh, so a remote daemon needs no listening port + // and no new credential. The system ssh binary is the transport: its + // agent, ssh_config, known_hosts and bastion rules already describe + // who may reach that host. + if ep, isSSH, perr := daemon.ParseSSHEndpoint(c.endpoint); isSSH { + c.ssh = &ep + c.sshURL = ep.String() + dialer := daemon.NewSSHDialer(ep) + var dial func(context.Context, string, string) (net.Conn, error) + if perr != nil { + dial = func(context.Context, string, string) (net.Conn, error) { return nil, perr } + } else { + dial = dialer.DialContext + } + c.endpoint = "http://" + dialer.Address() + c.hc = &http.Client{ + Timeout: timeout, + Transport: &http.Transport{ + DialContext: dial, + // One ssh process per connection, reused while it lives: + // starting ssh costs a handshake, so it is worth keeping + // an idle one exactly as a VPN endpoint is. + MaxIdleConns: set.Int("http.remoteIdleConns"), + MaxIdleConnsPerHost: set.Int("http.remoteIdleConns"), + IdleConnTimeout: idle, + }, + } + return c + } // A tsnet:// endpoint names a daemon by tailnet identity (#1967). The // client joins the tailnet as an ephemeral node to dial it; there is // no address to fall back to, and the dialer says so when it cannot @@ -393,6 +428,18 @@ func (c *Client) EnsureDaemon(ctx context.Context) error { if err := ctx.Err(); err != nil { return err } + if c.ssh != nil { + // Say what was tried. Over ssh the interesting failure is + // usually on the far side -- no daemon on that socket, or no + // mcpx on that PATH -- and "unreachable" alone sends the + // reader looking at the wrong machine. + _, derr := c.do(ctx, http.MethodGet, "/v1/health", nil) + if derr == nil { + derr = ErrNoDaemon + } + return fmt.Errorf("no mcpx daemon at %s (remote command: %s): %v; it is not started from here", + c.sshURL, strings.Join(c.ssh.RemoteCommand(), " "), derr) + } return fmt.Errorf("no mcpx daemon at %s; it is not started from here", c.endpoint) } if c.Ping(ctx) { diff --git a/pkgs/mcpx/internal/cli/dispatch.go b/pkgs/mcpx/internal/cli/dispatch.go index bdbce432da..c017e76103 100644 --- a/pkgs/mcpx/internal/cli/dispatch.go +++ b/pkgs/mcpx/internal/cli/dispatch.go @@ -71,6 +71,7 @@ func (a *App) handWritten() map[string]Handler { "secrets": a.CmdSecrets, "dashboard": a.CmdDashboard, "proxy": a.CmdProxy, + "stdio-proxy": a.CmdStdioProxy, "embeddings": a.CmdEmbeddings, "feedback": a.CmdFeedback, "interactions": a.CmdInteractions, diff --git a/pkgs/mcpx/internal/cli/manual.go b/pkgs/mcpx/internal/cli/manual.go index 8a4b3142a3..9c5d33b1cc 100644 --- a/pkgs/mcpx/internal/cli/manual.go +++ b/pkgs/mcpx/internal/cli/manual.go @@ -557,6 +557,24 @@ func handCommands() []Command { "mcpx serve --tools", }, }, + { + Name: "stdio-proxy", Group: "daemon", + Local: "It is a byte pipe: it dials the daemon's unix socket on this host and copies stdin/stdout to it, which no /v1 operation can express.", + Usage: "[--sock ]", + Summary: "serve the daemon's API on stdin/stdout, for an ssh tunnel", + Detail: "The remote half of an ssh:// daemon endpoint: `ssh host mcpx " + + "stdio-proxy` turns that ssh session's pipes into an HTTP connection " + + "to the daemon on the host. The socket is resolved here, by this " + + "process, from mcpx's own paths and configuration file, so the client " + + "needs no knowledge of the remote filesystem; --sock names a socket " + + "explicitly, for a host running more than one daemon. Public rather " + + "than hidden because the ssh command line a client runs names it. " + + "See docs/protocol.md for the MCP-over-ssh form.", + Examples: []string{ + "ssh buildbox mcpx stdio-proxy", + "ssh buildbox mcpx stdio-proxy --sock /run/user/1000/mcpx/daemon.sock", + }, + }, { Name: "openapi", Group: "discovery", Usage: "[-o file]", diff --git a/pkgs/mcpx/internal/cli/ssh_endpoint_test.go b/pkgs/mcpx/internal/cli/ssh_endpoint_test.go new file mode 100644 index 0000000000..d872f0090e --- /dev/null +++ b/pkgs/mcpx/internal/cli/ssh_endpoint_test.go @@ -0,0 +1,210 @@ +package cli + +import ( + "context" + "fmt" + "io" + "net" + "net/http" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/dezren39/mcpx/internal/daemon" + "github.com/dezren39/mcpx/internal/events" +) + +// The ssh transport runs the system ssh binary. These tests put a fake +// ssh on PATH: a shell script that drops ssh's own arguments and execs +// this test binary as a shim, which copies the session's stdio to a unix +// socket. That is the same shape as a real remote `mcpx stdio-proxy` +// without needing an sshd. + +// TestSSHShimProcess is the fake remote end. It is not a test of its +// own: it returns immediately unless the fake ssh script passes the +// "shim" marker, which only happens in a child process. +func TestSSHShimProcess(t *testing.T) { + marked := false + for _, a := range os.Args { + if a == "shim" { + marked = true + } + } + if !marked { + return + } + sock := os.Getenv("MCPX_TEST_SSH_SOCK") + conn, err := net.Dial("unix", sock) + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + go func() { + _, _ = io.Copy(conn, os.Stdin) + if cw, ok := conn.(interface{ CloseWrite() error }); ok { + _ = cw.CloseWrite() + } + }() + _, _ = io.Copy(os.Stdout, conn) + os.Exit(0) +} + +// fakeSSH writes an executable named ssh into a temporary directory and +// puts that directory first on PATH. +func fakeSSH(t *testing.T, body string) { + t.Helper() + dir := t.TempDir() + script := filepath.Join(dir, "ssh") + if err := os.WriteFile(script, []byte(body), 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) +} + +// shimSSH is a fake ssh that logs its arguments and execs the test +// binary as the stdio shim. +func shimSSH(t *testing.T, sock, logPath string) { + t.Helper() + t.Setenv("MCPX_TEST_SSH_SOCK", sock) + t.Setenv("MCPX_TEST_SSH_LOG", logPath) + fakeSSH(t, "#!/bin/sh\n"+ + "printf '%s\\n' \"$@\" > \"$MCPX_TEST_SSH_LOG\"\n"+ + "exec \""+os.Args[0]+"\" -test.run '^TestSSHShimProcess$' -- shim\n") +} + +// testSocketServer serves the daemon routes a client test needs: a +// health check and a server-sent event stream. +func testSocketServer(t *testing.T) string { + t.Helper() + sock := filepath.Join(t.TempDir(), "daemon.sock") + ln, err := net.Listen("unix", sock) + if err != nil { + t.Fatal(err) + } + mux := http.NewServeMux() + mux.HandleFunc("/v1/health", func(w http.ResponseWriter, r *http.Request) { + _, _ = io.WriteString(w, `{"ok":true}`) + }) + mux.HandleFunc("/v1/events", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, "data: {\"seq\":1,\"kind\":\"server\",\"message\":\"hello\"}\n\n") + if f, ok := w.(http.Flusher); ok { + f.Flush() + } + <-r.Context().Done() + }) + srv := &http.Server{Handler: mux} + go func() { _ = srv.Serve(ln) }() + t.Cleanup(func() { _ = srv.Close() }) + return sock +} + +// An ssh:// endpoint reaches the remote daemon over the tunnel, and the +// tunnel really is `ssh ... stdio-proxy`. +func TestSSHClientDialsThroughSSH(t *testing.T) { + sock := testSocketServer(t) + logPath := filepath.Join(t.TempDir(), "ssh.args") + shimSSH(t, sock, logPath) + + paths := daemon.Paths{State: t.TempDir(), Socket: socketPathFor(t)} + c := NewClientAt(paths, "", "ssh://buildbox:2222?bin=/opt/mcpx/mcpx") + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if !c.Ping(ctx) { + b, err := c.do(ctx, http.MethodGet, "/v1/health", nil) + t.Fatalf("Ping over ssh failed: %v (%s)", err, b) + } + if err := c.EnsureDaemon(ctx); err != nil { + t.Fatalf("EnsureDaemon over ssh: %v", err) + } + + args, err := os.ReadFile(logPath) + if err != nil { + t.Fatal(err) + } + got := string(args) + for _, want := range []string{"-T", "BatchMode=yes", "2222", "buildbox", "/opt/mcpx/mcpx", "stdio-proxy"} { + if !strings.Contains(got, want) { + t.Errorf("ssh args %q missing %q", got, want) + } + } +} + +// A stream is a long-lived GET, so it proves the tunnel is not a +// request/response shortcut: bytes arrive before the stream ends. +func TestSSHClientStreamsEvents(t *testing.T) { + sock := testSocketServer(t) + shimSSH(t, sock, filepath.Join(t.TempDir(), "ssh.args")) + + paths := daemon.Paths{State: t.TempDir(), Socket: socketPathFor(t)} + c := NewClientAt(paths, "", "ssh://buildbox") + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + got := make(chan string, 1) + go func() { + _ = c.Stream(ctx, events.Filter{}, func(e events.Event) { + select { + case got <- string(e.Kind): + default: + } + cancel() + }) + }() + select { + case kind := <-got: + if kind != "server" { + t.Fatalf("streamed event kind = %q; want server", kind) + } + case <-time.After(5 * time.Second): + t.Fatal("no event arrived over the ssh stream") + } +} + +// An ssh endpoint must never start a local daemon, and the failure must +// name the host and the remote command. +func TestSSHEndpointDoesNotAutostart(t *testing.T) { + fakeSSH(t, "#!/bin/sh\necho 'ssh: connect to host buildbox port 22: Connection refused' >&2\nexit 255\n") + paths := daemon.Paths{State: t.TempDir(), Socket: socketPathFor(t)} + c := NewClientAt(paths, "", "ssh://buildbox?bin=/opt/mcpx/mcpx") + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + err := c.EnsureDaemon(ctx) + if err == nil { + t.Fatal("EnsureDaemon succeeded with an unreachable ssh host") + } + msg := err.Error() + for _, want := range []string{"ssh://buildbox", "/opt/mcpx/mcpx stdio-proxy", "not started from here"} { + if !strings.Contains(msg, want) { + t.Errorf("error %q missing %q", msg, want) + } + } + if _, statErr := os.Stat(paths.Socket); statErr == nil { + t.Error("a local daemon socket was created for a remote endpoint") + } +} + +// A malformed ssh endpoint fails at dial time with the parse error, not +// as a silent plain-TCP connection to the host. +func TestMalformedSSHEndpointFails(t *testing.T) { + paths := daemon.Paths{State: t.TempDir(), Socket: socketPathFor(t)} + c := NewClientAt(paths, "", "ssh://buildbox:notaport") + if c.Ping(context.Background()) { + t.Fatal("a malformed ssh endpoint reported a reachable daemon") + } + _, err := c.do(context.Background(), http.MethodGet, "/v1/health", nil) + if err == nil || !strings.Contains(err.Error(), "invalid ssh endpoint") { + t.Fatalf("dial error = %v; want the parse error", err) + } +} + +// socketPathFor is a socket path that must not exist: a client that +// falls back to the local daemon would create or use it. +func socketPathFor(t *testing.T) string { + t.Helper() + return filepath.Join(t.TempDir(), "should-not-be-used.sock") +} diff --git a/pkgs/mcpx/internal/cli/stdio_proxy.go b/pkgs/mcpx/internal/cli/stdio_proxy.go new file mode 100644 index 0000000000..af96f281c5 --- /dev/null +++ b/pkgs/mcpx/internal/cli/stdio_proxy.go @@ -0,0 +1,71 @@ +package cli + +import ( + "context" + "fmt" + "io" + "net" + "os" + + "github.com/dezren39/mcpx/internal/config" + "github.com/dezren39/mcpx/internal/daemon" +) + +// CmdStdioProxy serves the daemon's API on stdin/stdout: it dials the +// local daemon's unix socket and pipes the bytes through. +// +// This is the remote half of an ssh:// endpoint (#1880). The client runs +// `ssh host mcpx stdio-proxy`, and the pipes of that ssh session become an +// HTTP connection to the daemon on this host. The socket path is resolved +// here, by this process, from its own defaults (and its own configuration +// file), so the client never needs to know how the remote filesystem is +// laid out. --sock exists for a host running more than one daemon, and +// ?sock= in the endpoint passes it through. +// +// It is a public, documented command rather than a hidden one: the ssh +// command line the client runs names it, so it is the first thing a user +// sees in a process list or an error, and it is useful on its own for +// wiring a tunnel by hand. +func (a *App) CmdStdioProxy(ctx context.Context, args []string) error { + fs := newFlagSet("stdio-proxy") + sock := fs.String("sock", "", "daemon socket on this host (default: mcpx's own path here)") + cfgPath := fs.String("config", a.ConfigPath, "config file") + if err := parseFlags(a, fs, args); err != nil { + return err + } + + path := *sock + if path == "" { + paths := a.Paths + // A daemon keyed to a configuration file set listens on a keyed + // socket (see Paths.ForConfig). Reading the same configuration + // here keeps the proxy pointed at the daemon `mcpx daemon` on this + // host would have started, which is what a zero-config client + // expects. An unreadable config is not fatal: fall back to the + // plain default socket rather than refusing the tunnel. + if cfg, err := config.Load(*cfgPath); err == nil && len(cfg.Sources) > 0 { + paths = paths.ForConfig(daemon.FingerprintConfig(cfg.Sources)) + } + path = paths.Socket + } + + var d net.Dialer + conn, err := d.DialContext(ctx, "unix", path) + if err != nil { + return fmt.Errorf("stdio-proxy: no mcpx daemon at %s on this host: %w (start one with `mcpx daemon`, or point ?sock= at its socket)", path, err) + } + defer conn.Close() + + // Requests flow one way down stdin and replies up stdout. When the + // far end of the socket closes, stdout is done and so is this process; + // waiting for stdin as well would hang on a terminal that never sends + // EOF. + go func() { + _, _ = io.Copy(conn, os.Stdin) + if cw, ok := conn.(interface{ CloseWrite() error }); ok { + _ = cw.CloseWrite() + } + }() + _, _ = io.Copy(os.Stdout, conn) + return nil +} diff --git a/pkgs/mcpx/internal/daemon/transport_ssh.go b/pkgs/mcpx/internal/daemon/transport_ssh.go new file mode 100644 index 0000000000..19b66ffb5b --- /dev/null +++ b/pkgs/mcpx/internal/daemon/transport_ssh.go @@ -0,0 +1,360 @@ +package daemon + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "net" + "net/url" + "os" + "os/exec" + "strconv" + "strings" + "sync" + "time" +) + +// SSH transport (#1880): the daemon's HTTP API tunnelled over the +// operator's own ssh, so a remote daemon is reachable with the access +// control they already have -- their ssh keys, their ssh_config, their +// bastion hosts -- and mcpx needs no new credential, no listening port +// and no new Go dependency. The client runs the system `ssh` binary and +// speaks HTTP to a helper on the far side that pipes the bytes into the +// remote daemon's unix socket. +// +// This is deliberately not an embedded SSH implementation +// (golang.org/x/crypto/ssh): that would duplicate the operator's +// ssh_config, agent and known_hosts handling, and would be a second +// place for a host key policy to be wrong. + +// SSHDefaultBin is the mcpx executable the remote ssh command runs. A +// remote mcpx somewhere else is named with ?bin=. +const SSHDefaultBin = "mcpx" + +// SSHProxyCommand is the subcommand run on the remote host: it connects +// its stdin/stdout to that host's daemon socket. It is a public command +// (mcpx stdio-proxy) rather than a hidden one: it appears in the ssh +// command line the client actually runs, so anybody reading an error, a +// process list or `ssh host ps` has to be able to look it up, and it is +// independently useful for wiring a tunnel by hand. +const SSHProxyCommand = "stdio-proxy" + +// SSHEndpoint is a parsed ssh:// daemon endpoint. +type SSHEndpoint struct { + User string // empty means ssh's own default for the host + Host string + Port int // 0 means ssh's own default (22, or whatever ssh_config says) + Bin string // remote mcpx executable; SSHDefaultBin unless ?bin= says otherwise + Sock string // remote daemon socket; ?sock=, or empty for the remote process's own default +} + +// String rebuilds the endpoint in the form a user typed, so errors and +// status output show the route they named rather than an internal +// http URL invented for it. +func (e SSHEndpoint) String() string { + var b strings.Builder + b.WriteString("ssh://") + if e.User != "" { + b.WriteString(e.User) + b.WriteByte('@') + } + b.WriteString(e.Host) + if e.Port != 0 { + b.WriteByte(':') + b.WriteString(strconv.Itoa(e.Port)) + } + q := url.Values{} + if e.Bin != "" && e.Bin != SSHDefaultBin { + q.Set("bin", e.Bin) + } + if e.Sock != "" { + q.Set("sock", e.Sock) + } + if enc := q.Encode(); enc != "" { + b.WriteByte('?') + b.WriteString(enc) + } + return b.String() +} + +// Target is the destination ssh connects to. +func (e SSHEndpoint) Target() string { + if e.User == "" { + return e.Host + } + return e.User + "@" + e.Host +} + +// RemoteCommand is the argv the remote ssh session runs. The socket path +// is normally resolved by the remote process itself, so no assumption +// about the remote filesystem crosses the tunnel; ?sock= overrides it. +func (e SSHEndpoint) RemoteCommand() []string { + bin := e.Bin + if bin == "" { + bin = SSHDefaultBin + } + argv := []string{bin, SSHProxyCommand} + if e.Sock != "" { + argv = append(argv, "--sock", e.Sock) + } + return argv +} + +// ParseSSHEndpoint parses ssh://[user@]host[:port][?bin=...&sock=...]. +// +// ok is false when the endpoint is not an ssh one at all; a malformed ssh +// endpoint is an error and never a silent fallback to plain TCP, because +// the fallback would send an unauthenticated API to whatever answers on +// that host's port 22. +func ParseSSHEndpoint(endpoint string) (ep SSHEndpoint, ok bool, err error) { + rest, isSSH := strings.CutPrefix(endpoint, "ssh://") + if !isSSH { + return SSHEndpoint{}, false, nil + } + u, perr := url.Parse("ssh://" + rest) + if perr != nil || u.Hostname() == "" { + return SSHEndpoint{}, true, fmt.Errorf("invalid ssh endpoint %q: want ssh://[user@]host[:port][?bin=/path/to/mcpx][&sock=/path/to/daemon.sock]", endpoint) + } + if u.Path != "" && u.Path != "/" { + return SSHEndpoint{}, true, fmt.Errorf("invalid ssh endpoint %q: %q is not part of an ssh endpoint (a remote socket is ?sock=)", endpoint, u.Path) + } + ep = SSHEndpoint{Host: u.Hostname(), Bin: SSHDefaultBin} + if u.User != nil { + ep.User = u.User.Username() + if _, hasPW := u.User.Password(); hasPW { + return SSHEndpoint{}, true, fmt.Errorf("invalid ssh endpoint %q: ssh:// carries no password; ssh's own keys, agent and ssh_config authenticate", endpoint) + } + } + if p := u.Port(); p != "" { + n, cerr := strconv.Atoi(p) + if cerr != nil || n < 1 || n > 65535 { + return SSHEndpoint{}, true, fmt.Errorf("invalid ssh endpoint %q: bad port %q", endpoint, p) + } + ep.Port = n + } + q := u.Query() + for k := range q { + switch k { + case "bin", "sock": + default: + return SSHEndpoint{}, true, fmt.Errorf("invalid ssh endpoint %q: unknown parameter %q (want bin, sock)", endpoint, k) + } + } + if b := q.Get("bin"); b != "" { + ep.Bin = b + } + ep.Sock = q.Get("sock") + return ep, true, nil +} + +// SSHDialer dials an ssh:// endpoint by running the system ssh binary. +// It exists per endpoint and is safe for concurrent use: every call +// starts its own ssh process. +type SSHDialer struct { + Endpoint SSHEndpoint + // SSHBin is the local ssh executable; empty means "ssh" from PATH. + SSHBin string + // Stderr, when set, also receives ssh's stderr: warnings (host key + // changes, agent messages) that are not failures. A failed + // connection's stderr is captured and put in the error regardless. + Stderr io.Writer +} + +// NewSSHDialer builds a dialer for one endpoint. +func NewSSHDialer(ep SSHEndpoint) *SSHDialer { return &SSHDialer{Endpoint: ep} } + +// Address is the placeholder host the client's HTTP URLs use. The dialer +// ignores it: ssh decides where the bytes go. +func (d *SSHDialer) Address() string { return net.JoinHostPort("ssh", "0") } + +func (d *SSHDialer) sshBin() string { + if d.SSHBin != "" { + return d.SSHBin + } + return "ssh" +} + +// DialContext starts ssh and returns the connection on its stdio. +// +// The process is not tied to ctx: an HTTP keep-alive connection outlives +// the dial that opened it, and killing ssh when the dialing request +// finished would close a healthy connection under the next request. The +// transport closes the conn when it is done with it, and Close kills ssh. +func (d *SSHDialer) DialContext(ctx context.Context, _, _ string) (net.Conn, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + args := []string{"-T", "-o", "BatchMode=yes"} + if d.Endpoint.Port != 0 { + args = append(args, "-p", strconv.Itoa(d.Endpoint.Port)) + } + args = append(args, "--", d.Endpoint.Target()) + remote := d.Endpoint.RemoteCommand() + args = append(args, remote...) + + cmd := exec.Command(d.sshBin(), args...) + inR, inW, err := os.Pipe() + if err != nil { + return nil, fmt.Errorf("ssh %s: %w", d.Endpoint.Target(), err) + } + outR, outW, err := os.Pipe() + if err != nil { + _ = inR.Close() + _ = inW.Close() + return nil, fmt.Errorf("ssh %s: %w", d.Endpoint.Target(), err) + } + stderr := &cappedBuffer{max: 8 << 10} + if d.Stderr != nil { + stderr.tee = d.Stderr + } + cmd.Stdin = inR + cmd.Stdout = outW + cmd.Stderr = stderr + if err := cmd.Start(); err != nil { + _ = inR.Close() + _ = inW.Close() + _ = outR.Close() + _ = outW.Close() + return nil, fmt.Errorf("ssh %s: %w", d.Endpoint.Target(), err) + } + // The child holds the far ends; closing our copies of them is what + // lets Read see EOF when ssh exits. + _ = inR.Close() + _ = outW.Close() + + return &sshConn{ + cmd: cmd, + in: inW, + out: outR, + stderr: stderr, + remote: sshAddr(d.Endpoint.Host + ":" + strconv.Itoa(d.Endpoint.Port)), + argv: remote, + }, nil +} + +// sshConn is one ssh process seen as a net.Conn: the HTTP bytes travel +// through its stdin and stdout. +type sshConn struct { + cmd *exec.Cmd + in io.WriteCloser // our write end of ssh's stdin + out io.ReadCloser // our read end of ssh's stdout + stderr *cappedBuffer + remote net.Addr + argv []string + + closeOnce sync.Once + waitOnce sync.Once + waitErr error + closed bool +} + +func (c *sshConn) Read(b []byte) (int, error) { + n, err := c.out.Read(b) + if errors.Is(err, io.EOF) { + c.wait() + if c.waitErr != nil { + return n, c.failure() + } + } + return n, err +} + +func (c *sshConn) Write(b []byte) (int, error) { + n, err := c.in.Write(b) + if err != nil { + c.wait() + if c.waitErr != nil { + return n, c.failure() + } + } + return n, err +} + +// Close shuts the tunnel down. Killing ssh rather than only closing its +// pipes matters for a cancelled request: the far end may be mid-response +// and would otherwise hold the remote socket open. +func (c *sshConn) Close() error { + c.closeOnce.Do(func() { + c.closed = true + _ = c.in.Close() + _ = c.out.Close() + if c.cmd.Process != nil { + _ = c.cmd.Process.Kill() + } + c.wait() + }) + return nil +} + +func (c *sshConn) wait() { + c.waitOnce.Do(func() { + c.waitErr = c.cmd.Wait() + if c.closed && c.waitErr != nil { + // A kill we asked for is not a failure to report. + var ee *exec.ExitError + if errors.As(c.waitErr, &ee) { + c.waitErr = nil + } + } + }) +} + +// failure turns ssh's exit into an error that names the host and the +// remote command, because "EOF" from a tunnel says nothing about which +// of the two ends failed. +func (c *sshConn) failure() error { + msg := strings.TrimSpace(c.stderr.String()) + if msg == "" { + msg = c.waitErr.Error() + } + return fmt.Errorf("ssh %s: running %q failed: %s", + c.remote.String(), strings.Join(c.argv, " "), msg) +} + +func (c *sshConn) LocalAddr() net.Addr { return sshAddr("local") } +func (c *sshConn) RemoteAddr() net.Addr { return c.remote } + +// Deadlines are no-ops: an ssh pipe has no deadline to set. The +// request's context is what bounds a call, and the transport closes the +// connection -- which kills ssh -- when that context ends. +func (c *sshConn) SetDeadline(time.Time) error { return nil } +func (c *sshConn) SetReadDeadline(time.Time) error { return nil } +func (c *sshConn) SetWriteDeadline(time.Time) error { return nil } + +type sshAddr string + +func (a sshAddr) Network() string { return "ssh" } +func (a sshAddr) String() string { return string(a) } + +// cappedBuffer keeps the head of ssh's stderr: enough to say why it +// failed, bounded so a chatty or hostile remote cannot exhaust memory. +type cappedBuffer struct { + mu sync.Mutex + buf bytes.Buffer + max int + tee io.Writer +} + +func (b *cappedBuffer) Write(p []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + if b.tee != nil { + _, _ = b.tee.Write(p) + } + if room := b.max - b.buf.Len(); room > 0 { + if len(p) > room { + b.buf.Write(p[:room]) + } else { + b.buf.Write(p) + } + } + return len(p), nil +} + +func (b *cappedBuffer) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.String() +} diff --git a/pkgs/mcpx/internal/daemon/transport_ssh_test.go b/pkgs/mcpx/internal/daemon/transport_ssh_test.go new file mode 100644 index 0000000000..c87f20a043 --- /dev/null +++ b/pkgs/mcpx/internal/daemon/transport_ssh_test.go @@ -0,0 +1,78 @@ +package daemon + +import "testing" + +func TestParseSSHEndpoint(t *testing.T) { + cases := []struct { + endpoint string + want SSHEndpoint + ok bool + wantErr bool + }{ + {endpoint: "ssh://buildbox", want: SSHEndpoint{Host: "buildbox", Bin: SSHDefaultBin}, ok: true}, + {endpoint: "ssh://drew@buildbox:2222", want: SSHEndpoint{User: "drew", Host: "buildbox", Port: 2222, Bin: SSHDefaultBin}, ok: true}, + {endpoint: "ssh://buildbox?bin=/opt/mcpx/bin/mcpx", want: SSHEndpoint{Host: "buildbox", Bin: "/opt/mcpx/bin/mcpx"}, ok: true}, + {endpoint: "ssh://buildbox?sock=/run/mcpx/daemon.sock", want: SSHEndpoint{Host: "buildbox", Bin: SSHDefaultBin, Sock: "/run/mcpx/daemon.sock"}, ok: true}, + {endpoint: "ssh://buildbox/", want: SSHEndpoint{Host: "buildbox", Bin: SSHDefaultBin}, ok: true}, + + {endpoint: "ssh://", ok: true, wantErr: true}, + {endpoint: "ssh://buildbox:notaport", ok: true, wantErr: true}, + {endpoint: "ssh://buildbox:70000", ok: true, wantErr: true}, + {endpoint: "ssh://buildbox/path", ok: true, wantErr: true}, + {endpoint: "ssh://user:pw@buildbox", ok: true, wantErr: true}, + {endpoint: "ssh://buildbox?bogus=1", ok: true, wantErr: true}, + + {endpoint: "tsnet://laptop.tailnet.ts.net", ok: false}, + {endpoint: "unix:///tmp/mcpx.sock", ok: false}, + {endpoint: "http://127.0.0.1:8065", ok: false}, + {endpoint: "", ok: false}, + } + for _, tc := range cases { + got, ok, err := ParseSSHEndpoint(tc.endpoint) + if ok != tc.ok || (err != nil) != tc.wantErr { + t.Errorf("ParseSSHEndpoint(%q) ok=%v err=%v; want ok=%v err=%v", tc.endpoint, ok, err, tc.ok, tc.wantErr) + continue + } + if tc.wantErr || !ok { + continue + } + if got != tc.want { + t.Errorf("ParseSSHEndpoint(%q) = %+v; want %+v", tc.endpoint, got, tc.want) + } + } +} + +// A parse round trip: what String prints must parse back to the same +// endpoint, so an error message quoting the endpoint still describes the +// route the user can type again. +func TestSSHEndpointStringRoundTrip(t *testing.T) { + eps := []SSHEndpoint{ + {Host: "buildbox", Bin: SSHDefaultBin}, + {User: "drew", Host: "buildbox", Port: 2222, Bin: SSHDefaultBin}, + {Host: "buildbox", Bin: "/opt/mcpx", Sock: "/run/mcpx/daemon.sock"}, + } + for _, ep := range eps { + back, ok, err := ParseSSHEndpoint(ep.String()) + if !ok || err != nil || back != ep { + t.Errorf("%+v printed %q, parsed back %+v ok=%v err=%v", ep, ep.String(), back, ok, err) + } + } +} + +// The remote command is what runs on the far side: it names the remote +// mcpx, the proxy subcommand, and only ever an explicit socket. +func TestSSHEndpointRemoteCommand(t *testing.T) { + if got := (SSHEndpoint{Host: "h"}).RemoteCommand(); len(got) != 2 || got[0] != "mcpx" || got[1] != SSHProxyCommand { + t.Errorf("RemoteCommand() = %v", got) + } + got := SSHEndpoint{Host: "h", Bin: "/opt/mcpx", Sock: "/run/d.sock"}.RemoteCommand() + want := []string{"/opt/mcpx", SSHProxyCommand, "--sock", "/run/d.sock"} + if len(got) != len(want) { + t.Fatalf("RemoteCommand() = %v; want %v", got, want) + } + for i := range want { + if got[i] != want[i] { + t.Fatalf("RemoteCommand() = %v; want %v", got, want) + } + } +} From 3c8c91643f7fd5c9045a4b00668883d7274e569e Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Thu, 29 Oct 2026 20:52:55 -0500 Subject: [PATCH 2/5] mcpx: document ssh remote access, name ssh:// in daemon.endpoint (#1880) --- pkgs/mcpx/docs/exec.md | 4 + pkgs/mcpx/docs/parity.md | 3 +- pkgs/mcpx/docs/protocol.md | 16 +++ pkgs/mcpx/docs/remote.md | 132 +++++++++++++++++++++ pkgs/mcpx/docs/story.md | 3 + pkgs/mcpx/internal/daemon/transport_ssh.go | 4 +- pkgs/mcpx/internal/settings/registry.go | 6 +- 7 files changed, 165 insertions(+), 3 deletions(-) create mode 100644 pkgs/mcpx/docs/remote.md diff --git a/pkgs/mcpx/docs/exec.md b/pkgs/mcpx/docs/exec.md index 86e97c8fa5..e98aa9f16c 100644 --- a/pkgs/mcpx/docs/exec.md +++ b/pkgs/mcpx/docs/exec.md @@ -207,6 +207,10 @@ loopback TCP can be a container with its own filesystem; neither transport tells you whether the caller can see the daemon's disk. So the *caller* says so, with `capabilities: ["artifacts"]` and optionally `sharedFs`. +An `ssh://` endpoint is the clearest case of `sharedFs: false`: the bytes +cross a process boundary on another machine, so a `{path}` is never +hardlinked there and an artifact is uploaded instead. + ### The store Content-addressed by sha256 under `/artifacts/blobs/ab/cdef...`, with a diff --git a/pkgs/mcpx/docs/parity.md b/pkgs/mcpx/docs/parity.md index f5aac788e9..48d46118c6 100644 --- a/pkgs/mcpx/docs/parity.md +++ b/pkgs/mcpx/docs/parity.md @@ -118,7 +118,7 @@ carry instead is a description that says so and MCP annotations | `tool_invoke` | `POST /v1/tools/{tool}` | `mcpx tool invoke` *generated* | `mcpx_tool_invoke` | `ops.toolInvoke()` | | | `types` | `GET /v1/types` | `mcpx types` | `mcpx_types` | `ops.types()`, `types()` | | -## CLI commands (66) +## CLI commands (67) Every command the binary dispatches, with the operations it reaches. A command that reaches none says why: those are decisions, not gaps. @@ -183,6 +183,7 @@ that reaches none says why: those are decisions, not gaps. | `skills` | – | Manages embedded agent skills. | | `stats` | `stats_query` | | | `status` | `status` | | +| `stdio-proxy` | – | It is a byte pipe: it dials the daemon's unix socket on this host and copies stdin/stdout to it, which no /v1 operation can express. | | `stop` | `shutdown` | | | `supervise` | – | Runs in its own process as the re-exec target of the supervised transport; it serves no API. | | `task` / `tasks` | `tasks_list`, `task_get`, `task_cancel`, `task_result` | Generated from the operation table. | diff --git a/pkgs/mcpx/docs/protocol.md b/pkgs/mcpx/docs/protocol.md index 157fecaaf1..769fda65c4 100644 --- a/pkgs/mcpx/docs/protocol.md +++ b/pkgs/mcpx/docs/protocol.md @@ -303,6 +303,22 @@ the rest of this page: 2026-07-28 request. Every `/mcp` client used to share the daemon's pid and cwd, and so one stateful instance and one set of artifacts. +#### MCP over ssh + +An MCP host that can only spawn a process gets a remote daemon the same way +the CLI does: with ssh as the transport and no streamable-HTTP endpoint to +configure. + +```json +{"mcpServers":{"mcpx":{"command":"ssh","args":["buildbox","mcpx","serve","--transport","stdio"]}}} +``` + +`mcpx serve` on the remote host is a stdio shim over the daemon **there**, so +the tool calls, elicitations and artifact bytes all belong to that daemon. No +port is opened and the only credential is the ssh one. For a client that sets +a daemon endpoint instead, `ssh://buildbox` is the shorter form and the client +starts ssh itself — see [`remote.md`](./remote.md). + --- ### 2.5 Pass-through: upstreams under their own names diff --git a/pkgs/mcpx/docs/remote.md b/pkgs/mcpx/docs/remote.md new file mode 100644 index 0000000000..7e1a3915aa --- /dev/null +++ b/pkgs/mcpx/docs/remote.md @@ -0,0 +1,132 @@ +# Reaching a daemon on another machine + +The daemon speaks HTTP on a unix socket, and every client surface — the +CLI, scripts, the TUI, MCP — goes through the same client. Which means a +daemon on another machine is a transport question, not a feature: point +`daemon.endpoint` at it and everything works there. + +Three routes exist, in order of how much setup they need. + +## 1. `ssh://` — nothing to set up + +```sh +export MCPX_DAEMON_ENDPOINT=ssh://buildbox +mcpx ls +mcpx tui +``` + +The client runs your own `ssh` binary (`ssh -T -o BatchMode=yes buildbox +mcpx stdio-proxy`) and speaks the daemon's HTTP API through it. Your ssh +agent, `ssh_config`, `known_hosts`, jump hosts and `Match` rules are the +access control, because it is literally your ssh doing the connecting. +Nothing listens on the remote host beyond the daemon's own unix socket, and +no mcpx credential exists to leak. + +Details worth knowing: + +- The remote socket path is resolved **by the remote process**, from mcpx's + own paths and configuration file there. The client makes no assumption + about the remote filesystem layout. +- `?bin=/path/to/mcpx` names a remote mcpx that is not on `PATH`: + `ssh://buildbox?bin=/opt/mcpx/bin/mcpx`. +- `?sock=/run/user/1000/mcpx/daemon.sock` picks a specific remote daemon, + for a host running more than one. +- `user@` and `:port` work as in any ssh target: + `ssh://drew@buildbox:2222`. +- `BatchMode=yes` is set, so ssh never stops to ask for a password or a + passphrase: an HTTP request has no terminal to answer on. Load the key in + your agent, or use a key with no passphrase. +- A remote endpoint is **never** auto-started. If nothing answers, the error + names the host and the exact remote command that was tried; start the + daemon there with `ssh buildbox mcpx daemon` (or `mcpx daemon + --detached`). +- Server-sent events (`/v1/events`, `mcpx log --follow`) stream over the + same tunnel; there is no separate event path. + +`mcpx stdio-proxy` is the remote half and is a normal command: it dials the +local daemon socket and copies stdin/stdout to it. Running it by hand is the +quickest way to check a host: + +```sh +ssh buildbox mcpx stdio-proxy --sock /run/user/1000/mcpx/daemon.sock +``` + +## 2. `ssh -L` — forward the socket itself + +For tools that cannot run `ssh` themselves, or when you want one tunnel for +many shells, forward the unix socket as a local socket: + +```sh +ssh -N -L /tmp/buildbox-mcpx.sock:/home/you/.local/state/mcpx/daemon.sock buildbox & +export MCPX_DAEMON_ENDPOINT=unix:///tmp/buildbox-mcpx.sock +mcpx status +``` + +The forward is a plain byte pipe, so it is the same thing the `ssh://` +transport does, just started by you instead of by the client. The remote +path must be the socket the daemon there is actually using — `mcpx status +--json` on the remote host prints it (`socket`). + +`ssh -L` also works in the other direction of convenience: `-L +127.0.0.1:8065:127.0.0.1:8065` forwards the daemon's loopback TCP port, for +a remote daemon started with `daemon.address` widened or a container that +serves TCP. Prefer the socket: it is the same filesystem permission check +as being there. + +## 3. `ssh -R` — a daemon behind NAT + +The two routes above dial out from the client, which fails when the daemon's +host cannot be reached at all. Reverse the direction instead: the daemon's +host connects out to a host that is reachable, and publishes the socket +there. + +On the daemon's host (behind NAT), forward its socket to a socket on the +public host: + +```sh +ssh -N -R /tmp/team-mcpx.sock:/home/you/.local/state/mcpx/daemon.sock public-host +``` + +Then, anywhere that can reach `public-host`: + +```sh +ssh -N -L /tmp/mcpx.sock:/tmp/team-mcpx.sock public-host & +MCPX_DAEMON_ENDPOINT=unix:///tmp/mcpx.sock mcpx ls +``` + +Or, with no local forward at all, use `ssh://` from the middle host, since +the socket is already there: + +```sh +ssh public-host MCPX_DAEMON_ENDPOINT=unix:///tmp/team-mcpx.sock mcpx ls +``` + +`ssh -R` needs `AllowStreamLocalForwarding` (the default) on the server, and +`StreamLocalBindUnlink=yes` in the forwarding client's `ssh_config` to +replace a stale socket after a dropped connection. + +## 4. `mcpx serve` over ssh — MCP to a remote daemon + +An MCP host that cannot set an endpoint can spawn ssh instead of mcpx: see +the MCP-over-ssh form in [`protocol.md`](./protocol.md#24-transport-and-identity). +The short version: + +```json +{"mcpServers":{"mcpx":{"command":"ssh","args":["buildbox","mcpx","serve","--transport","stdio"]}}} +``` + +That runs `mcpx serve` on the remote host, so the daemon there is the one +answering — again with no port and no credential beyond ssh. + +## What a remote endpoint is not + +- It is not a second authentication layer. **The daemon API is + unauthenticated**; who may reach it is who may reach the host and the + socket. `ssh://` inherits exactly the ssh access you already grant. +- It is not a shared filesystem. Scripts and artifacts sent to a remote + daemon travel as bytes; a `{path}` artifact is only hardlinked when the + caller proved it shares the daemon's disk, which an ssh tunnel never + proves. See [`exec.md`](./exec.md#the-store). +- It is never started from here. Local autostart does not apply, by design: + answering from a local daemon when the remote one is unreachable would be + worse than failing. diff --git a/pkgs/mcpx/docs/story.md b/pkgs/mcpx/docs/story.md index ebedbd0edb..f257ee81b6 100644 --- a/pkgs/mcpx/docs/story.md +++ b/pkgs/mcpx/docs/story.md @@ -2905,6 +2905,9 @@ else in this document is detail underneath those four verbs. has a shape, with answers recorded inline. - [`docs/dependencies.md`](./dependencies.md) — every library and external program, and why each is needed. +- [`docs/remote.md`](./remote.md) — reaching a daemon on another machine: + `ssh://` endpoints, `ssh -L` socket forwarding, `ssh -R` for a daemon + behind NAT, and MCP over ssh. - [`docs/opencode-plugin.md`](./opencode-plugin.md) — what the plugin does and why, opencode v1 against v2, and which parts are opencode's rather than general enough to port to another harness. diff --git a/pkgs/mcpx/internal/daemon/transport_ssh.go b/pkgs/mcpx/internal/daemon/transport_ssh.go index 19b66ffb5b..d4a53dc5a3 100644 --- a/pkgs/mcpx/internal/daemon/transport_ssh.go +++ b/pkgs/mcpx/internal/daemon/transport_ssh.go @@ -14,6 +14,8 @@ import ( "strings" "sync" "time" + + "github.com/dezren39/mcpx/internal/defaults" ) // SSH transport (#1880): the daemon's HTTP API tunnelled over the @@ -205,7 +207,7 @@ func (d *SSHDialer) DialContext(ctx context.Context, _, _ string) (net.Conn, err _ = inW.Close() return nil, fmt.Errorf("ssh %s: %w", d.Endpoint.Target(), err) } - stderr := &cappedBuffer{max: 8 << 10} + stderr := &cappedBuffer{max: defaults.ExecStderrLimit} if d.Stderr != nil { stderr.tee = d.Stderr } diff --git a/pkgs/mcpx/internal/settings/registry.go b/pkgs/mcpx/internal/settings/registry.go index 317c6892ec..ea77e4cc0f 100644 --- a/pkgs/mcpx/internal/settings/registry.go +++ b/pkgs/mcpx/internal/settings/registry.go @@ -451,7 +451,11 @@ func daemonSettings() []Setting { "one on a VPN -- and mcpx will not try to start that one, because " + "answering from a local daemon when a remote one is unreachable " + "would be worse than failing. unix:///path targets a different " + - "socket on this machine.", + "socket on this machine; ssh://[user@]host[:port] reaches a daemon " + + "through your own ssh (no port or credential on the far side), with " + + "?bin= for a remote mcpx not on PATH and ?sock= for a specific remote " + + "daemon; tsnet://name reaches one by tailnet identity. See " + + "docs/remote.md.", Commands: []string{"run", "exec", "call", "ls", "types", "catalog", "search", "status", "client", "serve", "tui", "prompts", "resources"}, }, From efe9e6cea3f84dee6d6e5a08842843c9b8841e9e Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Thu, 29 Oct 2026 20:56:24 -0500 Subject: [PATCH 3/5] mcpx: test the stdio-proxy half of an ssh tunnel (#1880) --- pkgs/mcpx/internal/cli/stdio_proxy.go | 18 ++++-- pkgs/mcpx/internal/cli/stdio_proxy_test.go | 74 ++++++++++++++++++++++ 2 files changed, 85 insertions(+), 7 deletions(-) create mode 100644 pkgs/mcpx/internal/cli/stdio_proxy_test.go diff --git a/pkgs/mcpx/internal/cli/stdio_proxy.go b/pkgs/mcpx/internal/cli/stdio_proxy.go index af96f281c5..cfbb033e4f 100644 --- a/pkgs/mcpx/internal/cli/stdio_proxy.go +++ b/pkgs/mcpx/internal/cli/stdio_proxy.go @@ -56,16 +56,20 @@ func (a *App) CmdStdioProxy(ctx context.Context, args []string) error { } defer conn.Close() - // Requests flow one way down stdin and replies up stdout. When the - // far end of the socket closes, stdout is done and so is this process; - // waiting for stdin as well would hang on a terminal that never sends - // EOF. + return pipeConn(conn, os.Stdin, os.Stdout) +} + +// pipeConn copies in to conn and conn to out until the far end closes. +func pipeConn(conn io.ReadWriteCloser, in io.Reader, out io.Writer) error { + // Requests flow one way down in and replies up out. When the far end + // of the socket closes, out is done and so is this process; waiting + // for in as well would hang on a terminal that never sends EOF. go func() { - _, _ = io.Copy(conn, os.Stdin) + _, _ = io.Copy(conn, in) if cw, ok := conn.(interface{ CloseWrite() error }); ok { _ = cw.CloseWrite() } }() - _, _ = io.Copy(os.Stdout, conn) - return nil + _, err := io.Copy(out, conn) + return err } diff --git a/pkgs/mcpx/internal/cli/stdio_proxy_test.go b/pkgs/mcpx/internal/cli/stdio_proxy_test.go new file mode 100644 index 0000000000..30ac6ab5f2 --- /dev/null +++ b/pkgs/mcpx/internal/cli/stdio_proxy_test.go @@ -0,0 +1,74 @@ +package cli + +import ( + "bytes" + "context" + "io" + "net" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/dezren39/mcpx/internal/daemon" +) + +// The remote half of an ssh:// endpoint: stdin really does reach the +// daemon socket and replies come back on stdout. +func TestPipeConnCopiesBothWays(t *testing.T) { + sock := filepath.Join(t.TempDir(), "daemon.sock") + ln, err := net.Listen("unix", sock) + if err != nil { + t.Fatal(err) + } + defer ln.Close() + + got := make(chan string, 1) + go func() { + conn, err := ln.Accept() + if err != nil { + return + } + defer conn.Close() + b, _ := io.ReadAll(io.LimitReader(conn, 4)) + got <- string(b) + _, _ = conn.Write([]byte("pong")) + }() + + conn, err := net.Dial("unix", sock) + if err != nil { + t.Fatal(err) + } + var out bytes.Buffer + if err := pipeConn(conn, strings.NewReader("ping"), &out); err != nil { + t.Fatalf("pipeConn: %v", err) + } + select { + case in := <-got: + if in != "ping" { + t.Errorf("daemon received %q; want ping", in) + } + case <-time.After(5 * time.Second): + t.Fatal("nothing arrived at the socket") + } + if out.String() != "pong" { + t.Errorf("stdout = %q; want pong", out.String()) + } +} + +// A remote with no daemon running says which socket was tried and how to +// start one, rather than a bare EOF. +func TestStdioProxyNamesTheSocket(t *testing.T) { + sock := filepath.Join(t.TempDir(), "absent.sock") + a := &App{Paths: daemon.Paths{State: t.TempDir(), Socket: sock}} + err := a.CmdStdioProxy(context.Background(), []string{"--sock", sock}) + if err == nil { + t.Fatal("CmdStdioProxy succeeded with no daemon") + } + msg := err.Error() + for _, want := range []string{"absent.sock", "mcpx daemon", "?sock="} { + if !strings.Contains(msg, want) { + t.Errorf("error %q missing %q", msg, want) + } + } +} From 881b9d3a8ba88baab2b1cae3d2bca0878c1570e3 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Thu, 29 Oct 2026 21:29:18 -0500 Subject: [PATCH 4/5] fix(mcpx): disposition Codex findings on the ssh transport (#1880) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - transport_ssh: shell-quote each remote argument and send the remote command as one quoted line — ssh joins argv with spaces and the remote shell parses it, so ?bin=/?sock= values containing spaces or metacharacters now keep their argument boundaries (P2); quoting regression test added. - cli/client: a successful second SSH health check is accepted (return nil) instead of being replaced with ErrNoDaemon when the first Ping merely timed out on a slow handshake (P2). - transport_ssh: cmd.WaitDelay (3s) bounds Cmd.Wait's stderr draining, so Close no longer blocks for the lifetime of a ProxyCommand child that inherited ssh's stderr pipe; an ErrWaitDelay from our own kill is forgiven like the ExitError (P2). --- pkgs/mcpx/internal/cli/client.go | 13 ++-- pkgs/mcpx/internal/daemon/transport_ssh.go | 59 ++++++++++++++++++- .../internal/daemon/transport_ssh_test.go | 18 ++++++ 3 files changed, 82 insertions(+), 8 deletions(-) diff --git a/pkgs/mcpx/internal/cli/client.go b/pkgs/mcpx/internal/cli/client.go index 3a1727ac96..98b3b49b56 100644 --- a/pkgs/mcpx/internal/cli/client.go +++ b/pkgs/mcpx/internal/cli/client.go @@ -433,12 +433,15 @@ func (c *Client) EnsureDaemon(ctx context.Context) error { // usually on the far side -- no daemon on that socket, or no // mcpx on that PATH -- and "unreachable" alone sends the // reader looking at the wrong machine. - _, derr := c.do(ctx, http.MethodGet, "/v1/health", nil) - if derr == nil { - derr = ErrNoDaemon + // A successful health request here — after a Ping that + // timed out on a slow handshake — means the daemon IS + // reachable; accept it instead of reporting ErrNoDaemon. + if _, derr := c.do(ctx, http.MethodGet, "/v1/health", nil); derr == nil { + return nil + } else { + return fmt.Errorf("no mcpx daemon at %s (remote command: %s): %v; it is not started from here", + c.sshURL, strings.Join(c.ssh.RemoteCommand(), " "), derr) } - return fmt.Errorf("no mcpx daemon at %s (remote command: %s): %v; it is not started from here", - c.sshURL, strings.Join(c.ssh.RemoteCommand(), " "), derr) } return fmt.Errorf("no mcpx daemon at %s; it is not started from here", c.endpoint) } diff --git a/pkgs/mcpx/internal/daemon/transport_ssh.go b/pkgs/mcpx/internal/daemon/transport_ssh.go index d4a53dc5a3..2fe5d367ef 100644 --- a/pkgs/mcpx/internal/daemon/transport_ssh.go +++ b/pkgs/mcpx/internal/daemon/transport_ssh.go @@ -35,6 +35,10 @@ import ( // remote mcpx somewhere else is named with ?bin=. const SSHDefaultBin = "mcpx" +// sshWaitDelay bounds Cmd.Wait's stderr draining after ssh exits or is +// killed; see DialContext. +const sshWaitDelay = 3 * time.Second + // SSHProxyCommand is the subcommand run on the remote host: it connects // its stdin/stdout to that host's daemon socket. It is a public command // (mcpx stdio-proxy) rather than a hidden one: it appears in the ssh @@ -104,6 +108,44 @@ func (e SSHEndpoint) RemoteCommand() []string { return argv } +// shellQuote renders one argument safe to embed in the remote command +// line. ssh sends the remote command to the far side's shell as a single +// string (its arguments joined with spaces), so a ?bin= or ?sock= value +// containing spaces or metacharacters would otherwise be split — or +// worse, interpreted — remotely. Arguments made only of shell-inert +// characters pass through unquoted, keeping the ordinary command line +// exactly what a reader expects to see. +func shellQuote(s string) string { + if s == "" { + return "''" + } + if strings.IndexFunc(s, func(r rune) bool { + switch { + case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9': + return false + } + switch r { + case '_', '-', '.', '/', ':', '@', '%', '+', '=', ',': + return false + } + return true + }) < 0 { + return s + } + return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" +} + +// remoteCommandLine is RemoteCommand as the one string ssh actually +// delivers to the remote shell, each argument shell-quoted. +func (e SSHEndpoint) remoteCommandLine() string { + argv := e.RemoteCommand() + quoted := make([]string, len(argv)) + for i, a := range argv { + quoted[i] = shellQuote(a) + } + return strings.Join(quoted, " ") +} + // ParseSSHEndpoint parses ssh://[user@]host[:port][?bin=...&sock=...]. // // ok is false when the endpoint is not an ssh one at all; a malformed ssh @@ -194,9 +236,18 @@ func (d *SSHDialer) DialContext(ctx context.Context, _, _ string) (net.Conn, err } args = append(args, "--", d.Endpoint.Target()) remote := d.Endpoint.RemoteCommand() - args = append(args, remote...) + // One argument, shell-quoted: ssh joins the command arguments with + // spaces and the remote shell parses the result, so quoting here is + // what preserves each value's argument boundary on the far side. + args = append(args, d.Endpoint.remoteCommandLine()) cmd := exec.Command(d.sshBin(), args...) + // Bound how long Wait may spend on the stderr copy after ssh dies: + // a ProxyCommand child of ssh can inherit the stderr pipe and hold + // it open long after ssh itself is gone, and an unbounded Wait + // would make Close (called synchronously by net/http on cancel) + // block for that child's whole lifetime. + cmd.WaitDelay = sshWaitDelay inR, inW, err := os.Pipe() if err != nil { return nil, fmt.Errorf("ssh %s: %w", d.Endpoint.Target(), err) @@ -294,9 +345,11 @@ func (c *sshConn) wait() { c.waitOnce.Do(func() { c.waitErr = c.cmd.Wait() if c.closed && c.waitErr != nil { - // A kill we asked for is not a failure to report. + // A kill we asked for is not a failure to report — and + // neither is the wait-delay expiry that kill can cause + // when a proxy child still holds the stderr pipe. var ee *exec.ExitError - if errors.As(c.waitErr, &ee) { + if errors.As(c.waitErr, &ee) || errors.Is(c.waitErr, exec.ErrWaitDelay) { c.waitErr = nil } } diff --git a/pkgs/mcpx/internal/daemon/transport_ssh_test.go b/pkgs/mcpx/internal/daemon/transport_ssh_test.go index c87f20a043..2a1479205f 100644 --- a/pkgs/mcpx/internal/daemon/transport_ssh_test.go +++ b/pkgs/mcpx/internal/daemon/transport_ssh_test.go @@ -76,3 +76,21 @@ func TestSSHEndpointRemoteCommand(t *testing.T) { } } } + +// The command line ssh delivers is one string the remote shell parses: +// a ?bin= or ?sock= value with spaces must arrive as ONE argument. +func TestSSHRemoteCommandLineQuotesValuesWithSpaces(t *testing.T) { + ep := SSHEndpoint{Host: "h", Bin: "/opt/My Tools/mcpx", Sock: "/run/my dir/d.sock"} + got := ep.remoteCommandLine() + want := "'/opt/My Tools/mcpx' stdio-proxy --sock '/run/my dir/d.sock'" + if got != want { + t.Errorf("remoteCommandLine() = %q; want %q", got, want) + } + plain := (SSHEndpoint{Host: "h", Bin: "/opt/mcpx", Sock: "/run/d.sock"}).remoteCommandLine() + if plain != "/opt/mcpx stdio-proxy --sock /run/d.sock" { + t.Errorf("inert values should pass through unquoted, got %q", plain) + } + if q := shellQuote("it's"); q != `'it'\''s'` { + t.Errorf("shellQuote(it's) = %q", q) + } +} From 0a9ee541a3fedde942c6cd75b4b89bbf35489372 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Thu, 29 Oct 2026 21:59:35 -0500 Subject: [PATCH 5/5] fix(mcpx): disposition Codex round-2 findings on the ssh transport (#1880) - Connect's named-endpoint rung only Pinged once, so an ssh handshake slower than autostart.pingTimeout made ordinary commands reject a reachable remote daemon; the EnsureDaemon fallback never applied. Client.reachable() now carries that fallback (Ping, then one plain health request for ssh:// endpoints) and both Connect and EnsureDaemon use it. Regression test: first fake-ssh invocation sleeps 3s, Connect still chooses the named endpoint. - stdio-proxy only observed its context while dialling; afterwards pipeConn blocked in io.Copy, so SIGINT/SIGTERM left the proxy alive indefinitely on a streaming /v1/events response. proxyPipe closes the daemon socket via context.AfterFunc, interrupting the copy. Regression test: cancel with a silent, open connection ends the pipe. --- pkgs/mcpx/internal/cli/client.go | 18 +++++++++++++- pkgs/mcpx/internal/cli/connect.go | 2 +- pkgs/mcpx/internal/cli/ssh_endpoint_test.go | 27 +++++++++++++++++++++ pkgs/mcpx/internal/cli/stdio_proxy.go | 15 +++++++++++- pkgs/mcpx/internal/cli/stdio_proxy_test.go | 22 +++++++++++++++++ 5 files changed, 81 insertions(+), 3 deletions(-) diff --git a/pkgs/mcpx/internal/cli/client.go b/pkgs/mcpx/internal/cli/client.go index 98b3b49b56..d198e6b1bd 100644 --- a/pkgs/mcpx/internal/cli/client.go +++ b/pkgs/mcpx/internal/cli/client.go @@ -407,6 +407,22 @@ func (c *Client) Ping(ctx context.Context) bool { return err == nil } +// reachable is Ping with the ssh:// fallback EnsureDaemon has always had: +// an ssh handshake can legitimately take longer than +// autostart.pingTimeout, so a timed-out Ping is retried once as a plain +// health request bounded only by the caller's ctx before the daemon is +// declared unreachable. Non-ssh endpoints get Ping exactly. +func (c *Client) reachable(ctx context.Context) bool { + if c.Ping(ctx) { + return true + } + if c.ssh == nil { + return false + } + _, err := c.do(ctx, http.MethodGet, "/v1/health", nil) + return err == nil +} + // EnsureDaemon starts a background daemon if one is not already running and // waits for it to become reachable. This is what makes every command work with // no setup step. @@ -422,7 +438,7 @@ func (c *Client) EnsureDaemon(ctx context.Context) error { // Starting a local daemon because a remote one is unreachable would // silently answer from the wrong machine, which is worse than // failing. - if c.Ping(ctx) { + if c.reachable(ctx) { return nil } if err := ctx.Err(); err != nil { diff --git a/pkgs/mcpx/internal/cli/connect.go b/pkgs/mcpx/internal/cli/connect.go index 26b3591245..a18e6becae 100644 --- a/pkgs/mcpx/internal/cli/connect.go +++ b/pkgs/mcpx/internal/cli/connect.go @@ -92,7 +92,7 @@ func (a *App) Connect(ctx context.Context, opt ConnectOptions) (*Client, *Ladder if opt.Endpoint != "" { start := time.Now() c := NewClientAt(paths, a.ConfigPath, opt.Endpoint) - if c.Ping(ctx) { + if c.reachable(ctx) { record("url", opt.Endpoint, start, nil) l.Chosen = "url" return c, l, nil diff --git a/pkgs/mcpx/internal/cli/ssh_endpoint_test.go b/pkgs/mcpx/internal/cli/ssh_endpoint_test.go index d872f0090e..0dd220ad83 100644 --- a/pkgs/mcpx/internal/cli/ssh_endpoint_test.go +++ b/pkgs/mcpx/internal/cli/ssh_endpoint_test.go @@ -208,3 +208,30 @@ func socketPathFor(t *testing.T) string { t.Helper() return filepath.Join(t.TempDir(), "should-not-be-used.sock") } + +// The CLI connection ladder gets the same slow-handshake fallback as +// EnsureDaemon: Connect's named-endpoint rung used to Ping once, so a +// first ssh handshake slower than autostart.pingTimeout (2s) made every +// ordinary command report a reachable daemon as dead. The fake ssh +// sleeps 3s on its first invocation only; the fallback health request +// dials again and answers at once. +func TestSSHConnectFallsBackPastSlowHandshake(t *testing.T) { + sock := testSocketServer(t) + t.Setenv("MCPX_TEST_SSH_SOCK", sock) + marker := filepath.Join(t.TempDir(), "ssh.slowed") + t.Setenv("MCPX_TEST_SSH_SLOW", marker) + fakeSSH(t, "#!/bin/sh\n"+ + "if [ ! -f \"$MCPX_TEST_SSH_SLOW\" ]; then : > \"$MCPX_TEST_SSH_SLOW\"; sleep 3; fi\n"+ + "exec \""+os.Args[0]+"\" -test.run '^TestSSHShimProcess$' -- shim\n") + + a := &App{Paths: daemon.Paths{State: t.TempDir(), Socket: socketPathFor(t)}} + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + c, ladder, err := a.Connect(ctx, ConnectOptions{Endpoint: "ssh://buildbox"}) + if err != nil { + t.Fatalf("Connect over a slow ssh handshake: %v\n%s", err, ladder.Describe()) + } + if c == nil || ladder.Chosen != "url" { + t.Fatalf("Connect chose %q; want the named ssh endpoint", ladder.Chosen) + } +} diff --git a/pkgs/mcpx/internal/cli/stdio_proxy.go b/pkgs/mcpx/internal/cli/stdio_proxy.go index cfbb033e4f..87d0431f7a 100644 --- a/pkgs/mcpx/internal/cli/stdio_proxy.go +++ b/pkgs/mcpx/internal/cli/stdio_proxy.go @@ -56,7 +56,20 @@ func (a *App) CmdStdioProxy(ctx context.Context, args []string) error { } defer conn.Close() - return pipeConn(conn, os.Stdin, os.Stdout) + return proxyPipe(ctx, conn, os.Stdin, os.Stdout) +} + +// proxyPipe pipes between the daemon socket and the session's stdio, +// ending when the caller's ctx does. pipeConn alone blocks in io.Copy +// once dialling is done, so a SIGINT/SIGTERM delivered through main's +// signal.NotifyContext would leave the proxy alive indefinitely on a +// streaming response (the daemon streams /v1/events until the +// connection closes). Closing the socket on cancellation is what makes +// the copy return. +func proxyPipe(ctx context.Context, conn net.Conn, in io.Reader, out io.Writer) error { + stop := context.AfterFunc(ctx, func() { _ = conn.Close() }) + defer stop() + return pipeConn(conn, in, out) } // pipeConn copies in to conn and conn to out until the far end closes. diff --git a/pkgs/mcpx/internal/cli/stdio_proxy_test.go b/pkgs/mcpx/internal/cli/stdio_proxy_test.go index 30ac6ab5f2..0a890c36cc 100644 --- a/pkgs/mcpx/internal/cli/stdio_proxy_test.go +++ b/pkgs/mcpx/internal/cli/stdio_proxy_test.go @@ -72,3 +72,25 @@ func TestStdioProxyNamesTheSocket(t *testing.T) { } } } + +// Cancellation ends the proxy even when the daemon never sends another +// byte and never closes: the ctx-triggered socket close is the only +// thing that can interrupt the copy. +func TestProxyPipeStopsOnContextCancel(t *testing.T) { + client, server := net.Pipe() + defer server.Close() + + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + go func() { + done <- proxyPipe(ctx, client, strings.NewReader(""), io.Discard) + }() + + time.Sleep(100 * time.Millisecond) + cancel() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("proxyPipe kept piping after its context was cancelled") + } +}