# Vercel AI SDK tools backed by a Sandscale sandbox

> A TypeScript integration guide: three AI SDK tools (run_command, write_file, read_file) that act on one Firecracker sandbox per task, with output caps, path checks, a step limit and a guaranteed stop.

A TypeScript integration guide: three AI SDK tools (run_command, write_file, read_file) that act on one Firecracker sandbox per task, with output caps, path checks, a step limit and a guaranteed stop.

November 27, 2026 · 5 min read · The Sandscale team

The [Vercel AI SDK](https://ai-sdk.dev/docs/ai-sdk-core/tools-and-tool-calling) gives you `tool()` and `generateText()`, and the model decides when to call your tools. What the tools touch is up to you. For a tool that runs commands the model wrote, the answer should not be the process your app runs in. This guide wires AI SDK tools to a Sandscale sandbox, so each task gets its own Firecracker microVM and nothing the model runs can reach your server.

The AI SDK facts here are from its docs and the `ai` 7.x type definitions as of November 2026. The Sandscale calls are from the [TypeScript SDK reference](https://sandscale.dev/docs/sdks/typescript). The code type-checks against `ai`, `zod` 4 and `@sandscale/sdk`.

## The shape of it

One sandbox per task, not per tool call. The model will run the tests, edit a file, and run the tests again; those three calls need to see the same files. So the function that handles a task:

1. creates a sandbox from a template, with a timeout,
2. writes the project files in,
3. defines tools that close over that sandbox’s id and region,
4. lets the model loop with a step limit,
5. stops the sandbox in a `finally`, whatever happened.

The sandbox’s own `timeoutSeconds` is the second line of defence. If your process crashes between steps 1 and 5, the sandbox still stops when its time runs out.

## The code

```ts
import { generateText, tool, isStepCount } from 'ai';
import { z } from 'zod';
import { Sandscale } from '@sandscale/sdk';

const sandscale = new Sandscale(); // reads SANDSCALE_API_KEY

const MAX_OUTPUT = 8_000;
const clip = (s: string) =>
  s.length > MAX_OUTPUT ? s.slice(0, MAX_OUTPUT) + `\n[cut ${s.length - MAX_OUTPUT} chars]` : s;

export async function fixFailingTest(task: string, files: Record<string, string>) {
  const box = await sandscale.sandboxes.create({
    template: 'builtin:node',
    timeoutSeconds: 1800,
    labels: { app: 'ai-sdk-agent' },
  });
  const region = box.region;

  try {
    for (const [path, content] of Object.entries(files)) {
      const dir = path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : '';
      if (dir) await sandscale.sandboxes.run(box.id, ['mkdir', '-p', `/workspace/${dir}`], { region });
      await sandscale.sandboxes.writeFile(box.id, `/workspace/${path}`, content, { region });
    }

    const tools = {
      run_command: tool({
        description:
          'Run a shell command in an isolated Linux sandbox. The project is in /workspace. ' +
          'The sandbox has no network unless your plan and policy allow it. ' +
          'Each command may run for up to 120 seconds. Output over 8,000 characters is cut.',
        inputSchema: z.object({
          command: z.string().max(2_000).describe('A shell command, run with sh -c'),
          timeout_seconds: z.number().int().min(1).max(120).default(60),
        }),
        execute: async ({ command, timeout_seconds }) => {
          const run = await sandscale.sandboxes.run(box.id, ['sh', '-c', command], {
            region,
            timeoutSeconds: timeout_seconds,
          });
          return {
            exit_code: run.exitCode,
            timed_out: run.timedOut,
            oom_killed: run.oomKilled,
            stdout: clip(run.stdout),
            stderr: clip(run.stderr),
          };
        },
      }),
      write_file: tool({
        description: 'Write a text file under /workspace in the sandbox, replacing it if it exists.',
        inputSchema: z.object({
          path: z.string().regex(/^[\w./-]+$/).describe('Path relative to /workspace'),
          content: z.string().max(100_000),
        }),
        execute: async ({ path, content }) => {
          if (path.includes('..')) return { error: 'path must stay inside /workspace' };
          await sandscale.sandboxes.writeFile(box.id, `/workspace/${path}`, content, { region });
          return { ok: true };
        },
      }),
      read_file: tool({
        description: 'Read a text file under /workspace in the sandbox.',
        inputSchema: z.object({ path: z.string().regex(/^[\w./-]+$/) }),
        execute: async ({ path }) => {
          if (path.includes('..')) return { error: 'path must stay inside /workspace' };
          const bytes = await sandscale.sandboxes.readFile(box.id, `/workspace/${path}`, { region });
          return { content: clip(new TextDecoder().decode(bytes)) };
        },
      }),
    };

    const result = await generateText({
      model: 'anthropic/claude-sonnet-5.5',
      system:
        'You fix failing tests. Work only through the tools. Run the tests first, ' +
        'make the smallest change that fixes them, run them again, then summarise the diff.',
      prompt: task,
      tools,
      stopWhen: isStepCount(20),
    });

    return { summary: result.text, steps: result.steps.length };
  } finally {
    await sandscale.sandboxes.stop(box.id, { region });
  }
}
```

## Why each piece is there

**Tool descriptions say what the environment is.** The model reads them on every call. Telling it the project is in `/workspace`, that output is cut past a limit, and how long a command may run prevents a lot of wasted steps. The network line matters too: the SDK’s `network` option defaults to `none`, and `allowlist` uses your organization’s egress allowlist where your plan includes it. If the model thinks it has the internet, it will try `npm install` and be confused when it fails.

**`sh -c` and a timeout per call.** `sandboxes.run` takes an argv array or a string. Passing `['sh', '-c', command]` makes it explicit that the model’s input is a shell command, which is what it will write anyway. `timeoutSeconds` on the run (the SDK default is 60) bounds each command; the model may ask for up to 120 here because the schema says so.

**Structured results.** `RunResult` carries `exitCode`, `timedOut` and `oomKilled` as well as the output. Passing those through lets the model tell “the test failed” from “the test was killed for memory” from “it hung”, which lead to very different next steps.

**Output caps.** A failing test suite can print a lot. Cutting at a fixed size and saying how much was cut keeps the context window for reasoning, not for log noise. [Truncating tool output for LLMs](https://sandscale.dev/blog/truncating-tool-output-for-llms) goes into how to choose what to keep.

**Path checks in code, not only in the schema.** The `regex` in the schema guides the model. The `..` check in `execute` is what actually holds. Schemas describe; handlers enforce.

**A step limit.** `stopWhen: isStepCount(20)` ends the loop after 20 steps even if the model would keep going. Without it, a model stuck on a test it cannot fix will keep trying.

**`finally` stops the sandbox.** Every path out of the function, including a thrown error from the model provider, stops the box. That is what keeps cost tied to the task.

## Adding a human in the loop

The AI SDK has a `toolApproval` option on `generateText` and `streamText`. Setting `toolApproval: { write_file: 'user-approval' }` makes the SDK return a `tool-approval-request` instead of running the tool, and your app sends the person’s answer back in a second call. The AI SDK docs note that `generateText` does not pause; it finishes and returns the request. For an unattended job you usually do not want this. For an assistant a person is watching, gating `write_file` is a reasonable middle ground: commands run freely in the sandbox, but changes to the project need a yes.

## What about experimental_sandbox?

AI SDK 7 has an `experimental_sandbox` option that passes a sandbox session object to your tools. Its docs are direct about it: passing one does not sandbox the tool itself, the SDK does not create or isolate a sandbox for you, and the isolation depends on the implementation behind it. The plain approach above makes the boundary explicit: your tool code runs in your app, and only the commands it sends to Sandscale run in the microVM. If you adopt the experimental interface later, the same Sandscale calls sit behind it.

## Going further

- **Snapshots for dependencies.** If every task needs `npm ci`, run it once, take a snapshot with `sandboxes.snapshot`, and start each task with `create({ snapshotId })`. The [snapshots guide](https://sandscale.dev/docs/guides/snapshots) covers what a snapshot keeps.
- **Labels for tracing.** The `labels` on `create` are how you find this task’s sandbox later. [Labels and run records](https://sandscale.dev/blog/labels-and-run-records-for-traceability) shows a labelling scheme.
- **Streaming output.** `sandboxes.run` accepts `onStdout` and `onStderr` for live output, useful if a person is watching. [Streaming sandbox output](https://sandscale.dev/blog/streaming-sandbox-output-typescript) covers it.

The Free plan includes 100 awake vCPU-hours a month, 3 boxes at once and up to 2 vCPU per box, which is enough to build and test this. See [pricing](https://sandscale.dev/pricing) for the rest.

**On this page**

1. The shape of it
2. The code
3. Why each piece is there
4. Adding a human in the loop
5. What about experimental_sandbox?
6. Going further

**Run your agents in a box of their own**

Each sandbox is a Firecracker microVM. Free includes 100 awake vCPU-hours a month.

[Start free](https://cloud.sandscale.dev/auth/signup)

## Keep reading

- [November 27, 2026 · **A LlamaIndex.TS data agent that runs its Python in a Sandscale sandbox** · Use LlamaIndex.TS's agent workflow with tools that write and run Python in a Firecracker sandbox, built per sandbox so a run can only reach its own box. Upload data files, answer with the numbers, clean up. Type-checked.](https://sandscale.dev/blog/llamaindex-ts-agent-with-sandscale)
- [November 27, 2026 · **Adding the Sandscale MCP server to Codex: config.toml, OAuth login and approval modes** · Configure the remote or local Sandscale MCP server in OpenAI Codex, sign in with codex mcp login, and use enabled_tools, approval modes and tool timeouts to match what each tool does.](https://sandscale.dev/blog/sandscale-mcp-server-in-codex)

---
Source: https://sandscale.dev/blog/vercel-ai-sdk-tools-on-sandscale
