Skip to main content

Vercel sandboxes

Run commands in isolated Vercel environments with either persistent Sandbox microVMs or stateless Serverless Functions.

Vercel sandbox
Direct link to Vercel sandbox

Executes commands inside Vercel Sandbox which is an ephemeral Firecracker MicroVM. Sandboxes created from a runtime run Amazon Linux 2023. Sandboxes created from a custom image or a snapshot use the filesystem that image or snapshot contains. Provides a persistent in-session filesystem, sudo access, exposed ports, and background processes. For interface details, see the WorkspaceSandbox interface.

note

This is distinct from VercelServerlessSandbox, which runs commands as stateless Vercel serverless Functions. VercelSandbox runs a full Linux MicroVM with a persistent filesystem and long-running processes.

Installation
Direct link to Installation

npm install @mastra/vercel

Authentication
Direct link to Authentication

The @vercel/sandbox SDK uses a Vercel OIDC token automatically when no explicit credentials are provided. If you provide token, teamId, or projectId, provide all three values together.

For local development, link the project and pull a development token:

vercel link
vercel env pull

On Vercel, authentication is handled automatically. No configuration needed.

Usage
Direct link to Usage

Add a VercelSandbox to a workspace and assign it to an agent:

import { Agent } from '@mastra/core/agent'
import { Workspace } from '@mastra/core/workspace'
import { VercelSandbox } from '@mastra/vercel'

const workspace = new Workspace({
sandbox: new VercelSandbox({
runtime: 'node24',
timeout: 600_000,
}),
})

const agent = new Agent({
id: 'code-agent',
name: 'Code Agent',
instructions: 'You are a coding assistant working in this workspace.',
model: 'anthropic/claude-sonnet-5-5',
workspace,
})

const response = await agent.generate('Print "Hello, world!" and show the Node.js version.')

console.log(response.text)

Resources and exposed ports
Direct link to Resources and exposed ports

Allocate vCPUs (2048 MB of memory per vCPU) and expose ports to reach network services running inside the sandbox:

const sandbox = new VercelSandbox({
runtime: 'node24',
resources: { vcpus: 4 },
ports: [3000],
})

const workspace = new Workspace({ sandbox })
await sandbox.start()

// The public HTTPS domain for an exposed port is available via getInfo()
const { metadata } = sandbox.getInfo()
console.log(metadata?.domains) // { 3000: 'https://....vercel.run' }

Streaming output
Direct link to Streaming output

Stream command output in real time via onStdout and onStderr callbacks:

await sandbox.executeCommand('sh', ['-c', 'for i in 1 2 3; do echo "line $i"; sleep 1; done'], {
onStdout: chunk => process.stdout.write(chunk),
onStderr: chunk => process.stderr.write(chunk),
})

Both callbacks are optional and can be used independently.

Custom images, snapshots and network policy
Direct link to Custom images, snapshots and network policy

Start from a Vercel Container Registry image or a filesystem snapshot, and restrict outbound traffic at creation time. The environment selection is mutually exclusive: pass at most one of runtime, image or source.

Sandboxes started from a custom image or a snapshot aren't assumed to run Amazon Linux 2023. Their default agent instructions make no operating-system or package-manager claim.

// From a container image (no runtime is sent with the request)
const fromImage = new VercelSandbox({ image: 'my-repo:v1' })

// From a filesystem snapshot
const fromSnapshot = new VercelSandbox({
source: { type: 'snapshot', snapshotId: 'snap_123' },
})

// From a runtime with all outbound traffic blocked
const offline = new VercelSandbox({ runtime: 'node24', networkPolicy: 'deny-all' })

// Allow only specific hosts and subnets
const restricted = new VercelSandbox({
networkPolicy: {
allow: ['registry.npmjs.org', '*.githubusercontent.com'],
subnets: { allow: ['10.0.0.0/8'] },
},
})

Creation options apply when a new sandbox is created. A networkPolicy protects that new sandbox from its first command.

When sandboxName matches a sandbox that already exists, starting resumes it unchanged: it keeps the configuration and network policy it was created with, so a stricter policy passed here doesn't restrict it. To change the policy of a running sandbox, update it through the underlying SDK (await sandbox.sandbox.update({ networkPolicy: 'deny-all' })). Mastra doesn't manage that.

Region and failover regions
Direct link to Region and failover regions

Vercel runs sandboxes in many regions. Set region to pin creation to one region, and failoverRegions to list the regions Vercel may use as fallbacks, in order. A failover region must not repeat region:

const sandbox = new VercelSandbox({
region: 'fra1',
failoverRegions: ['iad1', 'sfo1'],
})

Both options are passed to Sandbox.create() and Sandbox.getOrCreate(), so a sandbox created for a name uses them. When a sandbox with that name already exists, getOrCreate resumes it unchanged: the supplied region and failoverRegions don't reconfigure it. An empty failoverRegions array creates the sandbox without failover. Read the region a sandbox is configured for from the SDK instance; when Vercel fails over, the SDK's session object reports the region the running VM uses:

await sandbox.start()
console.log(sandbox.sandbox.region)

Mounting Vercel Drives
Direct link to Mounting Vercel Drives

Vercel Drives are persistent volumes that sandboxes can attach at a path. Pass mounts to attach them:

import { Drive } from '@vercel/sandbox'
import { VercelSandbox } from '@mastra/vercel'

const drive = await Drive.getOrCreate({ name: 'agent-data' })

const sandbox = new VercelSandbox({
// A sandbox's main region must match the Drive's region.
region: drive.region,
mounts: { '/data': drive },
})

await sandbox.start()
await sandbox.executeCommand('sh', ['-c', 'echo hello > /data/marker.txt'])

Mount paths must be absolute and can't overlap. A sandbox can mount up to four Drives, and its main region must match each Drive's region. Only one sandbox at a time can mount a Drive read-write, so other sandboxes mount drive.snapshot() for read-only copies. A value is a Drive instance for read-write access, drive.snapshot() for a read-only copy, or an explicit { drive: string, mode } pair where drive is the Drive's name and mode is 'read-write' or 'snapshot':

const archive = await Drive.getOrCreate({ name: 'agent-archive', region: drive.region })

const sandbox = new VercelSandbox({
region: drive.region,
mounts: {
// A Drive instance mounts read-write.
'/data': drive,
// The SDK's snapshot helper mounts a read-only copy.
'/snapshot': drive.snapshot(),
// The explicit form takes a Drive's name and a mode.
'/archive': { drive: archive.name, mode: 'read-write' },
},
})

Files written to a read-write mount persist in the Drive. Once the sandbox that holds the read-write mount stops, another sandbox can mount the same Drive and read them back:

await sandbox.stop()

const reader = new VercelSandbox({
region: drive.region,
mounts: { '/data': drive },
})
await reader.start()

const result = await reader.executeCommand('cat', ['/data/marker.txt'])
console.log(result.stdout) // hello

Mounts are applied when the sandbox is created. A sandbox already running keeps the mounts it started with, and a named sandbox that already exists resumes unchanged with the mounts it was created with.

Constructor parameters
Direct link to Constructor parameters

id?:

string
= Auto-generated
Unique identifier for this sandbox instance.

sandboxName?:

string
Optional name passed to the Vercel API. Auto-generated if omitted. A name is an identity: starting resumes an existing sandbox with that name without applying creation options, so an existing sandbox keeps the configuration and network policy it was created with.

token?:

string
Vercel API token. Falls back to the VERCEL_TOKEN environment variable. Omit to use the OIDC token.

teamId?:

string
Vercel team ID. Falls back to the VERCEL_TEAM_ID environment variable.

projectId?:

string
Vercel project ID. Falls back to the VERCEL_PROJECT_ID environment variable.

runtime?:

'node24' | 'node22' | 'node26' | 'python3.13'
= 'node24'
Sandbox runtime. Ignored and rejected when image or source is set. The node24 default applies only when the sandbox starts from a runtime.

image?:

string
Start from a Vercel Container Registry image (my-repo, my-repo:v1, or a fully-qualified vcr.vercel.com/... reference). Mutually exclusive with runtime and source. No runtime is sent with the request.

source?:

{ type: 'snapshot'; snapshotId: string }
Start from an existing filesystem snapshot. Only the snapshot source is supported; git and tarball sources are not exposed. Mutually exclusive with runtime and image. No runtime is sent with the request.

region?:

SandboxRegion
= 'iad1' (Vercel API default)
Vercel region to create the sandbox in, for example fra1. Accepts any Vercel region.

failoverRegions?:

SandboxRegion[]
Regions the sandbox can fail over to, in order. Must not include region. An empty array creates the sandbox with no failover regions.

networkPolicy?:

'allow-all' | 'deny-all' | NetworkPolicy
= 'allow-all'
Outbound network policy applied at creation. Pass 'deny-all' to block all egress, 'allow-all' (the platform default) for full internet access, or an object with allow domain rules and subnets CIDR lists. A newly created sandbox is protected from its first command; an existing sandbox resumed by sandboxName keeps its current policy.

timeout?:

number
= 300000 (5 minutes)
Timeout in milliseconds before the sandbox auto-terminates.

resources?:

{ vcpus?: number }
Resource allocation. Each vCPU comes with 2048 MB of memory.

ports?:

number[]
Ports to expose from the sandbox (up to 15). Public HTTPS domains are available via getInfo().metadata.domains.

mounts?:

SandboxMounts
Vercel Drives to mount inside the sandbox at creation. Keys are absolute paths inside the sandbox; values are a Drive instance, a drive.snapshot(), or an explicit { drive: string, mode } where drive is the Drive's name.

env?:

Record<string, string>
= {}
Default environment variables inherited by all commands.

workingDirectory?:

string
Default directory for command execution when no per-command cwd is given. A per-command cwd always wins. Use an absolute path.

metadata?:

Record<string, unknown>
= {}
Custom metadata surfaced via getInfo().

instructions?:

string | ((opts) => string)
Override the default instructions returned by getInstructions(). Pass a string to replace them, or a function to extend the defaults.

onStart?:

SandboxStartHook
Lifecycle hook called after the sandbox reaches running status.

onStop?:

SandboxLifecycleHook
Lifecycle hook called before the sandbox stops.

onDestroy?:

SandboxLifecycleHook
Lifecycle hook called before the sandbox is destroyed.

Properties
Direct link to Properties

id:

string
Sandbox instance identifier.

name:

'VercelSandbox'
Human-readable name.

provider:

'vercel-sandbox'
Provider type identifier.

status:

ProviderStatus
'pending' | 'starting' | 'running' | 'stopping' | 'stopped' | 'destroying' | 'destroyed' | 'error'

sandbox:

Sandbox
The underlying @vercel/sandbox Sandbox instance. Throws SandboxNotReadyError if the sandbox has not been started.

processes:

VercelSandboxProcessManager
Background process manager. See SandboxProcessManager reference.

Background processes
Direct link to Background processes

VercelSandbox includes a process manager for spawning and managing background processes. Each spawned process runs as a detached command inside the MicroVM, with output streamed through the command logs.

const sandbox = new VercelSandbox({ runtime: 'node24', ports: [3000] })
await sandbox.start()

const handle = await sandbox.processes.spawn('node server.js', {
env: { PORT: '3000' },
onStdout: data => console.log(data),
})

console.log(handle.stdout)
await handle.kill()

See the SandboxProcessManager reference for the full API.

Methods
Direct link to Methods

extendTimeout(ms)
Direct link to extendtimeoutms

Asks Vercel to keep the running session alive for ms more milliseconds, so a run can outlive the timeout the sandbox was created with:

const sandbox = new VercelSandbox({ timeout: 300_000 })
await sandbox.start()

// Keeps the same session alive for another 10 minutes.
await sandbox.extendTimeout(600_000)

Parameters:

ms:

number
Milliseconds to add to the running session deadline.

Returns: Promise<void>. It resolves once the running session deadline has moved by ms.

The call extends the live session deadline only, so 60_000 keeps the same MicroVM running for 60 seconds longer without changing the timeout the sandbox was constructed with (which getInfo().metadata.timeout keeps reporting). If the sandbox isn't running yet, extendTimeout() starts it first. Repeated calls reuse the same session instead of creating a new one. Vercel caps the total session duration by plan, so extending past that limit rejects with the provider error unchanged.

note

The Vercel Sandbox SDK doesn't expose a stdin channel for running commands, so handle.sendStdin() throws.

The Mastra adapter doesn't implement the Workspace filesystem mounting API, so mounts configured on a Workspace aren't attached to the sandbox. Attach Vercel Drives with the mounts constructor option instead (see Mounting Vercel Drives). The underlying Vercel Sandbox product also supports Filesystem in Userspace (FUSE) mounts, which you can configure through the SDK instance exposed by sandbox.sandbox, but Mastra doesn't manage their lifecycle.

Limits
Direct link to Limits

  • Up to 32 vCPUs, with 2048 MB of memory per vCPU.
  • Up to 15 exposed ports.
  • The filesystem is ephemeral. It's persisted only within the session and lost when the sandbox stops.
  • Maximum runtime is plan-dependent (45 minutes on Hobby, up to 24 hours on Pro and Enterprise), with a default of 5 minutes.

See the Vercel Sandbox documentation for current limits and pricing.

Vercel serverless sandbox
Direct link to Vercel serverless sandbox

VercelServerlessSandbox executes commands as Vercel serverless functions. It provides globally distributed, zero-infrastructure execution with automatic scaling. For interface details, see the WorkspaceSandbox interface.

warning

VercelServerlessSandbox is stateless. It doesn't provide a persistent filesystem, interactive shell, or long-running background processes. Only /tmp is writable, and it's ephemeral between invocations.

note

For a full Linux MicroVM with a persistent filesystem, sudo access, exposed ports, and background processes, use VercelSandbox, which is backed by the Vercel Sandbox product.

Installation
Direct link to Installation

npm install @mastra/vercel

Usage
Direct link to Usage

Add a VercelServerlessSandbox to a workspace and assign it to an agent:

import { Agent } from '@mastra/core/agent'
import { Workspace } from '@mastra/core/workspace'
import { VercelServerlessSandbox } from '@mastra/vercel'

const workspace = new Workspace({
sandbox: new VercelServerlessSandbox({
token: process.env.VERCEL_TOKEN,
}),
})

const agent = new Agent({
id: 'dev-agent',
name: 'dev-agent',
instructions: 'You are a coding assistant working in this workspace.',
model: 'anthropic/claude-sonnet-5-5',
workspace,
})

Team-scoped deployment with custom resources
Direct link to Team-scoped deployment with custom resources

const workspace = new Workspace({
sandbox: new VercelServerlessSandbox({
token: process.env.VERCEL_TOKEN,
teamId: 'team_abc123',
regions: ['iad1', 'sfo1'],
maxDuration: 120,
memory: 3008,
env: {
NODE_ENV: 'production',
},
}),
})

Constructor parameters
Direct link to Constructor parameters

token?:

string
Vercel API token. Falls back to VERCEL_TOKEN environment variable.

teamId?:

string
Vercel team ID for team-scoped deployments.

projectName?:

string
Existing Vercel project name. Auto-generated if omitted.

regions?:

string[]
= ['iad1']
Deployment regions.

maxDuration?:

number
= 60
Function maximum duration in seconds.

memory?:

number
= 1024
Function memory in MB.

env?:

Record<string, string>
Environment variables baked into the deployed function source. These are embedded at deploy time, not set dynamically.

workingDirectory?:

string
Default directory for command execution when no per-command cwd is given. A per-command cwd always wins. When omitted, commands fall back to /tmp and sandbox.workingDirectory stays undefined.

commandTimeout?:

number
= 55000
Per-invocation command timeout in milliseconds.

instructions?:

string | ((opts) => string)
Custom instructions that override the default instructions returned by getInstructions(). Pass a string to fully replace, or a function to extend the defaults.

onStart?:

SandboxStartHook
Lifecycle hook called after the sandbox reaches running status.

onStop?:

SandboxLifecycleHook
Lifecycle hook called before the sandbox stops.

onDestroy?:

SandboxLifecycleHook
Lifecycle hook called before the sandbox is destroyed.

Properties
Direct link to Properties

id:

string
Unique identifier for this sandbox instance.

name:

'VercelServerlessSandbox'
Human-readable name.

provider:

'vercel-serverless'
Provider type identifier.

status:

ProviderStatus
Current lifecycle status: 'pending', 'starting', 'running', 'stopping', 'stopped', 'destroying', 'destroyed', or 'error'.

Limitations
Direct link to Limitations

VercelServerlessSandbox uses serverless functions under the hood, which means:

  • No persistent filesystem: Files written to /tmp are ephemeral and cleared between invocations.
  • No interactive shell: Commands run via /bin/sh -c with no stdin streaming.
  • No background processes: No process manager, PIDs, or long-running tasks.
  • No mounting: Cloud storage mounting (S3, GCS) isn't supported.
  • Timeout limits: Maximum execution time is bounded by maxDuration (default 60s).