The Code execution tool lets an agent run a small Python script inside a sandbox during a workflow. Use it when a task needs deterministic computation that the language model is not good at on its own — parsing or reshaping JSON, regex extraction, math and aggregation, sorting and deduplicating, joining results from several tools, or validating tool inputs and outputs before sending them on. Code execution tools are configured from connectors as a Code execution tool. After you configure the tool, add it to a sub-agent or parent agent workflow. When the workflow runs, Maadify validates the script, executes it in an isolated sandbox, and returns the result, captured stdout, and the list of available linked tools to the agent.Documentation Index
Fetch the complete documentation index at: https://docs.maadify.com/llms.txt
Use this file to discover all available pages before exploring further.
- Tool Configurations
- Add Linked Tools

How code execution works
A code execution tool has three parts:- Default code is an optional Python script that runs when the agent does not provide its own.
- Default inputs are JSON values exposed as variables inside the script.
- Linked tools are other Maadify tools that the script can call by name.
print is captured separately as stdout.

Create a code execution tool
Create a Code execution tool
Describe the tool
Add default code (optional)
Add default inputs (optional)
Enable attached files (optional)
Link other tools (optional)
Use code execution in an agent
Choose how the agent can use it
Update the system prompt
code_execution_stubs and input.files template variables so the prompt always reflects the current linked tools and attached files. See Prompt template variables.Test in chat

What the agent sends to the tool
When the agent calls the code execution tool, it sends:code: a complete Python script. The value of the last expression is returned as the tool output.inputs: an optional JSON object. Each key is exposed as a top-level variable in the script.
inputs object.
What the tool returns
A successful run returns:success:true.output: the value of the last expression in the script.stdout: anything the script printed.available_functions: the list of linked tools the script could have called.
success:false.error: an object withtype(such asSyntaxError,TypingError,RuntimeError, orToolValidationError) and amessage.stdout: any output captured before the failure.
Sandbox capabilities and limits
Scripts run inside a restricted Python interpreter, not a full Python process. Many features and libraries are intentionally unavailable.Importable modules
Only the following standard library modules are available. Importing anything else raisesModuleNotFoundError.
jsonmathrepathlibtypingossysasynciodatetime(the module imports, butdatetime.now()anddate.today()are not available — pass the current time in throughinputsif you need it)
requests, numpy, pandas, pydantic, csv, collections, itertools, functools, dataclasses, enum, decimal, uuid, hashlib, base64, random, time, urllib, subprocess, socket, or threading in the sandbox.
Available builtins
print, len, range, min, max, sum, sorted, reversed, zip, enumerate, map, filter, any, all, round, abs, divmod, ord, chr, hex, bin, oct, bool, int, float, str, list, tuple, dict, set, repr, iter, next, id, hash, isinstance, hasattr, and type.
Builtins that are not available
open, exec, eval, compile, __import__, globals, locals, dir, vars, input, format, callable, frozenset, bytearray, and the bytes([...]) constructor.
Syntax that is not supported
The sandbox parser rejects:classdefinitions of any kind, including dataclasses,TypedDict,NamedTuple, and custom exception subclasses. Re-raise built-in exceptions such asValueErrorinstead.withstatements and context managers. Read and write files directly withpathlib.Pathmethods.yieldand generators. Use list comprehensions,map, orfilter.matchandcasestatements. Useifandelif.%string formatting andstr.format(). Use f-strings.
Syntax that works
f-strings, list and dict and set comprehensions, lambdas, decorators, type hints,async and await, try and except and raise and raise from, the walrus operator :=, ternary expressions, and * and ** unpacking.
Resource limits
Each run is bounded by per-call limits. Defaults are roughly:- Wall time: 5 seconds.
- Memory: 128 MB.
- Allocations: 100,000.
- Recursion depth: 50.
Attached files in the sandbox
When Include attached files is enabled, files the user attaches in chat are mounted into the sandbox under/files/ and a list named files is automatically added to the script’s variables. Each entry has the shape:
pathlib.Path. The open(...) builtin is not available.
Calling other tools from a script
A code execution tool can link to other Maadify tools so the script can call them as Python functions. Use this to combine tool outputs without making the agent call each tool one at a time.Link tools
<tool_name>_<id> form so the script can target a specific instance.
Prompt template variables
Two prompt template variables help an agent use the code execution tool well. Reference both from the sub-agent system prompt so the prompt always reflects what is actually wired into the tool.code_execution_stubs
code_execution_stubs is a dictionary keyed by the unique tool name (for example code_execution_tool_42). Each value is a Python stub block that lists every linked tool’s signature. Loop over the dictionary and render each stub:
input.files
input.files is the list of files attached to the current chat turn. Each entry has element_id, file_name, and file_type. The list is populated whether or not Include attached files is enabled, so the prompt can describe what was attached even when the script does not have read access.
Best practices
- Pass data into the script through
inputsinstead of hard-coding it incode. Hard-coded data wastes tokens and breaks when the input shape changes. - Make sure the last line of the script is the value you want returned. An assignment on the last line returns nothing.
- Prefer returning structured data, such as dicts or lists of primitives, over pretty-printed strings. Later workflow steps can map structured fields directly.
- Use
printfor diagnostic logs only. The structuredoutputis what the rest of the workflow consumes. - Keep loops bounded and avoid deep recursion so the script stays within the resource limits.
- When an attached file is large, read its size with
Path(...).stat().st_sizebefore reading the bytes. - Test the tool in chat with realistic inputs before adding it to a production workflow.
Troubleshooting
The script fails with ModuleNotFoundError
The script fails with ModuleNotFoundError
- The sandbox only ships the modules listed in Importable modules.
- Replace third-party libraries with built-in equivalents — for example, use
reinstead of regex helpers, or usejsoninstead of a parser library. - If you need a network call, use a different connector instead of code execution.
The script fails with NotImplementedError on class or with
The script fails with NotImplementedError on class or with
- The sandbox parser does not support
class,with,yield, ormatchstatements. - Refactor classes into plain functions and dictionaries. Replace
with open(...)withpathlib.Pathreads. Replace generators with list comprehensions. Replacematchwithifandelif.
The tool returns no output
The tool returns no output
- Check that the last line of the script is the value you want returned, not an assignment.
- The tool returns the value of the last expression.
result = compute()returns nothing because it is a statement, not an expression. Add a final lineresultto return it.
A linked tool call returns a coroutine instead of data
A linked tool call returns a coroutine instead of data
- The linked tool was called without
await. Addawaitto the call. - Linked tools are async and must be awaited from within the script.
A linked tool call fails with TypingError or invalid-argument-type
A linked tool call fails with TypingError or invalid-argument-type
- Pass the payload as a single dict, for example
await tool_name({"field": "value"}). - Do not spread the payload with
**payload— the sandbox rejects this pattern.
The script cannot read an attached file
The script cannot read an attached file
- Confirm Include attached files is enabled on the code execution tool.
- Use
pathlib.Pathrather thanopen(...), which is not available in the sandbox. - Iterate the runtime
fileslist and readf["path"]rather than guessing/files/<file_name>.
The script is killed mid-run
The script is killed mid-run
- The run hit a resource limit. Check the error message for details on which limit was exceeded.
- Reduce the size of the data you pass in, bound any loops, or move heavy work into a different connector.

