Skip to content

Connect MCP tools

An agent in a sandbox reaches MCP servers in one of two ways:

  • Registered in the agent: the servers of the task are registered in the configuration of the agent, inside the sandbox, when the sandbox is created. Nothing is registered with the daemon, and the sbx CLI is not needed; the mixin that registers them is an image the daemon keeps, as for any forged kit. Claude Code, Copilot and OpenCode, for now.
  • Through the MCP gateway of its sandbox: servers registered on the host with the sbx CLI, which a task loads into the gateway of its sandbox.

MCP compares the two, and says what each server can reach outside the sandbox.

A server of the task

@app.agent(..., mcp=[...]) registers McpServers in the agent of the sandbox of each run, and ctx.mcp_token(name) gives the task the token of a server of the host, drawn for that run:

docs_src/agents/mcp_mixin.py
import contextlib
from collections.abc import AsyncIterator
from pathlib import Path
from typing import Annotated, Any

from fastsandbox import Context, FastSandbox, McpServer, WorkspaceDir

# Served by this program on 127.0.0.1:47813: it accepts the tokens of the runs, and no other.
tools = McpServer.host("docs-tools", 47813)


@contextlib.asynccontextmanager
async def lifespan(app: FastSandbox) -> AsyncIterator[dict[str, Any]]:
    # The tokens the server of the host checks in the `Authorization` header of a request.
    yield {"tokens": set()}


app = FastSandbox("docs-checks", lifespan=lifespan)


@app.agent("claude", mcp=[tools], timeout="20m")
async def check_docs(ctx: Context, repo: Annotated[Path, WorkspaceDir(clone=True)]) -> str:
    """Has Claude Code check a README against the docs, with the tools of an MCP server."""
    token = ctx.mcp_token("docs-tools")
    ctx.state["tokens"].add(token)
    try:
        workdir = str(repo.resolve())
        await ctx.agent.prompt(
            "With the tools of the docs-tools MCP server, check that README.md matches "
            "the documentation, and write what differs to DIFFERENCES.md.",
            working_dir=workdir,
        )
        return await ctx.sandbox.read_text(f"{workdir}/DIFFERENCES.md")
    finally:
        ctx.state["tokens"].discard(token)
  • Line 9: McpServer.host(name, port) is a server that a program of the host serves on a port of its loopback, in any language, here this one. The sandbox reaches it at http://host.docker.internal:<port>/mcp, over streamable HTTP. The port is part of the mixin that registers the server, its token is not: one kit serves the sandboxes of every run, each with a token of its own, as long as the server keeps its port. A server on a free port, another at every run, makes each run forge a new mixin, whose kit images the daemon keeps beside those of the last: serve on the same port from one run to the next.
  • Line 21: the sandbox of each run is launched with the server registered in Claude Code (claude mcp add, as the user agent, at its creation) and its host allowed, by a mixin docker-sandbox-kit builds, /kits/docker-sandbox-mcp-claude. An agent other than claude, copilot or opencode, a name or a URL the crate cannot register, or two servers of the same name, fail the run with InvalidKitError or InvalidSpecError before anything is created.
  • Line 24: the token of the server, 32 random bytes drawn at the launch of the sandbox, which the sandbox holds in the variable the server names, DOCKER_SANDBOX_MCP_<NAME>_TOKEN. The proxy rewrites no request to the host, so the token is what tells this run apart from any other process: the server accepts the tokens of the runs, here kept in the state of the lifespan, and refuses any other.

The proxy of the sandbox forwards the requests to the loopback of the host, which names localhost:<port> in their Host header: a server bound to 127.0.0.1 takes them as it takes those of the host, the protection of the official MCP Python SDK against DNS rebinding included. Nothing in a request tells the sandbox apart from another process of the host but its token, which the server is therefore to check.

A remote server, which the agent calls itself, is McpServer.remote(name, url); behind a token, with_bearer_env(env) sends the content of the variable env of the sandbox as its bearer. For a key the sandbox must not hold, a sandbox launched with the client gets it as a key of its spec, or a ProxiedKey, for the host of the server and the variable env: the variable holds its placeholder, which the proxy replaces with the key. An agent task has no key of its own beside those of its agent, and its env is in clear in the sandbox: never put a key there.

A server the agent starts inside the sandbox, as the user agent, and speaks to over its standard input and output, is McpServer.stdio(name, program), its arguments given by with_args(*args). It is not reached over the network and needs no token; as a process of the sandbox, it has the network of the sandbox and inherits its variables. Installing its program is the work of another mixin, or of the image of the kit.

Each server has the JSON form of docker-sandbox-kit, to_json() ({"kind": "host", "name": "docs-tools", "port": 47813}), which McpServer.from_json() reads back.

With the client, a sandbox spec registers them (SandboxSpec.with_mcp(server), the token in lease.mcp_token(name)), and Mixin.mcp(agent, *servers) is the mixin itself, to compose in a Kit: one of the mixins written in Python, whose tokens the creation request gives (server.env(token)).

A server of the MCP gateway

1. Register the server on the host

sbx mcp add registers a server: a local one, started from a command, or a remote one, reached at a URL. The Docker documentation gives its options. Before registering, a program can ask whether the MCP policy allows it, with client.mcp.check_registration(...) (see MCP gateway).

A remote server behind a token is registered with a placeholder in its header, and the token is stored as the sbx secret mcp:<server>:<placeholder>: the gateway fills the header when it connects, and the sandbox never holds the token (see MCP gateway).

2. Load it for the agent

docs_src/agents/mcp_tools.py
from pathlib import Path
from typing import Annotated

from fastsandbox import Context, FastSandbox, WorkspaceDir

app = FastSandbox("docs-checks")


@app.agent("claude", timeout="20m")
async def check_docs(ctx: Context, repo: Annotated[Path, WorkspaceDir(clone=True)]) -> str:
    """Has Claude Code check a README against the docs, with the tools of an MCP server."""
    # A server registered on the host beforehand, with `sbx mcp add docs-tools ...`.
    await ctx.sandbox.load_mcp_server("docs-tools")
    workdir = str(repo.resolve())
    await ctx.agent.prompt(
        "With the tools of the docs-tools MCP server, check that README.md matches "
        "the documentation, and write what differs to DIFFERENCES.md.",
        working_dir=workdir,
    )
    return await ctx.sandbox.read_text(f"{workdir}/DIFFERENCES.md")
  • Line 13: load_mcp_server("docs-tools") loads the server into the gateway of the sandbox of the run, before the agent starts. A server that is not registered raises NotFoundError, before the agent costs anything.
  • Lines 16 and 17: the prompt names the server, so that the agent reaches for its tools.

What the agent sees

By default the gateway is dynamic: besides the tools of the servers loaded into it, it offers mcp-find, which searches the servers registered on the host, and mcp-add, which loads one, so the agent can load any of them by itself. Loading the server from the task makes sure it is there; it does not keep the others out. A server given by a mixin is registered beside the gateway, which the kit of the agent registers too.

A sandbox created with a static set of servers offers only those: the client creates one with with_static_mcp_servers(...) (see Static and dynamic gateways). Tool names are not prefixed by server, so two servers with a tool of the same name cannot be loaded together.

Examples

agent-kit-forge gives Claude Code, by a mixin, an MCP server it serves on the host, and uses it from inside the sandbox as Claude Code would, at the URL and with the token Claude Code registered: it lists the tools and calls one, without starting the agent. Each agent has an -mcp example, which serves an MCP server from the host through the gateway and has the agent call it:

just example agent-kit-forge
just example agent-claude-mcp

See Examples.