# Claude tool use with a Sandscale sandbox: the whole loop in one file

> A complete tool-use loop with the Anthropic TypeScript SDK where Claude's run_command and write_file calls execute in a Firecracker sandbox. Tool schemas, tool_result blocks with is_error, a turn limit and cleanup. Type-checked.

A complete tool-use loop with the Anthropic TypeScript SDK where Claude's run_command and write_file calls execute in a Firecracker sandbox. Tool schemas, tool_result blocks with is_error, a turn limit and cleanup. Type-checked.

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

Frameworks are optional. The Anthropic Messages API has tool use built in: you describe tools, Claude replies with `tool_use` blocks, you run them and send back `tool_result` blocks, and you repeat until Claude stops asking. This guide writes that loop by hand with the Anthropic TypeScript SDK, and runs every tool call in a [Sandscale sandbox](https://sandscale.dev/sandboxes) so the commands Claude chooses never run on your machine.

The code was type-checked with `tsc --strict` against `@anthropic-ai/sdk` 1.14 and `@sandscale/sdk` 1.0. Sandscale calls are from the [TypeScript SDK reference](https://sandscale.dev/docs/sdks/typescript).

## Install

```bash
npm install @anthropic-ai/sdk @sandscale/sdk
export ANTHROPIC_API_KEY=...
export SANDSCALE_API_KEY=...
export CLAUDE_MODEL=...   # the Claude model you use; the code has a default
```

## The code

```ts
import Anthropic from '@anthropic-ai/sdk';
import { Sandscale } from '@sandscale/sdk';

const anthropic = new Anthropic(); // reads ANTHROPIC_API_KEY
const sandscale = new Sandscale(); // reads SANDSCALE_API_KEY
const MODEL = process.env.CLAUDE_MODEL ?? 'claude-sonnet-4-5';

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

const tools: Anthropic.Tool[] = [
  {
    name: 'run_command',
    description:
      'Run a bash command in an isolated Linux sandbox, in /workspace. Files persist between calls in this ' +
      'conversation. There is no network access. Returns JSON with exit_code, timed_out, oom_killed, stdout ' +
      'and stderr; output over 8,000 characters is cut.',
    input_schema: {
      type: 'object',
      properties: {
        command: { type: 'string', description: 'The bash command to run.' },
        timeout_seconds: { type: 'integer', minimum: 1, maximum: 300 },
      },
      required: ['command'],
    },
  },
  {
    name: 'write_file',
    description: 'Write a text file in the sandbox. The path must be under /workspace/.',
    input_schema: {
      type: 'object',
      properties: { path: { type: 'string' }, content: { type: 'string' } },
      required: ['path', 'content'],
    },
  },
];

async function runTool(sandboxId: string, region: string | undefined, name: string, input: unknown) {
  const args = (input ?? {}) as Record<string, unknown>;
  if (name === 'run_command') {
    const command = String(args.command ?? '');
    const timeout = Math.min(Math.max(Number(args.timeout_seconds ?? 60), 1), 300);
    const r = await sandscale.sandboxes.run(sandboxId, ['bash', '-lc', command], {
      region,
      workdir: '/workspace',
      timeoutSeconds: timeout,
    });
    return {
      text: JSON.stringify({
        exit_code: r.exitCode,
        timed_out: r.timedOut,
        oom_killed: r.oomKilled,
        stdout: clip(r.stdout),
        stderr: clip(r.stderr),
      }),
      isError: false,
    };
  }
  if (name === 'write_file') {
    const path = String(args.path ?? '');
    if (!path.startsWith('/workspace/')) return { text: 'path must be under /workspace/', isError: true };
    await sandscale.sandboxes.writeFile(sandboxId, path, String(args.content ?? ''), { region });
    return { text: `wrote ${path}`, isError: false };
  }
  return { text: `unknown tool ${name}`, isError: true };
}

export async function solve(task: string, maxTurns = 25) {
  const sb = await sandscale.sandboxes.create({
    template: 'builtin:python',
    timeoutSeconds: 1800,
    labels: { app: 'claude-tool-use' },
  });
  const messages: Anthropic.MessageParam[] = [{ role: 'user', content: task }];
  try {
    for (let turn = 0; turn < maxTurns; turn++) {
      const reply = await anthropic.messages.create({
        model: MODEL,
        max_tokens: 4096,
        system: 'You work in a Linux sandbox. Check your work by running it before you answer.',
        tools,
        messages,
      });
      messages.push({ role: 'assistant', content: reply.content });

      if (reply.stop_reason !== 'tool_use') {
        return reply.content
          .filter((b): b is Anthropic.TextBlock => b.type === 'text')
          .map((b) => b.text)
          .join('\n');
      }

      const results: Anthropic.ToolResultBlockParam[] = [];
      for (const block of reply.content) {
        if (block.type !== 'tool_use') continue;
        try {
          const out = await runTool(sb.id, sb.region, block.name, block.input);
          results.push({ type: 'tool_result', tool_use_id: block.id, content: out.text, is_error: out.isError });
        } catch (err) {
          results.push({ type: 'tool_result', tool_use_id: block.id, content: String(err), is_error: true });
        }
      }
      messages.push({ role: 'user', content: results });
    }
    throw new Error(`no answer after ${maxTurns} turns`);
  } finally {
    await sandscale.sandboxes.stop(sb.id, { region: sb.region });
  }
}
```

## Walking through the loop

**Tool definitions are JSON Schema.** Each tool has a `name`, a `description` and an `input_schema`. The descriptions say what the box is: a Linux sandbox, files in `/workspace` that persist for the conversation, no network, output cut at 8,000 characters. Claude plans better when the description matches reality. The sandbox is created without a `network` option and the SDK’s default is `none`, so “no network access” is accurate.

**The assistant message goes back in whole.** After each reply, the code pushes `reply.content` as the assistant turn, including the `tool_use` blocks. The API needs those blocks in the history to match the `tool_result` blocks that follow.

**One user message carries every result.** When Claude asks for several tools in one reply, the code runs each and returns all the `tool_result` blocks together, each with the `tool_use_id` it answers.

**`is_error` is for tool failures, not for failing commands.** A command that exits 1 is a normal result: Claude asked to run the tests and the tests failed. That goes back with `is_error: false` and the exit code in the JSON. `is_error: true` is for the cases where the tool itself could not do its job: an unknown tool, a path outside `/workspace/`, or an exception from the Sandscale API.

**Inputs are checked, not trusted.** `input` arrives as whatever Claude produced. `runTool` coerces types, clamps the timeout between 1 and 300 seconds, and refuses paths outside `/workspace/`. The sandbox would contain a bad command anyway, but clear errors help Claude correct itself.

**The loop ends three ways.** Claude stops asking for tools (`stop_reason` is not `tool_use`) and the text is returned; the turn limit is reached and an error is thrown; or something fails and the error propagates. In every case, `finally` stops the sandbox, which deletes its disk. `timeoutSeconds: 1800` on create is the backstop if the process dies.

## Extending it

**Read files back.** Add a `read_file` tool with `sandscale.sandboxes.readFile`, which returns a `Uint8Array`; decode it with `TextDecoder` and clip it.

**Stream long commands.** For test suites that run a while, the SDK’s `run` can stream output as it arrives; see [streaming sandbox output](https://sandscale.dev/blog/streaming-sandbox-output-typescript). You can show progress to a user while Claude waits for the final result.

**Keep a sandbox across conversations.** For an assistant that comes back to the same project, store the sandbox id, `pause` it between sessions, and `resume` it when the user returns. Memory and disk are kept.

**Use MCP instead.** If you would rather not write tool plumbing at all, Claude Code and other MCP clients can use the [Sandscale MCP server](https://sandscale.dev/blog/remote-vs-local-sandscale-mcp-server) directly. The hand-written loop is for when you are building your own product on the Messages API.

## Guardrails beyond the loop

The loop’s checks are client-side. Sandscale adds server-side controls on every plan: [agent policy](https://sandscale.dev/security/agent-policy) can block or route a step to a person, [approvals](https://sandscale.dev/security/approvals) go to a named approver, DLP checks prompts and tool calls, and the [audit log](https://sandscale.dev/security/audit-log) records every sandbox and API call.

## Cost

Each conversation’s sandbox uses awake vCPU-hours while it runs: 100 a month on Free, 1,500 on Pro, 2,000 per member pooled on Team. Claude’s tokens are billed by Anthropic separately.

**On this page**

1. Install
2. The code
3. Walking through the loop
4. Extending it
5. Guardrails beyond the loop
6. Cost

**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/claude-api-tool-use-with-sandscale
