Letting the model write and run R code is the most flexible tool you can give an agent, and the most dangerous. Deputy offers three ways to do it, which differ in two respects: whether R state survives between calls, and whether the code is confined by an OS sandbox.
| Option | State between calls | Confinement |
|---|---|---|
tool_run_r_code |
none; each call starts a new R process | your user account’s access |
RSession |
variables, packages and plots persist | your user account’s access |
MCP Console, through mcp_console_connection()
|
persists; R, Python and SQL share data | OS sandbox |
Deputy calls the first two trusted-code tools. A separate process protects your R session from crashes and runaway loops, but the code can still read, write and send anything your account can. Use them when you trust the model, the prompt and every input the agent reads, for example your own analysis on your own data. Otherwise use a sandbox.
The trusted-code tools don’t pass on your environment variables, and
R there doesn’t read .Renviron. The code sees the variables
that locate programs, libraries, locales and temporary files, such as
PATH, HOME, LANG and
TMPDIR, but API keys in your environment aren’t handed to
it. Name any others it needs with env, for example
RSession$new(agent, env = c("HTTPS_PROXY", "NO_PROXY")),
tools_code(env = "HTTPS_PROXY") or
tools_preset("dev", env = ...). Proxy settings match in
either case. env = "inherit" passes everything, keys
included.
This keeps keys out of what the code is given, not out of its reach.
Code running as your account can still read your R session’s starting
environment through the operating system, and any file your account can
read, .Renviron included. The site
Renviron.site still applies, and so does a project
.Rprofile for tool_run_r_code. To keep keys
from the code, run the agent under an account that can’t read them, or
use a sandbox.
One-off R code
tool_run_r_code runs each snippet in a fresh R process
started with callr, with a 30-second timeout, and returns the printed
output and result. Enable it with r_code = TRUE:
library(deputy)
agent <- Agent$new(
chat = ellmer::chat("openai/gpt-6.2-sol"),
tools = c(tools_data(), list(tool_run_r_code)),
permissions = Permissions(r_code = TRUE, file_write = FALSE)
)
agent$run_sync("How many rows of mtcars have more than 4 cylinders?")tool_run_bash does the same for shell commands and needs
bash = TRUE. Nothing carries over between calls, so the
model has to reload data each time.
A persistent R session
RSession gives one agent its own R worker process.
Variables and loaded packages persist between calls, so the model can
load data once and work with it over many steps. Plots come back to the
model as images.
agent <- Agent$new(
chat = ellmer::chat("openai/gpt-6.2-sol"),
permissions = Permissions(r_code = TRUE, file_write = FALSE)
)
worker <- RSession$new(agent)
agent$register_tools(worker$tools())
agent$run_sync("Load mtcars, fit mpg ~ wt, and plot the residuals.")
agent$run_sync("Now add hp to the model. Did the fit improve?")
worker$close()The worker starts on the first call. Calls run one at a time in
order, each with a 30-second timeout by default, and each starts in the
agent’s working directory. $cancel(), or a timeout, stops
the worker and discards its variables; the next call starts a fresh
worker and says so. Call $close() when the conversation
ends, for example from session$onSessionEnded() in
Shiny.
A saved conversation keeps the code, output and plots. Use an explicit checkpoint to keep selected worker variables across a restart.
The worker loads packages from your session’s
.libPaths(). To give it a library of its own, for example
one the model installs packages into, name the directories in order with
libpath:
RSession$new(agent, libpath = c(my_lib, .libPaths())). Your
own session’s search path doesn’t change.
Static plots from base graphics, ggplot2, grid and patchwork are captured. To keep supported interactive outputs, opt into an artifact directory.
Reopen interactive R results
Use an existing private directory and a stable host owner ID. Visible Plotly, DT and Leaflet widgets with bundled resources, and tables from gt or flextable, can be exported to HTML. htmlwidgets export uses Pandoc. The result includes a bounded text summary and a static PNG when the renderer can capture one. Browser previews use optional webshot2 and Chrome. Flextable exports its own static image. The HTML, text and image share the call’s output budget.
worker <- RSession$new(
agent,
artifact_dir = app_artifact_dir,
artifact_owner_id = app_owner_id
)
agent$register_tools(worker$tools())
# In a host callback, use the saved ContentToolResult for this conversation.
interactive <- Filter(
function(segment) !is.null(segment$artifact$id),
result@extra$deputy_r$segments
)
if (length(interactive)) {
frame <- worker$artifact_frame(interactive[[1L]]$artifact$id)
# Return the frame from shiny::renderUI() for this authorized conversation.
}After a restart, load the saved conversation and recreate
RSession with the original owner, Agent and session IDs and
artifact directory. The saved tool card carries the display evidence and
reference. The host can show the verified frame beside that card without
starting an R worker. The frame isolates the document from the host page
and restricts subresource loads to bundled content. Use local layers for
Leaflet maps. Server-backed outputs require a live renderer. The host
controls authorization and retention.
Recover selected R data after a restart
Give each conversation a stable owner, Agent and session ID from your application. Configure an existing private directory where your application keeps checkpoint artifacts. The example uses a temporary directory. For reopening after a supervisor restart, use durable storage and retain the checkpoint receipt’s ID in your application.
directory <- tempfile()
dir.create(directory, mode = "0700")
open_worker <- function() {
agent <- Agent$new(
chat = ellmer::chat("openai/gpt-6.2-sol"),
agent_id = "analysis",
session_id = "analysis-17"
)
RSession$new(
agent,
checkpoint_dir = directory,
checkpoint_owner_id = "research-team"
)
}
worker <- open_worker()
promises::then(worker$run("measurements <- mtcars[1:5, ]; scratch <- 10"), function(result) {
worker$checkpoint("measurements")
}) |>
promises::then(function(receipt) {
worker$close()
reopened <- open_worker()
promises::then(reopened$restore_checkpoint(receipt$id), function(restored) {
print(restored$bindings)
reopened$run("nrow(measurements)")
}) |>
promises::finally(function() reopened$close())
})Checkpoint operations and R executions share one queue. Wait for the restore promise to resolve before submitting dependent code. Captures support ordinary R data such as base data frames, matrices, factors and lists of vectors. The artifact stores at most 8 MiB of serialized data. A receipt identifies the selected bindings and their capture generation. The restore receipt adds the generation that imported them. Variables outside the selection must be recreated. Configure the new Agent and register its tools as you would for a new worker.
Keep R data checkpoints, conversation output and job or approval effect records in their respective stores. Importing data does not repeat the R expressions that produced it. A failed expression can leave partial changes in R or in files and services. If a job’s effect outcome is indeterminate, inspect its external receipt before deciding whether to make another request.
Call your tools from R code
An R session can let the model’s code call some of the agent’s other tools, so it can fetch data with a tool and then analyse the result in R:
worker <- RSession$new(agent, tools = "fetch_measurements")
agent$register_tools(worker$tools())Inside the session, the code calls
tools$fetch_measurements(...) and gets the tool’s return
value as an ordinary R object. Each of these calls goes through the
agent’s permissions, hooks and usage limits like any other tool call.
The selected tools must be registered with convert = FALSE
and check their own arguments, and they can’t pause for a durable
approval.
Sandboxed R, Python and SQL with MCP Console
MCP Console is
an OS-sandboxed workbench. Its single send tool runs R,
Python and DuckDB SQL cells in one worker, so a data frame made in R can
be queried in SQL and read from Python in the same conversation, with
optional named sessions (session) and journal notes
(note).
agent <- Agent$new(
chat = ellmer::chat("openai/gpt-6.2-sol"),
permissions = Permissions(bash = TRUE, web = TRUE)
)
console <- mcp_console_connection(
agent,
command = Sys.getenv("DEPUTY_MCP_CONSOLE_BIN"),
dependencies = "allow"
)
agent$register_tools(console$tools())
# ...
console$close()Install MCP Console 0.4.0 yourself (for example with
uv tool install mcp-console==0.4.0) and pass the path to
the executable. Deputy checks the version before starting it, and works
with mcptools 1.0.2 and 1.0.3.
In its sandbox, code can read files but can’t reach the network, and
it can write only to private temporary storage and to paths you allow.
Deputy keeps it that way: it refuses options that would turn the sandbox
off, widen file access, add a proxy, override
tool.description, or run code somewhere else. It accepts
--writable-root PATH and safe -c overrides
including -c sandbox.profile=workspace (write in the
agent’s working directory), -c sandbox.profile=read_only,
-c sandbox.network=restricted,
-c r.resolution=disabled|fixed|explicit,
-c python.resolution=fixed|explicit,
-c tool.parameters.requirements.enabled=false, and
-c sessions.max=N. A project config file,
.agents/console/config.yaml, can change the sandbox policy,
so Deputy refuses to start when one exists and passes
--no-project-config unless you have reviewed it and pass
project_config = TRUE. After starting, Deputy checks the
sandbox the server reports and disconnects unless it is the native
sandbox with restricted networking.
send runs code, so Deputy treats it like a shell
command: the agent needs bash = TRUE, plus
web = TRUE because the server doesn’t annotate its tools.
Read-only and plan modes deny it.
MCP Console can also install the packages that code asks for using
its separate resolver sandbox (which has network access to package
repositories and cache writes). It does this when a call lists
requirements, and by default R also resolves missing
packages automatically on library() or ::,
while managed Python and DuckDB prepare runtimes and extensions. With
the default dependencies = "deny", Deputy launches Console
with non-preparing R-only overrides
(-c r.resolution=disabled, -c r.packages=[],
-c languages=[r],
-c tool.parameters.requirements.enabled=false) and verifies
that requirements, python, and
sql are not exposed, so missing packages fail without
downloading anything. Pass dependencies = "allow" for the
full R, Python and SQL workbench; a call that lists
requirements also needs
install_packages = TRUE in the agent’s permissions. Set
variables such as UV_CACHE_DIR or
MCP_CONSOLE_HOME through env to control cache
and recording locations.
Calls wait up to 2.5 seconds. Longer work keeps running and returns
[running; poll with an empty send], and the model collects
the output with an empty send.
mcp_console_control(console, "interrupt") interrupts a cell
and keeps the session’s state;
mcp_console_control(console, "restart") discards all R,
Python and SQL state (pass session = "name" to target a
named session). If the restarted worker isn’t ready within 2.5 seconds,
Deputy closes the connection and you need to start a new one.
MCP Console records every call, note, output and plot under
.agents/console/sessions/ when .agents/console
already exists in the agent’s working directory, or otherwise under
$MCP_CONSOLE_HOME/sessions/
(~/.agents/console/sessions/ by default). Recordings aren’t
redacted and aren’t deleted automatically;
console$status()$execution$recordings gives the path.