Sandbox specs¶
A SandboxSpec describes a whole sandbox as data:
its kit, its workspace and mounts, its network rules, the API keys its proxy
writes for it, the MCP servers of its agent, its variables and its resources.
Everything but its name and the values of its keys, which come at launch, so
that one spec serves every sandbox of a job and holds nothing secret.
launch() applies it in one call and gives
a Lease, which owns the sandbox until it is shut down.
The spec is the one of docker-sandbox-blueprint: each method below is a
method of the crate, its rules are those of the crate, and its JSON form is
the one a program in another language hands the crate. FastSandbox launches
the sandbox of each run of a task this way.
import os
import fastsandbox
from fastsandbox import Agent, Keys, KitCache, SandboxSpec
# One spec for every sandbox of the job: nothing secret, nothing named.
spec = (
SandboxSpec.agent(Agent.CLAUDE)
.with_workspace(os.getcwd())
.with_network_deny("*.pastebin.com")
.with_agent_keys()
.with_env("REVIEW_MODE", "strict")
)
async def main() -> None:
client = await fastsandbox.connect()
await spec.check(client)
cache = KitCache()
for job in ("review-1", "review-2"):
# The keys the environment holds go to the proxy; the sandbox holds placeholders.
async with spec.launch(client, job, Keys.from_env(spec), cache=cache) as lease:
status = await lease.sandbox.exec(["git", "status", "--short"])
print(f"{job}: {status.stdout.strip() or 'clean'}")
print(f" kits: {', '.join(lease.report.kits[1:])}")
if __name__ == "__main__":
fastsandbox.run(main())
Writing a spec¶
A spec starts from its base kit, then each method returns a new spec:
| Method | What the sandbox gets |
|---|---|
SandboxSpec.agent(agent) |
the kit of an Agent, resolved as sbx create <agent> resolves it |
SandboxSpec.base(reference) |
a published kit, docker.io/sbx/shell:latest |
SandboxSpec() |
no base kit: the sandbox is launched on a package the program holds (see Launching on a package) |
SandboxSpec.package(dir) |
the kit package of a directory, compiled by the CLI or saved (KitPackage.save), which must suit the daemon; the mixins, network rules and MCP servers of the spec are composed after every kit of the package, its own mixins included |
with_arg(name, value) |
an argument of the base kit, model for claude |
with_mixin(mixin), with_mixin_dir(dir) |
a mixin written in Python, or the mixin of a directory |
with_workspace(dir), with_cloned_workspace(repository) |
a host directory as its workspace, or a private clone of a Git repository |
with_mount(Workspace(...)) |
a further host directory or file, beside a workspace |
with_network_allow(*hosts), with_network_deny(*hosts) |
host rules, from its creation |
with_http_allow(hosts, methods, path), with_http_deny(...) |
HTTP rules, from its start |
with_key(KeySpec.for_service(...)), with_agent_keys(), with_keys_of(agent) |
API keys the proxy writes for it |
with_mcp(server) |
an MCP server registered in its agent |
with_env(key, value) |
a variable, in clear: a secret is a key |
with_cpus(n), with_memory("4g") |
its resources |
keep_on_failure() |
a failed launch keeps the sandbox, for a look inside |
check(client) checks a spec against the
rules of a launch and the kit policy of the daemon, without pulling or writing
anything but reading its mixin directories.
InvalidSpecError, a ValueError,
names the rule a spec breaks and its field: two base kits or none, a host that
is not a host pattern, a refusal that covers the host of a key or of an MCP
server (a refusal wins over any allowance), a variable set twice, a relative
path, further mounts without a workspace (the daemon refuses them, and a
workspace is read-write). A mixin or an MCP server the forge does not take, MCP servers for an
agent other than claude, copilot or opencode for instance, raises
InvalidKitError, and a kit the
forge refuses KitForgeError. A
launch makes the same checks first.
Keys¶
A KeySpec names the variable an agent reads a key
from and the hosts the proxy writes the key for:
KeySpec.for_service(env, service), the
hosts the kits of the sandbox declare for a service (anthropic for the
claude kit), or
KeySpec.for_hosts(env, hosts). It becomes a
ProxiedKey: the sandbox holds a placeholder,
and the key only travels over the socket, to the daemon.
Keysgives the values at launch, by variable.Keys.from_env(spec)reads them from the environment of the process; the values stay in the native extension, and no method reads one back.check_keys(keys)checks that every key has a value, and that no value is given for a variable no key reads, most likely a misspelt one.- An optional key may have no value, and one
of a service no kit declares is left out rather than refused: the report of
the launch names it, in
keys_left_out. with_agent_keys()gives the sandbox every key its agent takes, as its profile says (Agent.keys), each optional: whichever the environment holds goes to the proxy. It gives nothing for a published base kit or a package, whose agent is known once its kit is forged:with_keys_of(agent)gives the keys of the agent given, whatever the base kit, for a package compiled for that agent for instance.
Launching¶
spec.launch(client, name, keys) returns a
Launch, used as client.create() is:
awaited, it gives the Lease; as an async context
manager, it shuts the lease down on the way out, also on an error or a
cancellation, without masking the error of the block, as
client.create() does: a removal that
fails too is noted on it and logged. The steps, those of the crate:
- check the spec and the values of its keys;
- forge its kit in memory, or take it from a
KitCachegiven ascache=: the sandboxes of a job then forge it once; - draw a token for each MCP server of the host, and prepare the keys;
- create the sandbox;
- start it, apply its HTTP rules and push its keys;
- return the lease, which holds its session.
The lease gives the sandbox (lease.sandbox,
with the whole client), the answer of its creation
(created), the agent its kit declares
(agent), the token of each MCP server of the host
(mcp_token(name)), for the server to check in
the requests of that sandbox alone, and the report.
shutdown() removes the sandbox, its network
rules and its keys with it, by its identifier: never another sandbox given
the same name since; a shutdown given up on the way, by a timeout or Ctrl-C,
still removes it, in a task of the crate that the exit waits for too, and a
removal that fails then is logged by docker-sandbox.
detach() gives the sandbox
and its session to the program instead, which removes it;
held says whether the lease still owns the
sandbox. A lease dropped without either closes its session: the sandbox stops
about 30 seconds later and stays, until it is removed.
A launch that fails once the sandbox exists removes it and raises
LaunchError, which names the sandbox,
its identifier, the step that failed (network, keys, start, in the order
of the launch) and whether
the sandbox stays (kept); the error of the daemon is its __cause__. A
launch abandoned on the way, by a timeout or Ctrl-C, still removes the sandbox
it created: the crate finishes it in a task of its own, which the interpreter
waits for as it exits, for 10 s at most or until a second Ctrl-C.
Launching on a package¶
A program that holds a kit package, forged once in memory
or compiled, launches its sandboxes on it with
spec.launch_package(client, name, keys, package=package),
nothing written to a directory of its own. The spec names no base kit,
SandboxSpec(), and the rules of SandboxSpec.package apply: the package
suits the daemon, takes no kit arguments, and is launched as it is, or under
the mixins, network rules and MCP servers of the spec, its own kits kept.
A spec that names a base kit of its own is refused with InvalidSpecError,
and check and launch refuse a spec without one. The JSON form of a spec
has no such base kit: a package in memory is a value of the program.
shell = await KitForge(client).forge("shell")
spec = SandboxSpec().with_network_deny("*.pastebin.com")
for job in ("job-1", "job-2"):
async with spec.launch_package(client, job, package=shell) as lease:
await lease.sandbox.exec(["make", "test"])
The report¶
lease.report is a
Report of what the launch did, which never
holds the value of a key or of a token:
kits: the kits of the sandbox, the mixins the spec generates included,/kits/docker-sandbox-networkfor its host rules and/kits/docker-sandbox-mcp-<agent>for its MCP servers;network: its rules, with awarningwhen the global policy of the daemon allows every host, as the default policy ofsbxmay, depending on how it was set up, so that the allowances of the spec restrict nothing;keys, where each key goes, andkeys_left_out, with the reason;mcp, the servers registered in the agent;withheld, the services whose credential the daemon withholds.
Network rules¶
The host rules of a spec are a mixin of its kit: the daemon creates them with
the sandbox, applies them from its creation, and removes them with it. The
HTTP rules, on methods and paths, are applied before the sandbox starts, scoped
to it: they cover its startup commands, not its install commands. Both add to the
global policy of the daemon: see the network model. Every host is a
host pattern, api.example.com, *.example.com or example.com:8443; a URL
or a path raises InvalidSpecError
before anything is created, since the daemon would store it and never apply
it. An HTTP rule the daemon refuses fails the launch at its network step,
with LaunchError. The rules of a sandbox
handle, by contrast, apply to a sandbox that runs already (see
Network and policy).
From another language¶
to_json() and
SandboxSpec.from_json() are the JSON
form of the crate, the same fields, an unknown one refused with
InvalidSpecError: a program in
another language writes a spec, and a Python one launches it.
{
"agent": "claude",
"workspace": { "mount": "/srv/project" },
"network": { "deny": ["*.pastebin.com"] },
"keys": [{ "env": "ANTHROPIC_API_KEY", "service": "anthropic" }],
"mcp": [{ "kind": "host", "name": "tools", "port": 47813 }]
}
import json
import sys
from pathlib import Path
from typing import Any
import fastsandbox
from fastsandbox import Keys, SandboxSpec
async def main(form: dict[str, Any]) -> None:
# The JSON form of the crate, written by a program in any language.
spec = SandboxSpec.from_json(form)
client = await fastsandbox.connect()
async with spec.launch(client, keys=Keys.from_env(spec)) as lease:
print(f"{lease.sandbox.name}: keys {[key.env for key in lease.report.keys]}")
print(f" servers {[server.name for server in lease.report.mcp]}")
if __name__ == "__main__":
fastsandbox.run(main(json.loads(Path(sys.argv[1]).read_text())))