# Use kumoba as a sandbox tool in the AI SDK, OpenAI Agents SDK and Claude Agent SDK (https://kumoba.dev/guide/agent-frameworks)

Define a `run_code` tool that sends the model's code to a kumoba sandbox, so it runs in its own VM instead of on your machine.

Before you begin, [install kumoba and start `kumobad`](/getting-started).

## How the tools work [#how-the-tools-work]

Each example creates one sandbox for the conversation, gives the agent tools that act on it, and deletes the sandbox when the agent is done:

- `run_code` runs Python, JavaScript or Bash with `sandbox.run()` and returns the exit code, stdout and stderr. The code is passed as an argument, not through a shell, so quotes and newlines need no escaping. A command that fails still returns a result, so the model sees the error and can fix its code.
- `write_file` and `read_file` use `sandbox.files`. Files stay in `/workspace` between calls, so the model can write a script in one call and run it in the next.

The sandbox is created with `network: "blocked"`, so code the model writes cannot reach the internet. To let it install packages, allow the hosts it needs, for example `network: { allow: ["pypi.org", "files.pythonhosted.org"] }`. See [Control network access](/guide/network).

The examples run as the image's `kumoba` user and use `Kumoba.fromEnv()`, which finds a local `kumobad` with no configuration. Each one is a folder you can run with `npm install` and `npm start`, on Node 22.18 or later:

```sh
git clone https://github.com/Parassharmaa/kumoba
cd kumoba/examples/ai-sdk
npm install
OPENAI_API_KEY=... npm start
```

The tool code is tested against a real sandbox. The model calls depend on your provider and API key.

## Vercel AI SDK [#vercel-ai-sdk]

Define the tools with `tool()` and a Zod `inputSchema`, and pass them to `generateText` or `streamText`:

```ts
import { openai } from "@ai-sdk/openai";
import { generateText, isStepCount, tool } from "ai";
import { Kumoba } from "kumoba";
import { z } from "zod";

const interpreters = {
  python: ["python3", "-c"],
  javascript: ["node", "-e"],
  bash: ["bash", "-c"],
} as const;

const sandbox = await Kumoba.fromEnv().create({ image: "default", user: "kumoba", network: "blocked" });

const runCode = tool({
  description: "Run Python, JavaScript or Bash code in an isolated Linux VM.",
  inputSchema: z.object({
    language: z.enum(["python", "javascript", "bash"]),
    code: z.string(),
  }),
  execute: async ({ language, code }, { abortSignal }) => {
    const result = await sandbox.run([...interpreters[language], code], {
      cwd: "/workspace",
      timeoutMs: 60_000,
      maxOutputBytes: 64 * 1024,
      signal: abortSignal,
    });
    return { exitCode: result.exitCode, stdout: result.stdout, stderr: result.stderr };
  },
});

try {
  const { text } = await generateText({
    model: openai("gpt-6.2-sol"),
    tools: { run_code: runCode },
    stopWhen: isStepCount(10),
    prompt: "Print the first 20 prime numbers with Python.",
  });
  console.log(text);
} finally {
  await sandbox.delete();
}
```

The [AI SDK example](https://github.com/Parassharmaa/kumoba/tree/main/examples/ai-sdk) adds `write_file` and `read_file`, and a `computer` tool that clicks, types and returns a screenshot of the sandbox's desktop through `toModelOutput`.

## OpenAI Agents SDK [#openai-agents-sdk]

Define function tools with `tool()` and Zod `parameters`, and give them to an `Agent`:

```ts
import { Agent, run, tool } from "@openai/agents";
import { Kumoba } from "kumoba";
import { z } from "zod";

const interpreters = {
  python: ["python3", "-c"],
  javascript: ["node", "-e"],
  bash: ["bash", "-c"],
} as const;

const sandbox = await Kumoba.fromEnv().create({ image: "default", user: "kumoba", network: "blocked" });

const runCode = tool({
  name: "run_code",
  description: "Run Python, JavaScript or Bash code in an isolated Linux VM.",
  parameters: z.object({
    language: z.enum(["python", "javascript", "bash"]),
    code: z.string(),
  }),
  execute: async ({ language, code }, _context, details) => {
    const result = await sandbox.run([...interpreters[language], code], {
      cwd: "/workspace",
      timeoutMs: 60_000,
      maxOutputBytes: 64 * 1024,
      signal: details?.signal,
    });
    return { exitCode: result.exitCode, stdout: result.stdout, stderr: result.stderr };
  },
});

try {
  const agent = new Agent({ name: "Coder", instructions: "Run code with run_code.", tools: [runCode] });
  const result = await run(agent, "Print the first 20 prime numbers with Python.");
  console.log(result.finalOutput);
} finally {
  await sandbox.delete();
}
```

The SDK's `computerTool()` takes an object that implements its `Computer` interface. The [OpenAI Agents SDK example](https://github.com/Parassharmaa/kumoba/tree/main/examples/openai-agents) implements it with `sandbox.desktop`, so a computer use model drives the sandbox's Linux desktop while you watch it in the [live view](/guide/desktop):

```ts
const computer = await createComputer(sandbox);
const agent = new Agent({
  name: "Browser",
  model: "gpt-6.2-sol",
  tools: [computerTool({ computer })],
});
```

### Sandbox agents [#sandbox-agents]

The SDK's `SandboxAgent` gets its shell, file editing and image tools from a sandbox client instead of tools you write. `KumobaSandboxClient`, in the [OpenAI Agents SDK sandbox example](https://github.com/Parassharmaa/kumoba/tree/main/examples/openai-agents-sandbox), is a sandbox client that runs them in a kumoba VM:

```ts
import { run } from "@openai/agents";
import { file, Manifest, SandboxAgent } from "@openai/agents/sandbox";
import { KumobaSandboxClient } from "./src/index.ts";

const agent = new SandboxAgent({
  name: "Analyst",
  instructions: "Inspect the workspace with the shell before answering.",
  defaultManifest: new Manifest({
    entries: { "data/sales.csv": file({ content: "region,amount\nnorth,120\nsouth,80\n" }) },
  }),
});

const client = new KumobaSandboxClient({ image: "default", user: "kumoba", network: "blocked" });
const result = await run(agent, "Which region sold the most?", { sandbox: { client } });
console.log(result.finalOutput);
```

The runner creates a sandbox for the run, writes the manifest's files into `/workspace` and deletes the sandbox when the run ends. To keep one sandbox across runs, create a session with `client.create({ manifest })`, pass it as `sandbox: { session }` and call `session.close()` when you are done. `exec_command` runs the command with `/bin/sh -lc` and returns when it exits, and `apply_patch` and `view_image` read and write files with `sandbox.files`. The client has no PTY, so `tty: true` and `write_stdin` are not available, and it refuses SDK snapshots, mount entries and manifest users and groups with an error. Commands run for at most an hour, the limit kumobad sets.

A run that pauses for a tool approval keeps its sandbox, so the run can continue from `result.state` and `RunState.fromString()`. If you abandon a paused run, delete its sandbox with `kumoba delete <id>`, or pass `labels` to the client and find it with `kumoba list --label key:value`. An idle sandbox stops after `autoStopMinutes` but keeps its disk until you delete it.

The client is not published to npm yet: copy its `src` folder into your project. It imports helpers from `@openai/agents-core/sandbox/internal`, which can change in any release, so pin `@openai/agents` and `@openai/agents-core` to exactly the version the example uses, 0.23.1.

## Claude Agent SDK [#claude-agent-sdk]

Custom tools reach Claude through an in-process MCP server. Define them with `tool()`, wrap them with `createSdkMcpServer()`, and pass the server to `query()`:

```ts
import { createSdkMcpServer, query, tool } from "@anthropic-ai/claude-agent-sdk";
import { Kumoba } from "kumoba";
import { z } from "zod";

const interpreters = {
  python: ["python3", "-c"],
  javascript: ["node", "-e"],
  bash: ["bash", "-c"],
} as const;

const sandbox = await Kumoba.fromEnv().create({ image: "default", user: "kumoba", network: "blocked" });

const runCode = tool(
  "run_code",
  "Run Python, JavaScript or Bash code in an isolated Linux VM.",
  { language: z.enum(["python", "javascript", "bash"]), code: z.string() },
  async ({ language, code }) => {
    const result = await sandbox.run([...interpreters[language], code], {
      cwd: "/workspace",
      timeoutMs: 60_000,
      maxOutputBytes: 64 * 1024,
    });
    const output = { exitCode: result.exitCode, stdout: result.stdout, stderr: result.stderr };
    return { content: [{ type: "text", text: JSON.stringify(output) }] };
  }
);

try {
  for await (const message of query({
    prompt: "Print the first 20 prime numbers with Python.",
    options: {
      mcpServers: { kumoba: createSdkMcpServer({ name: "kumoba", tools: [runCode] }) },
      tools: [],
      allowedTools: ["mcp__kumoba__run_code"],
    },
  })) {
    if (message.type === "result" && message.subtype === "success") console.log(message.result);
  }
} finally {
  await sandbox.delete();
}
```

`tools: []` turns off the built-in tools such as Bash, which would run on your machine, so the code Claude writes runs only in the sandbox. `allowedTools` approves the kumoba tools by their `mcp__<server>__<tool>` names.

The [Claude Agent SDK example](https://github.com/Parassharmaa/kumoba/tree/main/examples/claude-agent-sdk) adds `write_file`, `read_file` and a `screenshot` tool that returns the sandbox's desktop as an image block.

## LangChain.js [#langchainjs]

Define the tool with `tool()` from `langchain` and a Zod `schema`, and pass it to `createAgent()`:

```ts
import { ChatOpenAI } from "@langchain/openai";
import { Kumoba } from "kumoba";
import { createAgent, tool } from "langchain";
import { z } from "zod";

const interpreters = {
  python: ["python3", "-c"],
  javascript: ["node", "-e"],
  bash: ["bash", "-c"],
} as const;

const sandbox = await Kumoba.fromEnv().create({ image: "default", user: "kumoba", network: "blocked" });

const runCode = tool(
  async ({ language, code }, config) => {
    const result = await sandbox.run([...interpreters[language], code], {
      cwd: "/workspace",
      timeoutMs: 60_000,
      maxOutputBytes: 64 * 1024,
      signal: config?.signal,
    });
    return JSON.stringify({ exitCode: result.exitCode, stdout: result.stdout, stderr: result.stderr });
  },
  {
    name: "run_code",
    description: "Run Python, JavaScript or Bash code in an isolated Linux VM.",
    schema: z.object({ language: z.enum(["python", "javascript", "bash"]), code: z.string() }),
  }
);

try {
  const agent = createAgent({
    model: new ChatOpenAI({ model: "gpt-6.1-sol", useResponsesApi: true }),
    tools: [runCode],
  });
  const result = await agent.invoke({
    messages: [{ role: "user", content: "Print the first 20 prime numbers with Python." }],
  });
  console.log(result.messages.at(-1)?.content);
} finally {
  await sandbox.delete();
}
```

The [LangChain.js example](https://github.com/Parassharmaa/kumoba/tree/main/examples/langchain) adds `write_file` and `read_file`.

## Next steps [#next-steps]

- [Work in a sandbox](/guide/sandboxes) for the rest of the sandbox API, and the [TypeScript SDK](/typescript) reference.
- [Give a sandbox a token without revealing it](/guide/secrets), so the agent's code can call an API without seeing the key.
- [Use kumoba from your coding agent](/guide/coding-agents) when the agent has a shell and can use the `kumoba` CLI instead.