Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Callbacks

Callbacks allow sandboxed Python code to call functions on the host. This enables controlled interaction with external resources like databases, APIs, or system services while maintaining the security of the sandbox.

Overview

From Python’s perspective, callbacks appear as async functions that can be awaited:

# Inside the sandbox
result = await get_weather(city="London")
print(result["temperature"])

The host defines these callbacks and controls exactly what the sandbox can access.

Defining Callbacks

[dependencies]
eryx = { version = "0.3", features = ["embedded", "macros"] }
extern crate eryx;
extern crate tokio;
extern crate serde;
extern crate serde_json;
extern crate schemars;
use eryx::{callback, CallbackError, Sandbox};
use serde_json::{json, Value};

/// Returns the current Unix timestamp
#[callback]
async fn get_time() -> Result<Value, CallbackError> {
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_err(|e| CallbackError::ExecutionFailed(e.to_string()))?
        .as_secs();
    Ok(json!({ "timestamp": now }))
}

/// Echoes the message back with optional repetition
#[callback]
async fn echo(message: String, repeat: Option<u32>) -> Result<Value, CallbackError> {
    let repeat = repeat.unwrap_or(1) as usize;
    Ok(json!({ "echoed": message.repeat(repeat) }))
}

#[tokio::main]
async fn main() -> Result<(), eryx::Error> {
    let sandbox = Sandbox::embedded()
        .with_callback(get_time)
        .with_callback(echo)
        .build()?;

    let result = sandbox.execute(r#"
t = await get_time()
print(f"Time: {t['timestamp']}")

msg = await echo(message="hi", repeat=3)
print(msg['echoed'])  # "hihihi"
    "#).await?;

    println!("{}", result.stdout_text());
    Ok(())
}
import eryx

registry = eryx.CallbackRegistry()

@registry.callback(description="Returns current Unix timestamp")
def get_time():
    import time
    return {"timestamp": time.time()}

@registry.callback(description="Echoes the message back")
def echo(message: str, repeat: int = 1):
    return {"echoed": message * repeat}

sandbox = eryx.Sandbox(callbacks=registry)

result = sandbox.execute("""
t = await get_time()
print(f"Time: {t['timestamp']}")

msg = await echo(message="hi", repeat=3)
print(msg['echoed'])  # "hihihi"
""")

Callback names must be unique: building a sandbox with two callbacks of the same name (including those added by libraries) fails with an error naming it.

Reserved Names

A guest installs each callback under its name (for a dotted name like http.get, under its first part, http), and keeps what it already has, so a callback named like something of the guest’s could only be called through invoke("name"). Building such a sandbox fails instead, naming the callback and what it collides with:

  • JavaScript: the guest’s globals (fetch, crypto, URL, setTimeout, console, require, invoke, the built-ins like JSON and Map, …), including as a dotted name’s first part (fetch.get, crypto.*).
  • Shell: the builtins (echo, cd, test, read, …, and eryx’s invoke, grep, env, xargs, chmod, kill, timeout, sh and bash), the reserved words (time, select, function, [[, …), which are parsed as syntax, and the sandbox’s commands (the embedded coreutils, with_command ones), which a callback of the same name would hide.
  • Python: the builtins (print, list, open, …) and the names the guest defines (invoke, list_callbacks, asyncio, json, …), including as a dotted name’s first part (json.dumps).

In JavaScript, process is reserved even in a sandbox without secrets, where the guest only defines it when there are some.

The lists are in crates/eryx/src/reserved/. Give the callback another name (fetch_user, http_fetch), or put it under a prefix (tools.fetch).

Callback Namespace

To keep callbacks out of the guest’s top-level names altogether, install them under one name. It’s off by default, so existing scripts keep working:

BindingOption
RustSandboxBuilder::with_callback_namespace("tools") (or wrap each in NamespacedCallback)
pyeryxSandbox(callback_namespace="tools"), also Session and the factory’s create_sandbox/create_session
gRPCExecuteRequest.callback_namespace
@eryx-org/eryxnew Sandbox({ callbackNamespace: "tools" })

A callback get_time is then await tools.get_time() in Python, await tools.get_time() in JavaScript, and the command tools.get_time in the shell. A prefix callback mcp.* nests under it as tools.mcp.<server>.<tool>. Only the namespace has to stay clear of the reserved names above, so tools.fetch builds in JavaScript; the namespace must be an identifier. list_callbacks(), trace events and callback journals show the namespaced names (tools.get_time), while the callback itself (and a gRPC client’s CallbackRequest.name) sees its own name. A pool built with a namespace puts each lease’s callbacks under it too. Code written against the bare names, such as a library preamble that calls get_time() or invoke("get_time"), has to use the namespaced ones.

Parameters and Types

Callback parameters are passed as JSON from the sandbox. Parameters must be deserializable types.

#![allow(unused)]
fn main() {
extern crate eryx;
extern crate serde;
extern crate serde_json;
extern crate schemars;
use eryx::{callback, CallbackError};
use serde_json::{json, Value};

/// Searches for users matching the criteria
#[callback]
async fn search_users(
    query: String,              // Required parameter
    limit: Option<u32>,         // Optional with default (via unwrap_or)
    include_inactive: Option<bool>,
) -> Result<Value, CallbackError> {
    let limit = limit.unwrap_or(10);
    let _include_inactive = include_inactive.unwrap_or(false);

    // ... perform search ...
    let _ = query;
    Ok(json!({ "users": [], "total": 0 }))
}
}
import eryx

registry = eryx.CallbackRegistry()

@registry.callback(description="Searches for users")
def search_users(
    query: str,
    limit: int = 10,
    include_inactive: bool = False
):
    # ... perform search ...
    return {"users": [], "total": 0}

Positional Arguments

Sandboxed code can pass a callback’s arguments by name or by position. Positional arguments bind to the callback’s parameters in the order of its schema’s properties, in the order the schema declares them (the order list_callbacks() shows), the way a Python function binds them:

  • In Python, await add(1, 2) and await add(a=1, b=2) are the same call.
  • In JavaScript, a single plain object whose keys are all parameter names is keyword arguments, await add({a: 1, b: 2}), and anything else is positional, await add(1, 2). So for a callback whose first parameter, options, takes an object, await configure({retries: 3}) passes that object as options, while await configure({options: {retries: 3}}) names it. Keyword and positional arguments can’t be mixed in one call. Trailing undefined arguments count as not passed, and an undefined before another argument is sent as null.
  • The shell guest follows the same rule once #808 lands: add 1 2 is positional.

More positional arguments than parameters, or one that is also passed by name, fail the call without running the callback: add() takes 2 positional arguments but 3 were given, add() got multiple values for argument 'a'.

The Python guest binds positional arguments itself. The other guests send them to the host under the reserved key __eryx_args__ (eryx::POSITIONAL_ARGS_KEY), and the host binds them with the same rules. A prefix callback (a.b.*) gets its positional arguments unbound instead (see PrefixCallback).

Error Handling

Return errors to indicate failures to the sandbox.

#![allow(unused)]
fn main() {
extern crate eryx;
extern crate serde;
extern crate serde_json;
extern crate schemars;
use eryx::{callback, CallbackError};
use serde_json::{json, Value};

/// Divides two numbers
#[callback]
async fn divide(a: f64, b: f64) -> Result<Value, CallbackError> {
    if b == 0.0 {
        return Err(CallbackError::InvalidArguments("Cannot divide by zero".into()));
    }
    Ok(json!({ "result": a / b }))
}
}
import eryx

registry = eryx.CallbackRegistry()

@registry.callback(description="Divides two numbers")
def divide(a: float, b: float):
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return {"result": a / b}

Parallel Execution

Multiple callbacks can run concurrently using asyncio.gather():

# Inside the sandbox
import asyncio

# These run in parallel on the host
results = await asyncio.gather(
    fetch_user(id=1),
    fetch_user(id=2),
    fetch_posts(user_id=1),
)
user1, user2, posts = results

Timers

asyncio.sleep, asyncio.wait_for and asyncio.timeout work inside the sandbox, so scripts can bound their own callbacks or back off between retries:

# Inside the sandbox
import asyncio

try:
    user = await asyncio.wait_for(fetch_user(id=1), timeout=2)
except TimeoutError:
    user = None

Each pending timer is a host-side sleep; the guest is suspended while it waits. Timers fire only when the event loop regains control, so blocking code (time.sleep, a CPU-bound loop) delays them rather than being interrupted. Timers still pending when an execution finishes are cancelled with it, and never extend the execution timeout.

asyncio.run()

Code runs on an event loop that is already running, so top-level await is the natural way to call callbacks. Scripts written in the usual asyncio.run(main()) style work too: a top-level asyncio.run(coro) call (including one under if __name__ == "__main__":) awaits coro on the sandbox’s loop and returns its result.

# Inside the sandbox
import asyncio

async def main():
    return await fetch_user(id=1)

user = asyncio.run(main())

Only calls written as asyncio.run(...) at the top level are handled this way. Inside a function, which can’t await, asyncio.run() raises a RuntimeError; use await there instead.

Introspection

The sandbox can discover available callbacks at runtime:

# Inside the sandbox
import eryx_callbacks

# List all available callbacks
for name in dir(eryx_callbacks):
    callback = getattr(eryx_callbacks, name)
    print(f"{name}: {callback.__doc__}")

Callbacks in the Shell

In a shell sandbox, every callback is a command. A shell function or builtin of the same name wins, as in bash, and invoke NAME still reaches the callback. Arguments become the callback’s JSON arguments, and its result is printed to stdout, so callbacks compose with pipes and $(...):

weather London --days 3          # positional, then a flag
weather --city=London --metric   # --key=value, and a bare boolean flag
weather --json '{"city": "London"}' --days 3
invoke weather '{"city": "London"}'
forecast=$(weather London | grep -i rain)
  • Typing: flag values are typed by the callback’s parameters schema. A string property keeps the exact text (--id 007 is "007"). integer, number and boolean values are parsed, and an invalid one is a usage error. object and array values are JSON. A property with no type, or one that isn’t in the schema, is JSON if it parses and a string otherwise.
  • Boolean flags: a boolean property can be given bare (--metric), which means true, unless the next argument is true or false.
  • Positional arguments: the host binds these to the schema’s properties in order, like the Python guest’s weather("London"). eryx serializes schemas with their properties in alphabetical order. Each one is typed by the property at its position. Too many positionals, or one for a property also given as a flag, fails the call, so the command exits 1.
  • Repeated keys: repeating a key collects into a list for an array property, and is a usage error otherwise.
  • --json: gives a base object, and flags override its keys. -- ends the flags.
  • invoke: invoke NAME ... takes the same arguments. With a single JSON object argument, the object is passed as the arguments as is. invoke also reaches names under a prefix callback (invoke ns.tool --x 1).
  • NAME --help: prints the callback’s description and its arguments.
  • stdin: not read.

The result prints as a line on stdout: a string as raw text, anything else other than null as compact JSON, and null as nothing.

Exit statuses:

StatusMeaning
0The callback succeeded.
1The call failed: the callback returned an error, or the host rejected the arguments. That covers too many positionals, or a positional for a property also given as a flag. NAME: message goes to stderr.
2A usage error the shell found before calling: a bad flag value, a repeated key, malformed --json. NAME: problem, then the usage line, go to stderr.
127invoke of an unknown name.

A callback that suspends (see Replay and Suspension) stops the whole script, whatever surrounds the call: approve || true doesn’t swallow it.

Alternative APIs

Rust: Manual TypedCallback

For more control, implement TypedCallback directly:

extern crate eryx;
extern crate tokio;
extern crate serde;
extern crate serde_json;
extern crate schemars;
use std::{future::Future, pin::Pin};
use eryx::{TypedCallback, CallbackError, Sandbox, JsonSchema};
use serde::Deserialize;
use serde_json::{json, Value};

#[derive(Deserialize, JsonSchema)]
struct GreetArgs {
    name: String,
    #[serde(default)]
    formal: bool,
}

struct Greet;

impl TypedCallback for Greet {
    type Args = GreetArgs;

    fn name(&self) -> &str { "greet" }
    fn description(&self) -> &str { "Generates a greeting" }

    fn invoke_typed(
        &self,
        args: GreetArgs,
    ) -> Pin<Box<dyn Future<Output = Result<Value, CallbackError>> + Send + '_>> {
        Box::pin(async move {
            let greeting = if args.formal {
                format!("Good day, {}.", args.name)
            } else {
                format!("Hey {}!", args.name)
            };
            Ok(json!({ "greeting": greeting }))
        })
    }
}

#[tokio::main]
async fn main() -> Result<(), eryx::Error> {
let sandbox = Sandbox::embedded()
    .with_callback(Greet)
    .build()?;
    Ok(())
}

Rust: DynamicCallback

For runtime-defined callbacks without compile-time types:

extern crate eryx;
extern crate tokio;
extern crate serde_json;
use eryx::{DynamicCallback, Sandbox};
use serde_json::json;

#[tokio::main]
async fn main() -> Result<(), eryx::Error> {
let callback = DynamicCallback::builder(
    "get_config",
    "Returns application configuration",
    |_args| Box::pin(async move {
        Ok(json!({
            "version": "1.0.0",
            "debug": false
        }))
    })
).build();

let sandbox = Sandbox::embedded()
    .with_callback(callback)
    .build()?;
    Ok(())
}

Python: Dict API

For simple cases, use a list of dictionaries:

import eryx

def my_callback(args):
    return {"result": args.get("value", 0) * 2}

sandbox = eryx.Sandbox(
    callbacks=[
        {
            "name": "double",
            "fn": my_callback,
            "description": "Doubles a value"
        }
    ]
)

Prefix Callbacks

A prefix callback handles every dotted name under a prefix with one handler, which receives the full name the sandbox called, its keyword arguments and its positional arguments. Use it for large or lazily discovered tool sets, where registering each tool separately would be costly: the sandbox installs one callback however many names it serves, and nothing under the prefix is looked up until it is called.

extern crate eryx;
extern crate tokio;
extern crate serde_json;
use eryx::{CallbackError, PrefixCallback, Sandbox};
use serde_json::json;

#[tokio::main]
async fn main() -> Result<(), eryx::Error> {
// Registers `mcp.grafana.*`.
let tools = PrefixCallback::new("mcp.grafana", "Grafana MCP tools", |name, kwargs, args| {
    Box::pin(async move {
        match name.as_str() {
            "mcp.grafana.user_info" => Ok(json!({ "login": "admin" })),
            // Bind a positional query, or take it by keyword.
            "mcp.grafana.search-docs" => {
                let query = args.first().unwrap_or(&kwargs["query"]).clone();
                Ok(json!({ "query": query }))
            }
            _ => Err(CallbackError::NotFound(name)),
        }
    })
});

let sandbox = Sandbox::embedded().with_callback(tools).build()?;
let output = sandbox
    .execute(
        r#"
user = await mcp.grafana.user_info()
docs = await mcp.grafana["search-docs"](query="alerts")
more = await mcp.grafana["search-docs"]("panels")
print(user["login"], docs["query"], more["query"])
"#,
    )
    .await?;
assert_eq!(output.stdout_text().trim(), "admin alerts panels");
    Ok(())
}
  • A name registered as an ordinary callback is called directly, so exact callbacks win over prefixes. Other names go to the longest matching prefix (mcp.grafana.* before mcp.*); a name under no prefix fails as unknown.
  • The sandbox has no schema for the names under a prefix, so it passes positional arguments to the handler, in order, rather than binding them. The handler can bind them itself (e.g. to an MCP tool’s input schema properties, in declared order) or reject them with CallbackError::InvalidArguments. A keyword-only call gets an empty list. An exact callback under the prefix still binds positional arguments from its own schema.
  • list_callbacks() lists the prefix (mcp.grafana.*) with its description, not the names under it.
  • JavaScript guest code calls them the same way: await mcp.grafana.user_info(), await mcp.grafana["search-docs"]("panels"). Any name below the prefix, at any depth, is a function. A single plain object is keyword arguments; anything else goes positionally. Looking at a namespace never calls the host, so then, toJSON (which JSON.stringify and console.log ask for), call, apply, bind and Object.prototype’s names (toString, …) aren’t tool names there: call those through invoke("mcp.grafana.toJSON"). console.log prints a namespace as [Namespace mcp.grafana]. listCallbacks() lists the prefix as is.
  • Any callback whose name ends in .* is a prefix callback, and gets the invoked name through Callback::invoke_named. In the JavaScript package, declare a callback named mcp.grafana.*: the callback handler already receives every call’s full name.
  • On the wire, positional arguments travel in the arguments object under the reserved key __eryx_args__ (eryx::POSITIONAL_ARGS_KEY), only when there are any: f(1, k=2) sends {"__eryx_args__":[1],"k":2}. PrefixCallback takes the key out; a custom prefix callback, or a JavaScript handler, sees it as is. Python code can’t pass a keyword argument of that name (it’s a TypeError), and an ordinary callback that receives the key fails with InvalidArguments without being called.
  • Journals, trace events and max_callback_invocations see the full name of each call. Journals key on the arguments text, positional ones included, so only identical calls replay.

MCP Tools as Callbacks

Eryx can also bridge MCP (Model Context Protocol) servers into the sandbox as callbacks. This lets sandboxed code call tools from external MCP servers (GitHub, filesystem, databases, etc.) using the same async callback mechanism.

See MCP Integration for details.

Replay and Suspension

When a script drives expensive callbacks (tool calls, API requests, database queries), eryx can journal callback results on one run and replay them on the next, so a re-run only re-executes the callbacks that haven’t run yet. A callback can also suspend execution — returning a “retry later” signal that halts the guest and lets the run resume once a dependency is ready.

See Callback Replay & Suspension for details.

Best Practices

  1. Keep callbacks focused - Each callback should do one thing well
  2. Validate inputs - Don’t trust data from the sandbox
  3. Handle errors gracefully - Return meaningful error messages
  4. Use descriptive names - Callbacks appear as functions in Python
  5. Document with descriptions - Help sandbox code understand what’s available
  6. Consider timeouts - Long-running callbacks can block sandbox execution