@mastra/e2b package connects a Mastra workspace to an E2B sandbox, so agent-generated commands run in an isolated cloud environment instead of on your machine.
In this guide, you will build a command-line coding agent that:
- Starts an E2B sandbox through Mastra’s workspace API.
- Creates and tests a small project inside the sandbox.
- Streams its progress to your terminal.
- Destroys the sandbox when the task finishes.
Prerequisites
- Node.js 22.13.0 or later
- An E2B API key
- An API key for a model provider supported by Mastra
Create the project
Create a new Node.js project and install Mastra, the E2B workspace provider, and their required dependencies:Build the coding agent
Create anindex.ts file:
index.ts
execute_command workspace tool, while @mastra/e2b routes those commands to the E2B sandbox through the JavaScript E2B SDK. Under the hood, workspace initialization creates or reconnects to a sandbox, command tools use E2B command execution, and workspace destruction kills the sandbox.
The id option is Mastra’s logical identifier, stored in E2B metadata so the provider can find the same sandbox again. The provider manages the native E2B sandbox ID for you. This one-shot example includes a timestamp so concurrent runs receive separate sandboxes.
A workspace configured with only a sandbox provides command execution tools, not Mastra’s dedicated
read_file or write_file tools. This example uses shell commands to work with files. To add dedicated file tools backed by shared cloud storage, configure an S3, GCS, or Azure Blob mount in the workspace.Run the agent
Run the default task:finally block calls workspace.destroy() so the sandbox is cleaned up even if the agent fails.
Use a custom template
For repeatable environments and faster startup, pre-install your runtimes and dependencies in an E2B template, then pass its ID or name toE2BSandbox: