---
title: "Run an LLM JavaScript tool with limits in C#"
url: https://recursiveai.org/onellm/cookbook/run-javascript-tool-with-limits/
description: "Run an LLM JavaScript tool in C# with explicit execution budgets and controlled host access. Includes an offline result and an infinite-loop failure."
version: "1.0.1"
---

# Run an LLM JavaScript tool with limits in C#

**OneLLM** is a free, open-source LLM and agent library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneLlm.JavaScript) · [GitHub](https://github.com/recursive-ai-oss/onellm-csharp) · [Docs](https://recursiveai.org/onellm/docs/) · [Download example (.zip)](https://recursiveai.org/onellm/cookbook/run-javascript-tool-with-limits/run-javascript-tool-with-limits.zip)

Run a JavaScript tool in a sandbox, offline, with a step budget and no file or network grants.

```shell
dotnet add package RecursiveAI.OneLlm.JavaScript
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using System.Text.Json.Nodes;
using OneLlm;
using OneLlm.JavaScript;
using OneLlm.Tools;
using OneLlm.Messages;

var tool = JsTools.RunJavaScript(
    new JsSandboxOptions { Fuel = 10_000 });
var context = new ToolContext(
    "demo", "call-1", TimeProvider.System);
var result = await ToolInvoker.InvokeAsync(
    tool,
    new JsonObject {
        ["code"] = "return 20 + 22"
    },
    context, CancellationToken.None);
Console.WriteLine(
    ((TextPart)result.Parts[0]).Text);
```

Unzip [the example](https://recursiveai.org/onellm/cookbook/run-javascript-tool-with-limits/run-javascript-tool-with-limits.zip), then `dotnet run`.

The zip runs the full program below, not just the snippet at the top.

**Output from the snippet at the top:**

```text
=> 42
```

## The full program

The download sets step, allocation and time budgets. It runs a calculation, then submits an infinite loop to the same tool. Both JavaScript inputs are inline in `Program.cs`; there are no input files or model calls.

```csharp
using System.Text.Json.Nodes;
using OneLlm;
using OneLlm.JavaScript;
using OneLlm.Messages;
using OneLlm.Tools;

var tool = JsTools.RunJavaScript(new JsSandboxOptions
{
    Fuel = 10_000,
    MaxAllocatedBytes = 8 * 1024 * 1024,
    TimeLimit = TimeSpan.FromSeconds(2)
});
var context = new ToolContext("demo", "call-1", TimeProvider.System);
var result = await ToolInvoker.InvokeAsync(tool,
    new JsonObject { ["code"] = "console.log('sum'); return 20 + 22;" },
    context, CancellationToken.None);
Console.WriteLine(((TextPart)result.Parts[0]).Text);
var failure = await ToolInvoker.InvokeAsync(tool,
    new JsonObject { ["code"] = "while (true) {}" },
    context, CancellationToken.None);
Console.WriteLine($"Loop is error: {failure.IsError}");
Console.WriteLine(((TextPart)failure.Parts[0]).Text);
```

**Output from `dotnet run` in the unzipped project:**

```text
sum
=> 42
Loop is error: True
Error: The script used more than 10000 steps.
error[Limit]: Execution exceeded the step limit of 10000 steps
 --> snippet.js:1:1
1 | while (true) {}
  | ^^^^^^^^^^^^^^^
```

A budget failure becomes an error `ToolResult` through `ToolInvoker`; inspect `IsError` before treating the text as a successful answer. The [sandbox documentation](https://recursiveai.org/onellm/docs/javascript/) states: “Memory is a budget, not a ceiling.”

## Variations

**Check a refused host operation.** Append this to the full program. The context has no file-read grant, so it cannot read even if a file named `notes.txt` exists:

```csharp
var denied = await ToolInvoker.InvokeAsync(tool,
    new JsonObject { ["code"] = "return await ctx.readFile('notes.txt')" },
    context, CancellationToken.None);
Console.WriteLine($"File read is error: {denied.IsError}");
Console.WriteLine(((TextPart)denied.Parts[0]).Text);
```

```text
File read is error: True
Error: error[Error]: Access to 'notes.txt' (no directory is granted for read access) is not available. Grant a file root that contains it to the runtime, with Capabilities.Files(...).
 --> snippet.js:1:14
1 | return await ctx.readFile('notes.txt')
  |              ^^^^^^^^^^^^
```

## Related recipes

- [Build an AI agent with tools in C#](https://recursiveai.org/onellm/cookbook/ai-agent-with-tools-csharp/)
- [Approve tool calls before they run](https://recursiveai.org/onellm/cookbook/approve-agent-tool-calls/)

## The short answer

Install `RecursiveAI.OneLlm.JavaScript`, create `JsTools.RunJavaScript` with `JsSandboxOptions`, and invoke it through `ToolInvoker`. Pass JavaScript in the `code` input. The returned `ToolResult` carries either the output or an error. The example needs no LLM provider because it exercises the tool directly, using the same invocation boundary a tool call uses.

For an LLM-driven run, add that tool to the runtime’s tool registry. The model supplies `{ code, input? }`; your host supplies budgets and capabilities. The model does not get to grant itself file or network access. The [JavaScript integration guide](https://recursiveai.org/onellm/docs/javascript/) documents the tool, its context and failure behavior.

## What is an LLM sandbox?

Here it is a fresh JavaScript engine for each tool call, with execution budgets and a restricted host interface. A script cannot leave globals, prototypes or promises behind for the next call. It can use ECMAScript built-ins, `console`, `input` and `ctx`. It has no file, network, process, environment, timer or module access of its own.

The useful distinction is between JavaScript computation and host operations. `return 20 + 22` needs no grant. Reading a file needs a host-provided capability. OneLLM exposes controlled operations such as `ctx.readFile`, `ctx.writeFile` and `ctx.fetch`, rather than handing the script general .NET objects. The context in this recipe grants none of those operations.

This is not a separate operating-system process. Allocation accounting and the host’s heap-growth backstop are budgets, not a promise that process memory can never pass a configured number. Size the containing process for the workload rather than treating `MaxAllocatedBytes` as a hard process-memory ceiling.

## How do I run a JavaScript tool from C#?

The snippet at the top creates the built-in `run_javascript` tool. Its `code` is the body of an async function, so it supports top-level `await` and `return`. Console output comes first; a returned value follows as `=>` and JSON. With neither, the tool returns `(no output)`. That makes the result suitable for returning to a model without writing a temporary output file.

Pass a `JsonObject` to `ToolInvoker.InvokeAsync` and provide a `ToolContext` with the instance ID, call ID and clock. This recipe uses fixed IDs only to keep the standalone example small. In a runtime, use the actual call context rather than combining unrelated callers under one identity.

The full program sets `Fuel` to 10,000 steps, `MaxAllocatedBytes` to 8 MiB and `TimeLimit` to two seconds. These are sample choices, not recommended settings for every script. Fuel counts calls, loop iterations and work in long-running built-ins. The loop exhausts fuel and produces the error shown above; script code cannot catch a sandbox limit and keep going.

## Is there a free C# LLM JavaScript tool sandbox?

The package is free and open source under MIT or Apache-2.0. The download executes locally with no API key and demonstrates the tool’s real result, a budget failure and a denied file operation. It does not claim that a live model wrote the JavaScript or inspected the answer.

When you do grant host access, keep it narrow. For `run_javascript`, the context’s grants govern the exposed operations. For a JavaScript tool file loaded with `JsTools.Load`, the tool must also declare its needed capabilities in `requires`; declaration alone grants nothing. File paths are checked against the host’s granted roots, and network fetches use its egress policy. Those controls are described in the [sandbox capability rules](https://recursiveai.org/onellm/docs/javascript/#the-sandbox).
