TL;DR

  • The sandbox is fast. The model is slow. A typical run_python run takes 0.43s. Writing the code for it takes 5.05s.
  • Models rarely write bad Python. Only 19 of 9,863 runs (0.19%) hit a SyntaxError. Most failures come from our sandbox’s own rules.
  • Errors are cheap when the agent can retry. 13.5% of runs failed, but 88.5% of retried failures recovered, most of them on the very next try.
  • MCP and CodeAct are not rivals. Direct MCP calls handle simple reads and approved writes. Python handles everything messy.

Why We Looked

CodeAct means letting an LLM write and run Python, instead of making one JSON tool call per turn. Debates about it usually come down to two claims:

  1. Writing code saves context tokens compared to chaining MCP (Model Context Protocol) tool calls.
  2. Sandbox startup will slow the agent down unless you invest in microVM snapshots or warm pools.

Both sound right on a whiteboard. Neither tells you what actually breaks after months of real users sending messy, multi-step tasks. So we went back through four months of production traces from our agent, Stevin, to find out.

The dataset

Stevin reaches for run_python when a task needs multi-page filtering, data transformation, deterministic checks, or binary file inspection. We pulled every trace that used it at least once, with no sampling or pagination gaps.

Count
Time window2026-08-01 to 2026-11-26
All traces in the project23,612
Traces that used run_python1,619 (6.9%)
Observations in the cohort208,370
run_python runs9,863
Direct MCP calls2,593
LLM generations27,564

Terms used in this post

  • Trace / span / observation: Langfuse’s units. A trace is one user task; spans and observations are the steps inside it.
  • run_python: Stevin’s tool that runs a Python snippet in an isolated sandbox. One execution is a run.
  • Direct MCP call: a normal tool call that the model makes itself, outside any Python code.
  • hide: a bridge object, already loaded inside the sandbox, that lets Python code call read-only external tools (hide.github.*, hide.notion.*).

How Stevin Calls Tools

Two tool execution paths in production: Direct MCP vs run_python sandbox with hide bridge Two tool execution paths in production: Direct MCP vs run_python sandbox with hide bridge

On any turn, Stevin can reach external systems in two ways.

Path A: direct MCP calls (2,593 calls across 747 traces)

  • The model emits a standard tool call, such as GITHUB_GET_AN_ISSUE, notion__notion-fetch, or exa__web_search_exa.
  • The full JSON response goes straight into the model’s context.
  • Writes (CREATE, UPDATE, DELETE) must pass a human approval card before they run.

Path B: run_python with the hide bridge (9,863 runs across 1,619 traces)

The model sends {code, description}. The code runs in an isolated process with these rules:

  • seccomp filters system calls. A forbidden call kills the process with SIGSYS.
  • The filesystem is restricted, and each run has a 60-second timeout.
  • Runs are stateless. Variables do not carry over to the next run.
  • hide is preloaded. One run can make at most 64 bridge calls, and each response is capped at 1 MB.
  • Writes are blocked inside code with stubs.NeedsApproval.
  • Only stdout goes back to the model.

The agent used this path heavily: 6.09 runs per trace on average (median 4), and 60.6% of scripts (5,977 of 9,863) called hide. This is sustained, iterative programming, not an occasional calculator.


Finding 1: The Sandbox Isn’t the Bottleneck

The usual first move when building a code sandbox is to cut container startup from 400ms to 50ms. Our latency data shows that this barely changes what users feel.

Mean end-to-end trace latency breakdown and single-invocation p50 vs mean flip Mean end-to-end trace latency breakdown and single-invocation p50 vs mean flip

Here is where time goes in each of the 1,619 traces. We measured the main task only, leaving out memory writes that happen after the task ends.

Per-trace componentMean (s)p50 (s)p90 (s)p99 (s)Share of mean
End-to-end total204.40106.53510.891,034.25100.0%
LLM generation132.5564.84297.54879.8164.9%
Python execution (run_python)18.963.2840.89276.919.3%
Direct MCP calls3.850.0010.0250.751.9%
Other (internal tools + orchestration)49.8022.84115.87341.4424.4%

In the “Other” bucket, internal tools (CLI, files, search, messages) take 28.9s per trace on average. The remaining 20.9s or so is orchestration and idle time.

LLM generation was the biggest single cost in 81.3% of traces (1,316 of 1,619). The gap is even clearer when we compare single calls:

Single callCountMean (s)p50 (s)p90 (s)p99 (s)
LLM generation that writes the code9,86310.105.0519.5688.74
run_python (outer span)9,8633.130.436.2160.08
run_python (interpreter only)9,7052.850.295.8959.99
Direct MCP call2,5932.401.555.2313.52

Writing the code takes 12x longer than running it

At the median, the model spends 5.05 seconds writing a snippet that finishes in 0.43 seconds (0.29s inside the interpreter). Cutting 150ms from sandbox startup saves almost nothing. Avoiding one unnecessary retry saves 5 to 15 seconds.

Why the mean flips

A typical run_python run is 3.6x faster than a direct MCP call (0.43s vs. 1.55s at p50). On the mean, though, Python looks slower (3.13s vs. 2.40s).

The cause is a small tail. 98 runs scanned without any budget, for example looping over 150+ branches one by one to collect commits. Each hit the 60-second timeout, and together they added 6,158.4 seconds.


Finding 2: Models Fail at Your Contract, Not at Python

1,332 of 9,863 runs failed (13.5%), touching 681 of 1,619 traces (42.1%). You might expect sloppy code: bad indentation, off-by-one errors, made-up library functions. The data says otherwise.

Root causes across 1,332 failed Python runs Root causes across 1,332 failed Python runs
Failure categoryFailed runsAffected traces (% of cohort)Main exceptions and likely cause
Sandbox and resource limits443306 (18.9%)BridgeError (194), PermissionError (107), Timeout (98), SIGSYS (14)
Wrong API response shape370292 (18.0%)TypeError (208), AttributeError (109), KeyError (53)
Import / missing dependency10082 (5.1%)ModuleNotFoundError (95), including 84 import hide errors
Retry-stop guardrail8556 (3.5%)TooManyFailures (85) after 5 failed runs in one turn
Missing files / paths7867 (4.1%)FileNotFoundError (77): expecting files from an earlier run
Tool-input schema error6358 (3.6%)ToolInputError (63): payload wrapped in {"arguments": ...}
State lost between runs6254 (3.3%)NameError (62): expecting variables from an earlier run
Logic bug5949 (3.0%)ValueError (24), IndexError (17), AssertionError (13), struct.error (3)
Other / encoding / policy5039 (2.4%)Unknown (29), encoding errors (17), NeedsApproval blocks (4)
Python SyntaxError1919 (1.2%)SyntaxError (19): 0.19% of all runs

Here, “failed” means run_python returned ok: false or the input failed schema checks. Wrong answers that exited cleanly can’t be told apart from normal exploration without human labels.

Start at the bottom. Syntax errors (19) and logic bugs (59) together are 5.9% of failures, or 0.79% of all runs. Current models write valid Python with ease.

Over 80% of failures happen where the model’s habits meet our runtime’s rules. Three patterns stand out.

1. The res["data"]["content"]["content"] trap

The 370 shape failures include 134 cases of TypeError: argument should be a bytes-like object or ASCII string, not 'dict' and 46 cases of 'str' object has no attribute 'get'.

Models know raw REST APIs well, but not your wrapper around them. GitHub’s GET /repos/{owner}/{repo}/contents/{path} returns {"content": "<base64>", ...}. The model knows our bridge wraps responses in {"data": ...}, so it writes:

res = hide.github.GITHUB_GET_REPOSITORY_CONTENT(
    owner="acme-org", repo="core-repo", path="docs/architecture.md", ref=head_sha
)
# Crash! In this provider wrapper, res["data"]["content"] is the outer file dict;
# the actual base64 payload lives at res["data"]["content"]["content"]!
raw = base64.b64decode(res["data"]["content"])

With no typed return stubs or helper functions, the model has to spend a whole run discovering that res["data"]["content"] is itself a dict.

2. Habits from scripts and notebooks

Models learned from millions of Python files and Jupyter notebooks. Those habits leak:

  • Normal Python imports what it uses. So the model writes import hide, causing 84 ModuleNotFoundError: No module named 'hide' failures, even though hide is already loaded. One trace even tried import default_api, from another platform’s tool runtime.
  • Jupyter keeps state between cells. Our runs don’t. This caused 62 NameErrors and 77 FileNotFoundErrors when a run referred to a variable or file from an earlier run.
  • Scripts write to /tmp. Our sandbox only allows writes in its working directory, so /tmp writes and reads like /usr/share/zoneinfo led to 107 PermissionErrors.
  • Wrapping the tool input. 63 calls failed before Python even started, because the model nested {"arguments": {"code": ...}} or sent the JSON as an encoded string.

3. Hitting the sandbox’s limits

The largest bucket, 443 failures, comes from the guardrails themselves: 194 BridgeErrors (oversized responses, misused bridge calls, unloaded toolkits), 107 PermissionErrors, 98 timeouts, and 14 SIGSYS kills. These limits are working as designed. The fix is to explain them better, which leads to the next finding.


Finding 3: A 13.5% Error Rate That Heals Itself

A web service with a 13.5% error rate would page someone all night. Here, it barely hurt task outcomes. In CodeAct, an exception is feedback in a fast loop, not a final 500 error.

Self-healing REPL recovery funnel across 9,863 sandbox runs Self-healing REPL recovery funnel across 9,863 sandbox runs

Of the 1,332 failed runs:

  • 1,155 were followed by another run_python run in the same trace. (Of the rest, 85 hit the TooManyFailures limit, and 92 were the last Python run before the agent switched tools or answered.)
  • 1,022 of those 1,155 (88.5%) eventually reached a successful run.
  • 875 of the 1,022 recoveries (85.6%) succeeded on the very next run. Median attempts, counting the first failure, was 2.0 (mean 2.17).

Two recoveries from production

  1. Probing a nested response (0.76s → 0.80s → 0.21s). While reading PR markdown files, the agent hit the b64decode TypeError above. Next, it ran a 10-line probe, print(res.keys(), res['data']['content'].keys()), and saw the nested content key. The third run decoded both files cleanly.
  2. Working around a blocked file (0.49s → 0.43s). To convert a UTC timestamp to Asia/Shanghai, the agent used zoneinfo.ZoneInfo("Asia/Shanghai") and got PermissionError: [Errno 13] Permission denied: '/usr/share/zoneinfo/Asia/Shanghai'. Four seconds later it switched to timezone(timedelta(hours=8)), which needs no files, and succeeded.

Error messages written for the model

The 85.6% next-run recovery rate is not luck. Much of our most useful sandbox work went into writing exception messages for an LLM, not for a human on call. Each one says what went wrong and what to do next:

# 1. Catching eager sequential calls inside hide.gather()
stubs.BridgeError: hide.gather takes (tool, kwargs) pairs — pass the tool itself,
not the result of calling it: hide.gather([(hide.github.LIST_ISSUES, {'owner': 'o'})]).
Note that calling it inside the list already ran it, one at a time, which is what
gather exists to avoid.

# 2. Auto-printing response schema when a bridge call exceeds the 1 MB payload cap
stubs.BridgeError: github.GITHUB_LIST_PULL_REQUESTS_FILES returned 1060351 bytes,
over the 1000000 byte limit for one call. Its shape was:
{"successful": "bool", "data": {"details": {"_type": "list", "_len": 100}}, ...}
Narrow it — fewer fields, a smaller page, a tighter time window — and call it again.

# 3. Keeping write side effects behind user approval cards
stubs.NeedsApproval: notion.NOTION_REPLACE_PAGE_CONTENT writes, so it cannot be called
from inside code — that would put the action past the approval card. Finish computing,
print what you decided, then issue this call as an ordinary tool call.

Look at the second message. Instead of a bare PayloadTooLarge, it prints the shape of the rejected response, which saves the agent a whole probing run. In the same spirit, when a toolkit isn’t loaded yet, BridgeError tells the agent to call load_toolkit('github') outside run_python and try again.

Where recovery broke down

Our blunt circuit breaker caused the most give-ups. After 5 failed runs in a turn, TooManyFailures disables Python for the rest of that turn. It fired 85 times across 56 traces, more than any other final error (ModuleNotFoundError was next at 42, then BridgeError at 37). In one multi-branch audit, the agent learned to scan branches in batches of 30, then hit the 5-failure limit just as the batching started working.


Finding 4: MCP and CodeAct Split the Job

People often frame MCP tool calls and code execution as competitors. In our data, 46.1% of Python-using traces (747 of 1,619) used both in the same task. Each one has a clear role:

MechanismVolumeError rateTypical use
Direct MCP, reads2,395 calls in 697 traces (92.4% of MCP)3.1% for all MCPOne issue, one file, one search: GITHUB_GET_REPOSITORY_CONTENT, exa__web_search_exa, notion__notion-fetch
Direct MCP, writes198 calls in 123 traces (7.6% of MCP)1.0% (2 of 198)Create an issue, post a comment, create a Notion page, behind an approval card
run_python, one-shot362 of 1,619 traces (22.4%)Succeeded first tryUUID5 key checks (0.37s), WCAG contrast math (0.77s), length checks (0.14s), volume sums (0.28s)
run_python, fan-outPart of 9,863 runs13.5% for all runshide.gather(...) fetches many issues or PR files, filters in Python, and prints 15 lines instead of 800 KB of JSON
run_python, file surgeryPart of 9,863 runs13.5% for all runsParsing files that no fixed tool can handle (story below)

For a single lookup, a direct call (1.54s p50 to run, plus 4.26s to generate) beats inventing boilerplate code. For writes, which have real-world impact, a flat MCP call behind an approval card keeps every action visible to a human. stubs.NeedsApproval makes sure writes can’t hide inside a loop.

A PDF that no tool could read

In one trace, the agent needed the invoice number, amount, and date from three PDF attachments. Standard text extraction returned nothing: the PDFs used custom per-font glyph codes ((\x06\x0f)Tj) inside compressed /ObjStm streams. Over 11 runs, each under 300ms, the agent:

  1. Wrote a zlib decompressor for the object streams.
  2. Parsed the raw beginbfchar ToUnicode CMap tables.
  3. Mapped each custom glyph code back to a UTF-8 character.
  4. Extracted every field correctly. Its only error, a SyntaxError from non-ASCII text in an rb'...' regex, was fixed 3 seconds later.

No MCP server will ever ship a decode_broken_vendor_pdf_cmap tool. With a Python sandbox, it doesn’t need to.


A Blind Spot in Our Tracing

We checked the parent of every one of the 2,593 MCP spans. All of them sat outside run_python, directly under the agent’s turn spans. Where inner mcp.call spans were sampled, inner and outer timing differed by a median of 4ms. So our direct MCP numbers are clean.

The Python numbers are not. 60.6% of runs (5,977 of 9,863) called hide internally, and those bridge calls did not create their own spans. Today, “Python execution time” mixes local CPU work with time spent waiting on GitHub or Notion.


Takeaway

If you are building tool-using agents, you don’t have to pick between MCP and CodeAct. Give your agent MCP for clean, auditable reads and human-approved writes. Give it a sandboxed Python runtime with a read-only tool bridge for everything messy, composite, or unexpected.

Once it runs in production, don’t rush to shave milliseconds off container startup. Read your traces first. The biggest wins are likely in clearer sandbox contracts, typed bridge responses, and error messages that teach the model what to do next. To see this hybrid MCP + CodeAct design in practice, check out Stevin.