Code Mode
MindRoom's code mode is programmatic tool calling: run Python with mindroom-agent python inside shell to discover tools, loop over calls with foreach() or fan out with parallel(), and filter raw structured results without loading intermediate payloads into the model context.
Print only the final summary back to the model.
Code mode is not a separate toolkit; eligible shells get it automatically in standard mode and minimal mode.
Use it for tool batches in a reply, not for a long-running process, a workflow that resumes, a scheduled poll, or computation that needs an isolated Python sandbox without tools.
Choose The Right Python Mode
| Mode | Tool or command | Calls MindRoom tools | Lifetime and replay | Use when |
|---|---|---|---|---|
| Code mode (inline Python) | mindroom-agent python in shell |
Yes, through the current shell's CLI grant | Lives with the shell command; no durable replay | Batch and filter tool results for the current reply |
| Sandboxed Python | python_sandbox |
No | Fresh sandbox per call; no saved state | Parse or compute on data already in hand without shell access |
| Scheduled Python checks | triggers_write(action="watch_script") |
Yes, through the check's permitted tools | Fresh check() each tick; JSON state persists across ticks and restarts |
Poll on a schedule and wake an agent only when needed |
| Durable workflows | workflow |
Yes, including agent calls through the workflow SDK | Resumes after interruption and reuses saved calls | Orchestrate multiple steps or agents without repeating saved calls |
| Background Python scripts | script |
Yes, through the script's tool grants | Process outlives the reply; no automatic relaunch or replay | Keep a stream, socket, or tight polling loop alive |
Prefer a shared event source or webhook when the external system can push notifications instead of being polled.
How Code Mode Works
Batch calls and return a summary
This example uses the website toolkit to compare free-threading coverage across Python release notes and guides.
foreach() runs the same function for every URL, while parallel() runs a fixed list of independent functions with no arguments.
The website tool returns a JSON string with chunks from the requested page and any same-host pages it follows.
The script filters chunks by their actual page URL in meta_data["url"], then prints only the count of matching chunks and one short excerpt per requested page.
A null count means the crawl returned no chunks under that exact URL, for example after a redirect.
mindroom-agent python - <<'PYTHON'
import json
import re
def summarize(url, term):
chunks = json.loads(tool("website", "website_read_url", url=url))
page_text = [chunk["content"] for chunk in chunks if chunk["meta_data"]["url"] == url]
if not page_text:
return {"url": url, "matching_chunks": None, "sample": None}
hits = 0
sample = None
for text in page_text:
match = re.search(re.escape(term), text, re.IGNORECASE)
if match:
hits += 1
if sample is None:
sample = text[max(0, match.start() - 40):match.end() + 80]
return {"url": url, "matching_chunks": hits, "sample": sample}
release_notes = [
"https://docs.python.org/3.13/whatsnew/3.13.html",
"https://docs.python.org/3.14/whatsnew/3.14.html",
]
notes = foreach(release_notes, lambda url: summarize(url, "free-thread"), max_concurrent=2)
guides = parallel([
lambda: summarize("https://docs.python.org/3/howto/free-threading-python.html", "GIL"),
lambda: summarize("https://docs.python.org/3/howto/free-threading-extensions.html", "Py_GIL_DISABLED"),
])
{"release_notes": notes, "guides": guides}
PYTHON
Use list_tools() or search_tools("website") to find a function the current grant allows, then use describe_tool() to read its input schema before calling it.
Choose how to pass Python code
| Form | Source | sys.argv[0] |
|---|---|---|
mindroom-agent python -c CODE [ARG ...] |
Inline snippet | -c |
mindroom-agent python - [ARG ...] or mindroom-agent python |
Standard input | - |
mindroom-agent python FILE [ARG ...] |
Python file | FILE as passed |
Arguments after CODE, -, or FILE pass through unchanged as sys.argv[1:].
The snippet and stdin forms print a non-None trailing expression as JSON when possible, otherwise as Python repr().
The file form does not echo a trailing expression, so use print() for the summary.
Run mindroom-agent python --help for usage.
Use mindroom-agent python to run with MindRoom's installed SDK, the shell's CLI grant, and the helpers already imported.
Bare python3 does not pre-import the helpers and may not have the SDK installed.
Keep raw results out of model context
tool() returns the tool's raw JSON-compatible value to Python, not the formatted preview from mindroom-agent tools call or a result inserted into the model's context.
A tool that returns a string still gives Python a string, even if it contains JSON.
Only the shell window that requested a raw result can read it.
Raw results count against the live-turn size limit until the shell window closes.
For results delivered by reference, Python releases that space earlier by acknowledging the result after decoding it.
When tool traces are shown in a streamed reply, each CLI tool call gets its own entry.
For a tool that returns media, Python receives {"content": ..., "attachments": [...]} with attachment references rather than media bytes.
The media itself attaches to the shell result even if the program prints no summary.
If a completed call's result cannot be delivered, for example because it exceeded the size limit, tool() raises ToolError with kind="indeterminate" and the call ID in the message.
Check the original call's effects before retrying, because an unavailable result does not undo what the tool did.
Standard Mode And Minimal Mode
A standard-mode agent gets code mode automatically in run_shell_command when replying or running as a subagent in a Matrix conversation, provided its shell meets the deployment requirements.
MindRoom mentions mindroom-agent in the agent's instructions when this access is available.
The agent keeps all its normal tools, so it can call them directly or batch the eligible ones from Python.
Tools that may require approval, delegate, manage background jobs, or end the turn stay direct-only in standard mode.
Standard-mode CLI access is unavailable when run_shell_command is configured to pause the reply for approval or after the reply has paused for any approval.
A shell approval handled by a managed background job does not by itself disable CLI access.
Standard-mode CLI access is not available to workflow children, agents running as team members, call agents, silent listening turns, OpenAI-compatible API requests, or local OS-sandboxed shells (local_sandbox != "off").
A sandboxed named worker (sandbox=True or mount_dir=...) also receives no CLI grant, so code mode cannot call tools there.
Minimal mode normally replaces the full prompt and tool schemas with a short prompt and one Bash tool.
Use !mode <agent> minimal in a Matrix conversation, run_subagent(minimal=True) for an eligible child, or minimal=True for a headless run.
With CLI access, the agent uses mindroom-agent, including mindroom-agent python, to discover and call its other tools.
A sandboxed minimal child (run_subagent(..., minimal=True, sandbox=True)) gets Bash and, when offered, direct read_tool_output access for pruned inline output from its own conversation.
It receives no CLI grant and cannot use code mode to call tools.
See Minimal Agent Mode for !mode, minimal_instructions, and the CLI subcommands.
Add shell and the toolkits your code will call to the agent's configuration:
For Matrix replies, keep the MindRoom API server enabled regardless of where the shell runs.
Route shell through a worker, or set defaults.allow_shell_without_worker: true if you explicitly trust the agent to run commands in MindRoom's own process.
See deployment requirements for worker connectivity, authentication, and the headless setup.
Shared Python SDK
Code mode pre-imports its helpers and error types from mindroom.workflow; background scripts and durable workflows import the helpers they use explicitly.
mindroom-agent python cannot execute code inside a background script.
mindroom.workflow helper |
Code Mode (mindroom-agent python) |
Background Scripts (script) |
Durable Workflows (workflow) |
|---|---|---|---|
tool(toolkit, function, **arguments) |
Concurrent calls with the raw-result cap | Calls serialize per script; result cap about 64 KiB | Saves and reuses completed calls by default; cached=False runs them again on resume |
shell(command, ...) |
ShellResult(ok, exit_code, output) |
Same result type | Same result type with cached= replay control |
foreach(items, fn, max_concurrent=None) and parallel(fns, max_concurrent=None) |
16 threads by default, capped at 32 per batch | Same thread limit; tool calls still serialize | Up to 256 active replayable lanes per batch |
list_tools(), search_tools(query, ...), describe_tool(toolkit, function=None) |
Lists, searches, or reads descriptions and schemas | No | No |
agent(), spawn(), ask_user(), sleep(), sleep_until(), phase(), log(), now(), random(), send(), inbox(), state, run() |
No | No | Yes, see the workflow helper reference |
| Error classes | ToolError, PartialFailure, WorkflowError |
Same | Same, plus AgentError for agent calls |
tool() takes toolkit and function positionally and tool arguments by keyword; cached= only affects durable workflows.
shell() returns a command's final nonzero exit code without raising for that exit, but can raise ToolError if the shell call fails or does not report a final exit status.
The default is tail=2000 with up to 50 KiB of inline output per stream (stdout and stderr separately); redirect to a file if you need the full output.
Both fan-out helpers take max_concurrent by keyword and return results in input order.
If an item fails, the other items finish before the helper raises PartialFailure, whose .results and .errors identify the results and exceptions by position.
describe_tool() accepts TOOLKIT, TOOLKIT, FUNCTION, or TOOLKIT.FUNCTION; omit the function only for a single-function toolkit, including a deferred one.
Scheduled watch_script checks use pre-bound tool() and state in def check(): instead of this SDK, and python_sandbox has no MindRoom tool bridge.
Limits, Approvals, And Security
MindRoom limits raw results to 8 MiB per call and 32 MiB of retained results across the turn's open shell windows. Raw results do not survive a MindRoom restart.
The CLI grant gives code the tools available to that agent for that reply and does not bypass tool approval.
Code mode runs with shell authority, not with the restrictions of python_sandbox; use a worker to isolate code from the primary runtime as described in the security posture.
For shared CLI call budgets, receipt limits, and shell lifetimes, see Approvals, shells, and limits.