Connect E2B to ChatGPT: Run Secure Code & Isolated Sandboxes
Learn how to connect E2B to ChatGPT using a managed MCP server. This guide covers sandbox automation, secure code execution, and bypassing API constraints.
If you need to connect E2B to ChatGPT to spin up dynamic microVMs, execute secure code, and automate isolated filesystems, you need a Model Context Protocol (MCP) server. This server acts as the translation layer between ChatGPT's function calls and E2B's REST APIs. (If your team uses Claude instead, check out our guide on connecting E2B to Claude, or explore our broader architectural overview on connecting E2B to AI Agents).
ChatGPT's native Advanced Data Analysis tool is highly restricted. It lacks network access, limits the packages you can install, and operates in a black box. E2B solves this by providing customizable, cloud-hosted sandboxes tailored for AI agents. However, giving a Large Language Model (LLM) raw API access to deploy compute instances is an engineering challenge. You have to handle execution state, strict sandbox lifecycles, and streaming process outputs.
You can either spend weeks building and maintaining custom infrastructure, or use a managed integration layer to dynamically generate a secure, authenticated MCP server URL. This guide breaks down exactly how to use Truto to generate a managed MCP server for E2B, connect it natively to ChatGPT, and execute complex code workflows using natural language.
The Engineering Reality of the E2B API
A custom MCP server is a self-hosted API layer. While the open MCP standard provides a predictable way for models to discover tools, the reality of implementing it against a compute orchestration API is painful. You are not just dealing with generic CRUD operations. You are managing ephemeral virtual machines, persistent network storage, and remote shell executions.
If you decide to build a custom MCP server for E2B, you own the entire lifecycle. Here are the specific integration challenges you must solve:
The Ephemeral Sandbox Lifecycle (TTLs)
E2B sandboxes are not permanent servers. They are ephemeral microVMs governed by strict Time-To-Live (TTL) policies. If an LLM initiates a long-running data processing script, takes three minutes to evaluate the output, and then tries to run a secondary command, the sandbox might have already terminated. A custom integration must constantly manage this state, forcing the LLM to call refresh endpoints (e_2_b_sandboxes_refresh) to extend the TTL, or risk losing the entire filesystem mid-execution.
Handling Rate Limits and 429s Gracefully
E2B enforces API rate limits to prevent runaway compute costs. If an AI agent attempts to spawn 50 concurrent sandboxes to parallelize a task, it will hit rate limits. It is critical to note that Truto does not retry, throttle, or apply backoff on rate limit errors. When the upstream E2B API returns an HTTP 429, Truto passes that error directly to the caller, normalizing the upstream rate limit info into standardized IETF headers (ratelimit-limit, ratelimit-remaining, ratelimit-reset). Your client, or the LLM prompt itself, is entirely responsible for reading these headers and executing exponential backoff. If your custom server absorbs these errors improperly, the LLM will hallucinate successful code execution.
Stateful Process Streams and Filesystem Syncing When you start a process in E2B, the output does not always return synchronously in a simple JSON response. You are interacting with pseudoterminals (PTYs). If your LLM expects a synchronous response but the E2B process requires streaming inputs or detaches into the background, the agent loses context. Your MCP translation layer must effectively map E2B's remote execution model into a flat, stringified response format that ChatGPT can parse as tool outputs.
Step 1: Generate the E2B MCP Server
Instead of building this orchestration layer from scratch, Truto dynamically derives MCP tools directly from E2B's API documentation and resource schemas. This guarantees that your AI tools never fall out of sync with E2B's API updates.
Each MCP server is scoped to a single integrated account (your specific E2B tenant). The server URL contains a cryptographic token that handles all authentication routing. You can generate this server in two ways.
Method 1: Via the Truto UI
For teams moving quickly, you can generate the MCP server directly from your dashboard:
- Navigate to the Integrated Accounts page in Truto.
- Select your connected E2B integration.
- Click the MCP Servers tab.
- Click Create MCP Server.
- Select your desired configuration (e.g., limit to read operations, or specific sandbox tags).
- Copy the generated MCP server URL.
Method 2: Via the Truto API
For platform engineers building multi-tenant AI products, you can provision MCP servers programmatically for your users.
Make an authenticated POST request to the /integrated-account/:id/mcp endpoint:
curl -X POST https://api.truto.one/integrated-account/YOUR_ACCOUNT_ID/mcp \
-H "Authorization: Bearer YOUR_TRUTO_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "E2B ChatGPT Orchestrator",
"config": {
"methods": ["read", "write", "custom"]
}
}'The API returns a database record and a ready-to-use secure URL:
{
"id": "mcp_abc123",
"name": "E2B ChatGPT Orchestrator",
"config": { "methods": ["read", "write", "custom"] },
"expires_at": null,
"url": "https://api.truto.one/mcp/t_a1b2c3d4e5f6..."
}Step 2: Connect the MCP Server to ChatGPT
Once you have the Truto MCP URL, you must register it with ChatGPT. The URL acts as the definitive connection string - no local node servers or complex OAuth flows are required on the client side.
Method A: Via the ChatGPT UI
If you are using ChatGPT Enterprise, Team, or Plus accounts with Developer mode enabled:
- In ChatGPT, navigate to Settings -> Apps -> Advanced settings.
- Ensure Developer mode is toggled on.
- Under MCP servers / Custom connectors, click Add.
- Provide a Name (e.g., "E2B Sandboxes").
- Paste the Truto MCP URL into the Server URL field.
- Click Save.
ChatGPT will immediately handshake with the URL, pulling down the full list of E2B tools.
Method B: Via Manual Configuration File (SSE Transport)
If you are running a custom ChatGPT desktop client wrapper or an agent framework that mimics ChatGPT's UI, you can inject the server using a standard JSON config file. Because Truto MCP servers are remote endpoints, you connect using the Server-Sent Events (SSE) transport protocol.
{
"mcpServers": {
"e2b-sandbox-manager": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-sse",
"--url",
"https://api.truto.one/mcp/t_a1b2c3d4e5f6..."
]
}
}
}E2B Hero Tools for ChatGPT
Once connected, ChatGPT will map its reasoning engine to the available E2B functions. Truto handles the translation between a flat JSON-RPC request and the nested JSON required by E2B. Here are the highest-leverage tools available for your agent.
1. create_a_e_2_b_sandbox
This tool allows the agent to spin up a new, isolated microVM from a specific base template. The agent can configure environment variables and initial network rules dynamically.
"I need an isolated Python environment. Spin up a new E2B sandbox using the data-science template ID, set the timeout to 600 seconds, and pass in the database connection string as an environment variable."
2. e_2_b_process_start
This is the core execution engine. The agent passes shell commands or scripts into the running sandbox. The tool returns the standard output (stdout) and standard error (stderr) of the process.
"In the sandbox you just created, run
pip install pandas scikit-learnand return the installation logs. If it succeeds, execute thetrain_model.pyscript in the root directory."
3. e_2_b_filesystem_upload_file
Agents use this tool to write generated code or data directly to the sandbox filesystem. If the parent directories do not exist, E2B creates them automatically.
"Write the following 300-line React component into a file called
App.tsxand upload it to the/home/user/project/srcdirectory in the sandbox."
4. e_2_b_sandboxes_refresh
Because E2B sandboxes are ephemeral, an agent executing a complex, multi-step pipeline must keep the environment alive. This tool extends the Time-To-Live (TTL) up to 3600 seconds per call.
"The model training script is going to take a while. Ping the sandbox refresh endpoint to extend the timeout by another 3000 seconds so it doesn't shut down while we wait."
5. e_2_b_sandboxes_create_snapshot
If the agent has successfully configured a complex environment (e.g., installed 50 custom dependencies and downloaded large datasets), it can persist that state into a snapshot. Future sandboxes can be instantly booted from this snapshot.
"We finished setting up the complex Rust build environment. Create a persistent snapshot of this sandbox and assign it the alias
rust-build-env-v1so we can reuse it later."
6. delete_a_e_2_b_sandbox_by_id
Cost control is critical. Agents should be instructed to explicitly kill sandboxes as soon as their task is complete rather than waiting for the TTL to expire.
"The vulnerability scan is complete, and I have saved the results to our internal database. Please delete sandbox ID
sbx-889900to stop billing."
To view the exact JSON Schema for every available E2B endpoint, review the E2B Integration Page.
Workflows in Action
Giving ChatGPT access to E2B transforms it from a chatbot into an autonomous DevOps engineer and data scientist. Here is how specific workflows execute in production.
Scenario 1: Automated Vulnerability Testing on a Custom Repo
A security engineer wants to test an untrusted open-source repository for common exploits without risking local hardware.
"Spin up a new E2B sandbox. Clone the repo at github.com/example/untrusted-app. Run a static analysis security tool over the codebase, output the report to a text file, download the results for me to read, and then instantly kill the sandbox."
Step-by-step execution:
create_a_e_2_b_sandbox: ChatGPT provisions a base Ubuntu environment.e_2_b_process_start: Executesgit cloneto pull down the repository.e_2_b_process_start: Runs the static analysis tool (e.g.,banditorsemgrep) and pipes the output toreport.txt.e_2_b_filesystem_download_file: Readsreport.txtback into the LLM's context window.delete_a_e_2_b_sandbox_by_id: Terminates the microVM immediately.
The engineer gets a summarized security report in the chat interface, knowing the code was executed in an entirely isolated network boundary.
sequenceDiagram participant User participant Agent as ChatGPT participant Truto as Truto MCP participant E2B as E2B API User->>Agent: "Test this untrusted repo..." Agent->>Truto: call create_a_e_2_b_sandbox Truto->>E2B: POST /sandboxes E2B-->>Truto: sandboxID: "sbx-123" Truto-->>Agent: sandboxID: "sbx-123" Agent->>Truto: call e_2_b_process_start (git clone) Truto->>E2B: POST /sandboxes/sbx-123/process E2B-->>Truto: success Truto-->>Agent: stdout: "Cloning into..." Agent->>Truto: call delete_a_e_2_b_sandbox_by_id Truto->>E2B: DELETE /sandboxes/sbx-123 E2B-->>Truto: 204 No Content
Scenario 2: Orchestrating an Ephemeral Data Pipeline
A data analyst needs to process a massive CSV file using a specific Python library that is not available in ChatGPT's default Code Interpreter.
"I need to process this custom telemetry data. Spin up a data-science sandbox, upload this raw dataset, run a Python script to group by user ID and calculate averages, and give me the final processed CSV."
Step-by-step execution:
create_a_e_2_b_sandbox: ChatGPT requests a sandbox using a pre-configured data science template ID.e_2_b_filesystem_upload_file: The agent chunks the raw dataset and streams it into the sandbox filesystem.e_2_b_filesystem_upload_file: The agent writes a custom Python aggregation script and saves it to the sandbox.e_2_b_process_start: Executes the Python script.e_2_b_sandboxes_refresh: During execution, the agent proactively extends the TTL to ensure the script does not die prematurely.e_2_b_filesystem_download_file: Retrieves the processed CSV and serves it back to the user.
Security and Access Control
Giving an LLM access to execute arbitrary code is inherently dangerous if not properly scoped. Truto provides multiple layers of defense at the MCP server level to ensure ChatGPT only performs authorized actions.
- Method Filtering: You can strictly limit the MCP server to only perform read operations (e.g., viewing logs or listing sandboxes) by passing
config: { methods: ["read"] }during creation. This ensures the LLM cannot accidentally delete infrastructure. - Tag Grouping: E2B resources are tagged logically. You can restrict an MCP server to only access
metricsortemplates, cutting off access to the core execution environment entirely. - Require API Token Auth: For internal engineering teams, you can enable
require_api_token_auth: true. This forces the ChatGPT client to pass a valid Truto API bearer token in the headers. URL possession alone is no longer enough to execute code. - Automatic Expiration: When generating an MCP server for a temporary agent deployment, pass an
expires_atISO datetime. Truto will automatically destroy the token and kill access exactly when the window closes, leaving zero stale credentials. - Integration Auth Isolation: The MCP server maps precisely to one E2B API key. Truto handles the credential management securely in its vault, ensuring the raw E2B token is never exposed to the LLM or the client application.
flowchart TD
A["ChatGPT Tool Call"] --> B{"Require API Token Auth?"}
B -->|"Yes"| C{"Valid Bearer Token?"}
B -->|"No"| D["Validate MCP Hash in KV"]
C -->|"No"| E["Reject Request (401)"]
C -->|"Yes"| D
D -->|"Expired"| E
D -->|"Valid"| F["Check Method Filters"]
F -->|"Allowed"| G["Execute Proxy API (E2B)"]
F -->|"Blocked"| H["Reject Request (403)"]Moving Fast Without Breaking Infrastructure
Connecting ChatGPT to E2B unlocks true agentic workflows. Instead of just writing code for you to copy and paste, the LLM can write the code, deploy the environment, execute the script, debug the errors, and return the final artifact.
Managing this orchestration layer in-house requires building TTL tracking, PTY stream parsing, and strict rate limit backoff handling. By generating an MCP server through a unified API architecture, you abstract away the API maintenance and focus strictly on the AI prompt logic. The endpoints update dynamically, the credentials stay locked in a vault, and the LLM operates within exactly the security boundary you define.
FAQ
- Does Truto automatically retry E2B rate limit errors?
- No. When the E2B API returns an HTTP 429 error, Truto passes that error directly to the caller and normalizes the rate limit information into standard IETF headers (ratelimit-limit, ratelimit-remaining, ratelimit-reset). Your application or LLM must handle its own retry and exponential backoff logic.
- Can I restrict which E2B sandboxes ChatGPT can access?
- Yes. Using method and tag filtering on the MCP token, you can restrict ChatGPT to only read operations or scope its access to specific E2B templates to ensure it only spins up approved sandbox environments.
- How do I connect the E2B MCP server to ChatGPT?
- You can connect via the ChatGPT UI by adding a custom connector in the settings, or by using a manual configuration file with the Model Context Protocol SSE transport.
- What happens if a sandbox times out while ChatGPT is thinking?
- E2B sandboxes have strict time-to-live (TTL) policies. You must explicitly prompt ChatGPT to call the sandbox refresh tool periodically to extend the TTL if it is executing long-running tasks or taking time to generate a complex response.