> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.modbox.run/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.modbox.run/_mcp/server.

# Provision a sandbox

POST /sandboxes/provision
Content-Type: application/json

Creates a sandbox and returns immediately with a `sandbox_id` — the container boots in the background, so the sandbox is **not** usable yet when this call returns.

Next step: call `POST /sandboxes/wait` to block until it is ready, or poll `GET /sandboxes/detail/{sandbox_id}` until `status` is `running`. The `sandbox_url` is only populated once the sandbox is running.

Supply either `image_id` (a registered image, recommended) or `image` (a raw Docker reference). Set `ttl_seconds` so the sandbox is reclaimed automatically even if the caller crashes.

Reference: https://docs.modbox.run/api-reference/modbox-api/sandboxes/provision-sandbox

## Authentication

- `Authorization` header (bearer token, required) — Bearer authentication of the form `Bearer <token>`, where token is your auth token.

## Request

### Headers

- `x-workspace-id` (string, optional, nullable) — UUID of the workspace that scopes this request. List the workspaces you belong to with GET /workspaces.

### Body (application/json)

This endpoint expects a ProvisionRequest.

- `task_id` (string, required) — Your unique name for this sandbox. Reuse it to destroy, wait on or query the sandbox later. Must be unique among live sandboxes — a UUID or a per-session id works well.
- `image` (string, optional, nullable) — Raw Docker image reference. Prefer `image_id`, which also carries memory, TTL and readiness settings. Ignored when `image_id` is set.
- `image_id` (string, optional, nullable) — Id of a registered image from `GET /sandbox-images`. Recommended: it applies the image's memory, readiness and TTL defaults, and handles private-registry authentication. If neither `image_id` nor `image` is supplied, the deployment's default image is used — pass one explicitly for reproducibility.
- `env_vars` (map from string to string, optional, nullable) — Environment variables injected into the container. Use this to pass configuration, or the standard HTTP_PROXY/HTTPS_PROXY variables to route egress through a proxy.
- `ttl_seconds` (integer, optional, nullable) — Destroy the sandbox automatically after this many seconds (60–86400). Overrides the image default. Always set this for agent workloads so a crashed caller cannot leak resources.

## Response

### 200

Successful Response

- `success` (boolean, required) — True when the sandbox was accepted for provisioning.
- `endpoint` (SandboxEndpoint, optional, nullable) — Where to reach the sandbox and the token to authenticate with. The URL is known immediately, but only answers once `status` is `running`.
- `capabilities` (map from string to string, optional, nullable) — Absolute URLs for what this sandbox exposes, keyed by capability (`exec`, `files`, and depending on the image `terminal`, `vnc`, `cdp`, `mcp`). Read this instead of assuming paths — they differ between images.
- `sandbox_id` (string, optional, nullable) — Id of the new sandbox. Poll `GET /sandboxes/detail/{sandbox_id}` with it.
- `status` (string, optional, default: provisioning) — Lifecycle state at the time of the response. Always `provisioning` here — the container is still booting.
- `sandbox_url` (string, optional, nullable) — Public URL of the sandbox. Null until the status becomes `running` — read it from `GET /sandboxes/detail/{sandbox_id}`.
- `error` (string, optional, nullable) — Failure reason when `success` is false.

## Errors

### 400 Bad Request Error

Bad request — the parameters are invalid.

- `error` (ErrorBody, required) — Machine-readable description of a failure.
- `detail` (string, optional, nullable) — DEPRECATED — mirrors 'error.message' for backwards compatibility. Read 'error.code' instead.

### 401 Unauthorized Error

Unauthenticated — the Bearer token is missing or invalid.

- `error` (ErrorBody, required) — Machine-readable description of a failure.
- `detail` (string, optional, nullable) — DEPRECATED — mirrors 'error.message' for backwards compatibility. Read 'error.code' instead.

### 403 Forbidden Error

Forbidden — the caller lacks permission for this resource.

- `error` (ErrorBody, required) — Machine-readable description of a failure.
- `detail` (string, optional, nullable) — DEPRECATED — mirrors 'error.message' for backwards compatibility. Read 'error.code' instead.

### 404 Not Found Error

Not found — no such resource in this workspace.

- `error` (ErrorBody, required) — Machine-readable description of a failure.
- `detail` (string, optional, nullable) — DEPRECATED — mirrors 'error.message' for backwards compatibility. Read 'error.code' instead.

### 422 Unprocessable Entity Error

Validation error — see 'error.details' for the offending fields.

- `error` (ErrorBody, required) — Machine-readable description of a failure.
- `detail` (string, optional, nullable) — DEPRECATED — mirrors 'error.message' for backwards compatibility. Read 'error.code' instead.

## Types

### SandboxEndpoint

How to reach the sandbox runtime API once the sandbox is running.

- `base_url` (string, required) — Public base URL of the sandbox.
- `api_url` (string, required) — Base URL of the sandbox runtime API (exec and files).
- `access_token` (string, optional, nullable) — Credential for the sandbox runtime API, sent as 'Authorization: Bearer \<token>'. **Returned only once, when the sandbox is created.** It is not included in any later response — store it with the sandbox id.

### ErrorBody

Machine-readable description of a failure.

- `code` (enum, required) — Stable identifier for this class of failure. Branch on this value instead of parsing 'message'.
  - Allowed values: `unauthenticated`, `invalid_token`, `invalid_credentials`, `email_not_verified`, `forbidden`, `insufficient_role`, `workspace_required`, `workspace_forbidden`, `workspace_not_found`, `member_not_found`, `sandbox_not_found`, `sandbox_name_conflict`, `sandbox_not_ready`, `provisioning_failed`, `image_not_found`, `image_disabled`, `image_immutable`, `registry_not_found`, `api_key_not_found`, `validation_error`, `not_found`, `conflict`, `rate_limited`, `internal_error`, `upstream_error`
- `message` (string, required) — Human-readable explanation of what went wrong.
- `hint` (string, optional, nullable) — Concrete next step that is likely to resolve the error.
- `docs_url` (string, optional, nullable) — Link to the documentation section for this error code.
- `retryable` (boolean, optional, default: false) — True when retrying the identical request may succeed (transient failure). False means the request must change first.
- `request_id` (string, optional, nullable) — Correlation id, also returned in the 'X-Request-Id' header.
- `details` (list of ErrorDetail, optional, nullable) — Field-level problems, present on validation errors.

### ErrorDetail

A single field-level problem, typically from request validation.

- `issue` (string, required) — Human-readable description of what is wrong with this field.
- `field` (string, optional, nullable) — Dotted path to the offending field, e.g. 'body.task_id'.

## Examples

**Request**

```json
{
  "task_id": "agent-session-42"
}
```

**Response**

```json
{
  "success": true,
  "endpoint": {
    "base_url": "https://sandbox-3fa85f64.sandbox.modbox.run",
    "api_url": "https://sandbox-3fa85f64.sandbox.modbox.run/api",
    "access_token": "string"
  },
  "capabilities": {
    "exec": "https://sandbox-3fa85f64.sandbox.modbox.run/api/exec/",
    "files": "https://sandbox-3fa85f64.sandbox.modbox.run/api/files"
  },
  "sandbox_id": "string",
  "status": "provisioning",
  "sandbox_url": "string",
  "error": "string"
}
```

**SDK Code**

```python
import requests

url = "https://api.example.com/sandboxes/provision"

payload = { "task_id": "agent-session-42" }
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript
const url = 'https://api.example.com/sandboxes/provision';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"task_id":"agent-session-42"}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.example.com/sandboxes/provision"

	payload := strings.NewReader("{\n  \"task_id\": \"agent-session-42\"\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby
require 'uri'
require 'net/http'

url = URI("https://api.example.com/sandboxes/provision")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"task_id\": \"agent-session-42\"\n}"

response = http.request(request)
puts response.read_body
```

```java
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.example.com/sandboxes/provision")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"task_id\": \"agent-session-42\"\n}")
  .asString();
```

```php
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.example.com/sandboxes/provision', [
  'body' => '{
  "task_id": "agent-session-42"
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp
using RestSharp;

var client = new RestClient("https://api.example.com/sandboxes/provision");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"task_id\": \"agent-session-42\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = ["task_id": "agent-session-42"] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.example.com/sandboxes/provision")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```