> ## Documentation Index
> Fetch the complete documentation index at: https://onecli.sh/docs/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Setting OneCLI up for your person? Follow https://onecli.sh/docs/quickstart.md. Never ask for or accept a key, token or password in the chat: OneCLI needs none.
> No OneCLI credential? Run `onecli connect`, or follow https://onecli.sh/auth.md. A person approves every new agent in their browser.
> Already connected? `onecli status`, `onecli items` and `onecli check <METHOD> <URL>` tell you what you can use. Full guide: https://onecli.sh/skill.md
> Search these docs over MCP at https://onecli.sh/docs/mcp. Report a wrong or unclear page with its `submit_feedback` tool.

# Connect an agent in a Modal sandbox

> Start a Modal sandbox from TypeScript or Python with its own OneCLI agent: the agent's settings, an outbound policy for OneCLI, and no key inside it.

Your code starts a Modal sandbox and makes a OneCLI agent for it, on one vault. The sandbox can reach only OneCLI. Its HTTPS calls go through the gateway, which adds the vault's key on the way out, so no key is ever in the sandbox.

> [!NOTE]
>
> Modal's JavaScript SDK is in beta.

## Before you start

* A OneCLI managing key in `ONECLI_API_KEY`. Make one in the dashboard under **Settings** > **API keys**. It stays with your code: never put it in the sandbox.
* Modal credentials in `MODAL_TOKEN_ID` and `MODAL_TOKEN_SECRET`, or in `~/.modal.toml`.
* Node.js 22 or later, or Python 3.11 or later.
* The example uses your **Personal** vault and its **Test key** for `httpbin.org`, which every account starts with. Use any vault, and any host it has an item for.

## Install

```bash TypeScript theme={null}
npm install @onecli-sh/sdk modal
```

```bash Python theme={null}
pip install onecli-sdk modal
```

## Example

Save the TypeScript as `sandbox.mts` and run `npx tsx sandbox.mts`, or the Python as `sandbox.py` and run `python sandbox.py`. It prints `200`.

```typescript TypeScript theme={null}
import { OneCLI } from "@onecli-sh/sdk";
import { ModalClient, OutboundPolicy, OutboundRoute } from "modal";

const onecli = new OneCLI(); // reads ONECLI_API_KEY
const modal = new ModalClient(); // reads MODAL_TOKEN_ID and MODAL_TOKEN_SECRET

// 1. An agent on your Personal vault. It ends by itself after an hour.
const agent = await onecli.agents.create({
  vaultName: "Personal",
  provider: "modal",
  ttlSeconds: 3600,
});

// 2. The sandbox: an image with curl, the agent's settings,
//    and a network to OneCLI only.
const app = await modal.apps.fromName("onecli-sandboxes", {
  createIfMissing: true,
});
const image = modal.images
  .fromRegistry("debian:bookworm-slim")
  .dockerfileCommands([
    "RUN apt-get update",
    "RUN apt-get install -y --no-install-recommends curl ca-certificates",
  ]);
const sandbox = await modal.sandboxes.create(app, image, {
  env: agent.env,
  outboundPolicy: new OutboundPolicy({
    routes: [
      OutboundRoute.tls({ domains: agent.allowHosts }),
      OutboundRoute.any().block(),
    ],
  }),
  timeoutMs: 3600 * 1000,
});

// Run one shell line and return what it printed.
const run = async (line: string): Promise<string> => {
  const proc = await sandbox.exec(["sh", "-c", line]);
  const [output, exitCode] = await Promise.all([
    proc.stdout.readText(),
    proc.wait(),
  ]);
  if (exitCode !== 0) throw new Error(`exit code ${exitCode}: ${line}`);
  return output;
};

try {
  // 3. Once: write the certificate files that agent.env points at.
  await run(agent.setupCommand);

  // httpbin.org/bearer answers 401 with no key.
  // 200 means the gateway added the Test key.
  const call =
    'curl -s -o /dev/null -w "%{http_code}" https://httpbin.org/bearer';
  console.log(await run(call)); // 200
} finally {
  await sandbox.terminate();
  await agent.disconnect();
}
```

```python Python theme={null}
import modal
from onecli import OneCLI

with OneCLI() as onecli:  # reads ONECLI_API_KEY
    # 1. An agent on your Personal vault. It ends by itself after an hour,
    #    and leaving the block disconnects it.
    with onecli.agents.create(
        vault_name="Personal",
        provider="modal",
        ttl_seconds=3600,
    ) as agent:
        # 2. The sandbox: an image with curl, the agent's settings,
        #    and a network to OneCLI only. Modal reads its own credentials.
        app = modal.App.lookup("onecli-sandboxes", create_if_missing=True)
        image = modal.Image.debian_slim().apt_install("curl", "ca-certificates")
        sandbox = modal.Sandbox.create(
            app=app,
            image=image,
            env=dict(agent.env),
            outbound_policy=modal.OutboundPolicy(
                routes=[
                    modal.OutboundRoute.tls(domains=agent.allow_hosts),
                    modal.OutboundRoute.any().block(),
                ]
            ),
            timeout=3600,
        )

        def run(line: str) -> str:
            """Run one shell line and return what it printed."""
            proc = sandbox.exec("sh", "-c", line)
            output = proc.stdout.read()
            exit_code = proc.wait()
            if exit_code != 0:
                raise RuntimeError(f"exit code {exit_code}: {line}")
            return output

        try:
            # 3. Once: write the certificate files that agent.env points at.
            run(agent.setup_command)

            # httpbin.org/bearer answers 401 with no key.
            # 200 means the gateway added the Test key.
            call = 'curl -s -o /dev/null -w "%{http_code}" https://httpbin.org/bearer'
            print(run(call))  # 200
        finally:
            sandbox.terminate()
```

## What goes where

> [tab] TypeScript
>
> | OneCLI | Modal |
> | - | - |
> | `agent.env` | `env` in `modal.sandboxes.create` |
> | `agent.allowHosts` | `outboundPolicy`: one `OutboundRoute.tls` route for the hosts, then `OutboundRoute.any().block()` |
> | `agent.setupCommand` | `sandbox.exec(["sh", "-c", ...])`, once. Check the exit code from `wait()`. |
> | Stop | `sandbox.terminate()`, then `agent.disconnect()` |

> [tab] Python
>
> | OneCLI | Modal |
> | - | - |
> | `agent.env` | `env` in `modal.Sandbox.create`. `dict(agent.env)` matches the type in Modal's type hints. |
> | `agent.allow_hosts` | `outbound_policy`: one `OutboundRoute.tls` route for the hosts, then `OutboundRoute.any().block()` |
> | `agent.setup_command` | `sandbox.exec("sh", "-c", ...)`, once. Check the exit code from `wait()`. |
> | Stop | `sandbox.terminate()`, then leaving the `with` block disconnects the agent |

The [Sandboxes overview](https://onecli.sh/docs/guides/sandboxes#how-it-works) explains each value.

## Good to know

* **The image needs `curl`.** Slim images, such as `debian:bookworm-slim` and Modal's `debian_slim`, lack it, so the example adds `curl` and `ca-certificates`. Modal builds the image the first time.
* **A `tls` route, not `https`.** A `tls` route matches by host name on port 443 and never decrypts the connection, which is what the gateway needs.
* **Lifetime.** A Modal sandbox lives 5 minutes unless you set `timeoutMs` in TypeScript, or `timeout` in seconds in Python, up to 24 hours. Keep the agent's lifetime at least as long.
* **Node clients.** Behind an allow list, Node's `http` and `https` modules and axios fail, because they send no host name to the gateway. Give them `agent.baseUrl(host)` instead, or `agent.base_url(host)` in Python. See the SDK reference for [TypeScript](https://onecli.sh/docs/sdks/node.md#a-client-that-cannot-use-a-proxy) or [Python](https://onecli.sh/docs/sdks/python.md#a-client-that-cannot-use-a-proxy).
* **Modal's own key injection.** Modal can also add a key to a sandbox's calls itself, with header replacements on its `https` routes, in beta. See [how OneCLI compares](https://onecli.sh/docs/guides/sandboxes#why-onecli-when-a-provider-injects-keys).

## From a terminal

Modal sandboxes are made from code, so use the example above. For a sandbox of another provider, see [From a terminal](https://onecli.sh/docs/guides/sandboxes#from-a-terminal).

## Versions

Written in December 2026 for `@onecli-sh/sdk` 4.1 and `modal` 0.12 in TypeScript, and for `onecli-sdk` 0.1 and `modal` 1.7 in Python.

## Next steps

* [All sandbox providers](https://onecli.sh/docs/guides/sandboxes)
* [An agent for a sandbox, in the TypeScript SDK reference](https://onecli.sh/docs/sdks/node.md#an-agent-for-a-sandbox)
* [An agent for a sandbox, in the Python SDK reference](https://onecli.sh/docs/sdks/python.md#an-agent-for-a-sandbox)
* [Set what agents may do with each item](https://onecli.sh/docs/guides/agent-access.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.