Giving a model a tool that runs code is a one-afternoon job. Giving it one that the model uses well, that cannot be talked into running for an hour, and whose failures lead to a sensible next step instead of a retry loop, takes more thought. Most of that thought goes into three things the model actually sees: the tool’s description, its input schema and the shape of its result.
This post designs a run_code tool field by field, then shows a TypeScript handler. The schema uses plain JSON Schema, which the major tool-calling APIs accept in some form, so the design carries across providers.
Start with the description
The description is the tool’s documentation, and the model reads all of it on every call. It should say:
- What the environment is. A fresh sandbox, no network, nothing persists between calls. If the model thinks files survive, it will write a file in one call and read it in the next, and be confused when it is gone.
- When to use it. Checking a calculation, testing a snippet, inspecting data. This steers the model away from using it for things it should not, such as trying to fetch a URL.
- What happens at the limits. Output is cut and marked; the program is stopped at its timeout. A model that knows the rules works within them.
Keep it short and literal. Clever phrasing helps nobody.
The input schema
Four fields cover most needs:
| Field | Why it is there | Limit |
|---|---|---|
language |
Picks the interpreter. An enum stops the model inventing languages you do not support. |
python or javascript |
code |
The whole program, run as a file. | 20,000 characters |
stdin |
Lets the model pass data separately from code, which is cleaner than pasting data into source. | 20,000 characters |
timeout_seconds |
Lets the model ask for longer when it knows a task is heavy. | 1 to 120, default 30 |
Some deliberate omissions:
- No
networkflag. If the model can turn the network on, a prompt injection can too. Network access is a decision for your code, per task, not for the model per call. - No
envor secrets. Nothing in the tool’s input should be able to pull credentials into the run. - No
packageslist. Installing packages at the model’s request is its own risk; see what happens when agents install packages. Preinstall what you support in the template. - No working directory or file paths. With a fresh sandbox per call, there is nothing to navigate.
additionalProperties: false tells the model, and any validator, that extra fields are not welcome. Validate again in the handler anyway. Schemas guide models; they do not bind them.
The result shape
The result is where most tools fall short. A model needs to know not only what happened, but what to do next. Use a discriminated union with a status field:
ok/error: the program ran to completion.errormeans a non-zero exit code, and stderr usually explains why. The model should read it and fix the code.timeout/out_of_memory: the program was stopped. Include ahintwith the concrete fix: do less work, raise the timeout up to the cap, process data in pieces.rejected: the program never ran. Include areasonwritten for the model, and aretryflag. Bad input isretry: true, because the model can fix it. A kill switch or a capacity limit isretry: false, because retrying will not help and the right move is to tell the user or carry on without running code.
Always include a truncated flag when output was cut, so the model does not mistake missing output for no output. Our post on feeding command output back to an LLM goes deeper on cleanup and secret masking before output reaches the model.
The handler
This uses @sandscale/sdk 1.0.0 and runs each call in a new sandbox.
import { Sandscale, SandscaleError, KillSwitchError } from '@sandscale/sdk';
export const runCodeTool = {
name: 'run_code',
description:
'Run a short program in a fresh, isolated sandbox with no network and return its exit code and output. ' +
'Files do not persist between calls. Use it to check a calculation, test a snippet or inspect data you were given. ' +
'Output longer than the limit is cut in the middle and marked; if you need the cut part, print less.',
input_schema: {
type: 'object',
properties: {
language: { type: 'string', enum: ['python', 'javascript'], description: 'The language of `code`.' },
code: { type: 'string', maxLength: 20000, description: 'The complete program. It runs as a file, not in a REPL.' },
stdin: { type: 'string', maxLength: 20000, description: 'Optional text piped to standard input.' },
timeout_seconds: { type: 'integer', minimum: 1, maximum: 120, description: 'Seconds before the program is stopped. Default 30.' },
},
required: ['language', 'code'],
additionalProperties: false,
},
} as const;
type RunCodeInput = { language: 'python' | 'javascript'; code: string; stdin?: string; timeout_seconds?: number };
export type RunCodeResult =
| { status: 'ok' | 'error'; exit_code: number; stdout: string; stderr: string; truncated: boolean }
| { status: 'timeout' | 'out_of_memory'; stdout: string; stderr: string; truncated: boolean; hint: string }
| { status: 'rejected'; reason: string; retry: boolean };
const LIMIT = 8000;
const clip = (s: string) => (s.length <= LIMIT ? s : `${s.slice(0, 2000)}\n[... ${s.length - LIMIT} characters cut ...]\n${s.slice(-(LIMIT - 2000))}`);
const FILES = { python: ['main.py', ['python3', 'main.py']], javascript: ['main.js', ['node', 'main.js']] } as const;
export async function handleRunCode(sandscale: Sandscale, raw: unknown): Promise<RunCodeResult> {
const input = raw as Partial<RunCodeInput>;
if (input.language !== 'python' && input.language !== 'javascript') {
return { status: 'rejected', reason: 'language must be "python" or "javascript"', retry: true };
}
if (typeof input.code !== 'string' || input.code.length === 0 || input.code.length > 20000) {
return { status: 'rejected', reason: 'code must be a non-empty string of at most 20000 characters', retry: true };
}
const timeout = Math.min(Math.max(Math.trunc(input.timeout_seconds ?? 30), 1), 120);
const [file, command] = FILES[input.language];
let boxId: string | undefined;
let region: string | undefined;
try {
const template = input.language === 'python' ? 'builtin:python' : 'builtin:node';
const box = await sandscale.sandboxes.create({ template, timeoutSeconds: timeout + 300 });
boxId = box.id;
region = box.region;
await sandscale.sandboxes.writeFile(box.id, `/workspace/${file}`, input.code, { region });
const run = await sandscale.sandboxes.run(box.id, [...command], { region, timeoutSeconds: timeout, stdin: input.stdin });
const stdout = clip(run.stdout);
const stderr = clip(run.stderr);
const truncated = stdout !== run.stdout || stderr !== run.stderr;
if (run.timedOut) {
return { status: 'timeout', stdout, stderr, truncated, hint: `Stopped after ${timeout}s. Do less work, or raise timeout_seconds up to 120.` };
}
if (run.oomKilled) {
return { status: 'out_of_memory', stdout, stderr, truncated, hint: 'Ran out of memory. Process data in smaller pieces.' };
}
return { status: run.exitCode === 0 ? 'ok' : 'error', exit_code: run.exitCode, stdout, stderr, truncated };
} catch (err) {
if (err instanceof KillSwitchError) {
return { status: 'rejected', reason: 'Code execution is switched off for this organization. Do not retry; tell the user.', retry: false };
}
if (err instanceof SandscaleError && err.status === 429) {
return { status: 'rejected', reason: 'Too many sandboxes are running right now. Try again later or continue without running code.', retry: false };
}
throw err; // Anything else is our problem, not the model's.
} finally {
if (boxId) await sandscale.sandboxes.stop(boxId, { region }).catch(() => undefined);
}
}
Decisions in the handler
A fresh sandbox per call. Nothing from an earlier call is there, which matches what the description promises and means one bad program cannot leave something behind for the next. If you want state across calls in a session, that is a different tool with a different description; see the trade-offs in our post on running untrusted PR code.
Two clocks. The command gets the model’s timeout, clamped to 1 to 120 seconds. The sandbox gets that plus five minutes as its lifetime, so it stops by itself even if the handler crashes before finally runs.
Clamp, do not trust. timeout_seconds is clamped rather than rejected, because a model asking for 300 seconds should get 120, not an error. code over the limit is rejected, because cutting a program is worse than asking for a shorter one.
Errors split by who can fix them. Input problems and capacity limits go back to the model as rejected, with clear wording. A KillSwitchError means someone stopped all agents on purpose; the reason tells the model not to retry. Everything else is rethrown: an unexpected API error is your bug to log and alert on, and the model cannot do anything useful with it.
Stop errors are swallowed. The finally block ignores a failed stop. The sandbox’s own lifetime is the backstop, and a cleanup failure should not hide the real result.
Test the tool like an API
Write tests that call the handler directly with the inputs a model will eventually send: an empty program, an infinite loop, a program that prints a megabyte, a program that allocates until it dies, a wrong language, an extra field. Each should produce the status you designed for. Then watch real transcripts: if the model keeps making the same mistake, the fix is usually in the description, not the code.
Where Sandscale fits
The handler above is the whole integration: create, writeFile, run and stop, with each run in its own Firecracker microVM. The SDK leaves the sandbox’s network off unless you ask for it. The open-source quickstart ships a smaller version of this tool you can start from.