sandbox

package
v0.2.90 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 15 Imported by: 0

README

MCP sandbox

Package sandbox runs stdio MCP servers in Docker containers instead of directly on the host. Use it when an agent starts MCP servers you do not fully trust, or when you want to limit what a server can reach if it is compromised.

It plugs into the SDK through mcp.CommandExecutor, so nothing else in the SDK depends on Docker. Agents that never configure a sandbox run their servers on the host, as before.

Quick start

executor, err := sandbox.NewDockerExecutor(sandbox.Config{
    Image:           "mcp/filesystem@sha256:...", // pin by digest
    AllowedCommands: []string{"node"},
    MountPaths: []sandbox.MountPath{
        {Host: "/srv/docs", Container: "/projects"}, // read-only by default
    },
}, logger)
if err != nil {
    return err
}
defer executor.Close(context.Background())

myAgent, err := agent.NewAgent(
    agent.WithLLM(llm),
    agent.WithLazyMCPConfigs([]agent.LazyMCPConfig{{
        Name:    "files",
        Type:    "stdio",
        Command: "node",
        Args:    []string{"/app/dist/index.js", "/projects"},
    }}),
    agent.WithMCPCommandExecutor(executor),
)

WithMCPCommandExecutor covers every stdio server the agent starts: from WithLazyMCPConfigs, WithMCPURLs, WithMCPPresets and MCP YAML configuration. For a server you create yourself, set mcp.StdioServerConfig.Executor. Servers passed to WithMCPServers are already running, so the option cannot apply to them.

A runnable example is in examples/mcp/sandbox.

Configuration

Field Default Meaning
Image required Image the server runs in. Pin it by digest.
AllowedCommands none Commands servers may start. A bare name (node) is looked up on the container's PATH; an absolute path (/usr/local/bin/node) must match exactly. Empty allows nothing.
DeniedCommands none Refused even when allowed, matched by base name (sh refuses /bin/sh too).
NetworkMode none As for docker run --network. Use bridge for servers that call APIs. host is refused.
MemoryLimit 256m As for docker run --memory.
CPULimit 0.5 As for docker run --cpus.
PidsLimit 64 Maximum processes in the container.
TmpfsSize 64m Size of the writable /tmp.
AllowExecInTmp false Lets programs run from /tmp. Turn it on only for servers that download a program at start and then run it from /tmp.
User image default As for docker run --user.
MountPaths none Host paths to share. Read-only unless Writable is set.
DockerPath docker on PATH The docker CLI to run.
Servers started with npx

A Node server launched with npx downloads itself at start, so it needs network access and a writable home. With an image such as node:22-alpine (pinned by digest), allow npx, set NetworkMode: "bridge", and give the server HOME=/tmp in its environment:

agent.WithLazyMCPConfigs([]agent.LazyMCPConfig{{
    Name:    "files",
    Type:    "stdio",
    Command: "npx",
    Args:    []string{"-y", "@modelcontextprotocol/server-filesystem", "/projects"},
    Env:     []string{"HOME=/tmp"},
}})

Prefer an image that already contains the server, which can run with no network at all.

Security model

Each server gets its own new container (docker run --rm -i). Containers are never reused or shared, so servers cannot see each other's files or processes. Every container:

  • starts the command with --entrypoint, so the image's own entrypoint is ignored and only allowed commands run
  • has a read-only root filesystem and a size-limited /tmp that cannot hold executables (unless AllowExecInTmp is set)
  • drops all Linux capabilities and sets no-new-privileges
  • has memory, CPU and process-count limits
  • has no network by default
  • runs an init process that reaps the server's child processes
  • sees only the host paths in MountPaths, read-only by default
  • receives only the server's configured environment variables, never the host's

Secret values are handed to the docker CLI through its environment and named with --env KEY, so they do not appear in the host's process list. HOME, PATH and DOCKER_* are passed inline instead, so setting them for a server does not change how the docker CLI itself behaves.

What it does not protect against:

  • Kernel exploits. Containers share the host's kernel. Docker isolation is not a virtual machine boundary.
  • What an allowed program does. The allowlist checks the command the agent asks to start, not what that program runs once inside the container.
  • A changing image. The image decides what is in the container. Pin it by digest; NewDockerExecutor logs a warning when it is not pinned.
  • The network you allow. With bridge, a server can reach anything the Docker network can reach, including services on your private network.

Cleanup

When a server stops normally, its input closes, it exits, and Docker removes the container. If the context given to Command is canceled, the container is force-removed. Close force-removes every container the executor started that still exists.

If the host process is killed before any of that runs, Docker closes the server's input and well-behaved MCP servers exit. Every container carries the label agent-sdk-go.sandbox, so you can find any that did not:

docker ps --filter label=agent-sdk-go.sandbox

Tests

Unit tests use a stand-in for the docker CLI and need no Docker. The integration tests check the restrictions against a real daemon:

go test -tags integration ./pkg/sandbox/

Documentation

Overview

Package sandbox runs stdio MCP servers in Docker containers instead of directly on the host.

DockerExecutor implements mcp.CommandExecutor. Give it to an agent with agent.WithMCPCommandExecutor, or set it on mcp.StdioServerConfig.Executor for a server you start yourself:

executor, err := sandbox.NewDockerExecutor(sandbox.Config{
	Image:           "mcp/filesystem@sha256:...",
	AllowedCommands: []string{"node"},
	MountPaths:      []sandbox.MountPath{{Host: "/srv/docs", Container: "/projects"}},
}, logger)
if err != nil {
	return err
}
defer executor.Close(context.Background())

a, err := agent.NewAgent(
	agent.WithLLM(llm),
	agent.WithLazyMCPConfigs([]agent.LazyMCPConfig{{
		Name:    "files",
		Type:    "stdio",
		Command: "node",
		Args:    []string{"/app/dist/index.js", "/projects"},
	}}),
	agent.WithMCPCommandExecutor(executor),
)

What the sandbox does

Each server gets its own new container (docker run --rm -i), which runs only that server and is removed when the server exits. Containers are never reused or shared, so servers cannot see each other's files or processes. Each container:

  • runs the command with --entrypoint, so the image's own entrypoint is ignored and only allowed commands start
  • has a read-only root filesystem, plus a writable tmpfs at /tmp that cannot hold executables unless Config.AllowExecInTmp is set
  • drops all Linux capabilities and sets no-new-privileges
  • has memory, CPU and process-count limits
  • has no network unless Config.NetworkMode allows it ("host" is refused)
  • runs an init process (--init) that reaps the server's child processes
  • sees only the host paths in Config.MountPaths, read-only by default
  • receives only the server's configured environment variables, never the host's environment

What it does not do

  • Containers share the host's kernel. Docker isolation is not a virtual machine boundary; a kernel exploit can escape it.
  • The allowlist checks the command the agent asks to start. It does not limit what that program runs once it is inside the container.
  • The image decides what is in the container. Pin it by digest ("image@sha256:...") so it cannot change underneath you. NewDockerExecutor logs a warning when the image is not pinned.
  • Allowing network access lets the server reach anything the Docker network can reach, including services on your private network.

Cleanup

When a server stops normally, its input closes, the server exits and Docker removes the container. If the context given to Command is canceled, the container is force-removed. Close force-removes every container the executor started that is still running. If the host process is killed before any of that runs, Docker closes the server's input and well-behaved MCP servers exit; to find any that did not, every container carries the label "agent-sdk-go.sandbox":

docker ps --filter label=agent-sdk-go.sandbox

Index

Constants

View Source
const (
	DefaultNetworkMode = "none"
	DefaultMemoryLimit = "256m"
	DefaultCPULimit    = "0.5"
	DefaultPidsLimit   = 64
	DefaultTmpfsSize   = "64m"
)

Defaults applied to zero-value Config fields.

View Source
const LabelKey = "agent-sdk-go.sandbox"

LabelKey labels every container a DockerExecutor starts. Its value is the executor's ID, so Close removes only that executor's containers.

Variables

View Source
var (
	// ErrCommandDenied is returned when a command is not allowed to start.
	ErrCommandDenied = errors.New("sandbox: command not allowed")

	// ErrDockerNotFound is returned when the docker CLI cannot be found.
	ErrDockerNotFound = errors.New("sandbox: docker CLI not found")

	// ErrInvalidConfig is returned when a Config cannot be used.
	ErrInvalidConfig = errors.New("sandbox: invalid config")

	// ErrClosed is returned when Command is called after Close.
	ErrClosed = errors.New("sandbox: executor is closed")
)

Functions

This section is empty.

Types

type Allowlist

type Allowlist struct {
	// contains filtered or unexported fields
}

Allowlist decides which commands may start. Denied commands win over allowed ones, and an empty allow list allows nothing.

Allowed entries without a slash match a bare command name exactly, which the container then looks up on its PATH. Allowed entries that are absolute paths match exactly that path. A command given as a path never matches a bare-name entry, so allowing "node" does not allow "/tmp/node" or "./node".

Denied entries match by base name, so denying "sh" refuses "sh", "/bin/sh" and "/usr/bin/sh".

func NewAllowlist

func NewAllowlist(allowed, denied []string) *Allowlist

NewAllowlist returns an Allowlist for the given allowed and denied commands.

func (*Allowlist) Check

func (a *Allowlist) Check(command string) error

Check returns nil if command may start, and an error wrapping ErrCommandDenied if not.

type Config

type Config struct {
	// Image is the container image servers run in. Required. Pin it by
	// digest, for example "mcp/time@sha256:...", so it cannot change.
	Image string `json:"image" yaml:"image"`

	// AllowedCommands lists the commands servers may start. An entry without
	// a slash, such as "npx", allows that name, looked up on the container's
	// PATH. An absolute path, such as "/usr/local/bin/npx", allows exactly
	// that path. Matching is exact and case-sensitive. If the list is empty,
	// nothing is allowed.
	AllowedCommands []string `json:"allowed_commands" yaml:"allowed_commands"`

	// DeniedCommands lists commands refused even when allowed. They match by
	// base name, so denying "sh" refuses "sh", "/bin/sh" and "/usr/bin/sh".
	DeniedCommands []string `json:"denied_commands,omitempty" yaml:"denied_commands,omitempty"`

	// NetworkMode is the container's network, as for docker run --network.
	// The default, "none", gives the server no network at all. Use "bridge"
	// for servers that call external APIs. "host" is refused.
	NetworkMode string `json:"network_mode,omitempty" yaml:"network_mode,omitempty"`

	// MemoryLimit is the container's memory limit, as for docker run
	// --memory. Default "256m".
	MemoryLimit string `json:"memory_limit,omitempty" yaml:"memory_limit,omitempty"`

	// CPULimit is the number of CPUs the container may use, as for docker run
	// --cpus. Default "0.5".
	CPULimit string `json:"cpu_limit,omitempty" yaml:"cpu_limit,omitempty"`

	// PidsLimit caps the number of processes in the container. Default 64.
	PidsLimit int `json:"pids_limit,omitempty" yaml:"pids_limit,omitempty"`

	// TmpfsSize is the size of the writable /tmp. Default "64m".
	TmpfsSize string `json:"tmpfs_size,omitempty" yaml:"tmpfs_size,omitempty"`

	// AllowExecInTmp lets programs run from /tmp. It is off by default, so
	// nothing written at run time can be executed. Turn it on only for
	// servers that download a program at start and then run it from /tmp.
	// Node servers started with npx do not need it; they need network access
	// and HOME=/tmp in the server's environment.
	AllowExecInTmp bool `json:"allow_exec_in_tmp,omitempty" yaml:"allow_exec_in_tmp,omitempty"`

	// User runs the server as this user, as for docker run --user ("uid",
	// "uid:gid" or a user name in the image). Empty keeps the image's user.
	User string `json:"user,omitempty" yaml:"user,omitempty"`

	// MountPaths are host paths to share with the container.
	MountPaths []MountPath `json:"mount_paths,omitempty" yaml:"mount_paths,omitempty"`

	// DockerPath is the docker CLI to run. Empty means "docker" on the
	// host's PATH.
	DockerPath string `json:"docker_path,omitempty" yaml:"docker_path,omitempty"`
}

Config configures a DockerExecutor.

type DockerExecutor

type DockerExecutor struct {
	// contains filtered or unexported fields
}

DockerExecutor runs each stdio MCP server in its own Docker container. It implements mcp.CommandExecutor. See the package documentation for what the container is allowed to do.

It is safe for concurrent use. Call Close when you are done with it.

func NewDockerExecutor

func NewDockerExecutor(cfg Config, logger logging.Logger) (*DockerExecutor, error)

NewDockerExecutor checks cfg and returns an executor for it. It does not contact the Docker daemon or pull the image; that happens when the first server starts. A nil logger uses the default logger.

func (*DockerExecutor) Close

func (d *DockerExecutor) Close(ctx context.Context) error

Close force-removes every container this executor started that still exists, including ones serving a live MCP session, and makes later Command calls fail. It can be called more than once.

func (*DockerExecutor) Command

func (d *DockerExecutor) Command(ctx context.Context, name string, args []string, env []string) (*exec.Cmd, error)

Command returns a docker run command that starts name with args in a new container. env holds the server's "KEY=VALUE" variables; they are the only environment the server sees.

If ctx is canceled while the server runs, the container is force-removed.

func (*DockerExecutor) ID

func (d *DockerExecutor) ID() string

ID returns the value of the LabelKey label on this executor's containers.

type MountPath

type MountPath struct {
	Host      string `json:"host" yaml:"host"`
	Container string `json:"container" yaml:"container"`
	Writable  bool   `json:"writable,omitempty" yaml:"writable,omitempty"`
}

MountPath shares a host path with the container. It is read-only unless Writable is set.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL