//go:build darwin || testbuild package main import ( "context" "errors" "io" "os" "strconv" "golang.org/x/sys/unix" "amadan.net/oficina/equipo/internal/runner" ) // toolProxy is a Mac runner's MCP tool endpoint, the CLI's only MCP // server there (provider.DarwinToolMCP): equipo-runner tool-proxy // --socket . Like the Linux tool proxy it reads no environment and // no configuration and writes nothing to stderr: 2 for other arguments, // 1 when it cannot serve. A Linux release does not have it; Linux runs // the certified equipo-tool-proxy instead. func toolProxy(ctx context.Context, args []string, input io.Reader, output io.Writer) (int, bool) { if len(args) != 2 || args[0] != "--socket" { return 2, true } if dropInherited() != nil { return 1, true } if runner.ServeDarwinToolProxy(ctx, input, output, args[1]) != nil { return 1, true } return 0, true } // errInherited: the endpoint could not list or close what it inherited. var errInherited = errors.New("tool endpoint: inherited descriptors") // dropInherited lets go of what the endpoint inherited from the CLI that // started it: a token's descriptor (CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR) // and the CLI's whole environment. It serves with neither. // // A descriptor above 2 is inherited exactly when close-on-exec is clear: // one that had it set did not survive exec, and every descriptor the Go // runtime and standard library open carries it (the poller's kqueue or // epoll and eventfd, pipes, files, sockets; this binary has no cgo). So // the runtime's own descriptors are kept by what they are, not guessed // by number, whenever they were opened. The list comes from /dev/fd (on // Linux a link to /proc/self/fd). // // The environment is emptied: the endpoint needs none of it. That clears // the process's own copy; the original strings exec placed in memory // remain, which is why a token never travels in the environment (task 8 // passes it by descriptor). func dropInherited() error { entries, err := os.ReadDir("/dev/fd") if err != nil { return errInherited } for _, e := range entries { fd, err := strconv.Atoi(e.Name()) if err != nil { return errInherited } if fd <= 2 { continue } flags, err := unix.FcntlInt(uintptr(fd), unix.F_GETFD, 0) if errors.Is(err, unix.EBADF) { continue // the listing's own descriptor, closed already } if err != nil { return errInherited } if flags&unix.FD_CLOEXEC == 0 { if err := unix.Close(fd); err != nil { return errInherited } } } os.Clearenv() return nil }