Skip to main content
Mastra is a TypeScript framework for building AI agents and workflows. The @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:
  1. Starts an E2B sandbox through Mastra’s workspace API.
  2. Creates and tests a small project inside the sandbox.
  3. Streams its progress to your terminal.
  4. Destroys the sandbox when the task finishes.

Prerequisites

This guide uses OpenAI, but you can replace the model with any model supported by Mastra.

Create the project

Create a new Node.js project and install Mastra, the E2B workspace provider, and their required dependencies:
Set your E2B and model provider API keys:

Build the coding agent

Create an index.ts file:
index.ts
The Mastra agent runs in your local Node.js process. Mastra automatically gives it an 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:
Or pass your own coding task:
The first workspace initialization creates the E2B sandbox. The agent can then install packages, create files, run commands, and start background processes entirely inside the sandbox. The 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 to E2BSandbox:
Use templates when every agent run needs the same language toolchain, system packages, or repository bootstrap files.

How the integration works

Learn more