cd /news/ai-agents/reduced-builtins-are-not-a-sandbox-w… · home › topics › ai-agents › article
[ARTICLE · art-180856] src=dev.to ↗ pub= topic=ai-agents verified=true sentiment=↓ negative

Reduced Builtins Are Not a Sandbox: What the mcp-use CodeExecutor Advisory (CVE-2026-140133) Teaches Agent Builders

A security advisory, CVE-2026-140133, documents code injection in the CodeExecutor of the open-source mcp-use Python library, reported to affect versions up to 1.7.1. The maintainer states the built-in executor "is not a sandbox" and should not be used in production, a caveat already present in the source file's docstrings. The advisory's broader lesson is that filtering builtins does not create a security boundary, since handing model-written code the asyncio module exposes process-spawning functions like create_subprocess_shell without any import.

recommendation

Do not treat a reduced-builtins namespace as a sandbox; run model-written code in an isolated process or container with scoped permissions, since module objects like asyncio carry process-spawning capabilities.

more in playbook: Securing agents and AI tools
by read7 min views6 publishedDec 3, 2026

TL;DR: CVE-2026-140133 describes code injection in the CodeExecutor of the open-source mcp-use Python library (reported as affecting versions up to 1.7.1). The maintainer's position is that the built-in executor "is not a sandbox" and should not be used in production, and the source file says so in its own docstrings. The useful lesson is not about one library. It is about a design habit: running model-written Python with a trimmed set of builtins and calling that containment. Below: what the code actually exposes, why a reduced-builtins namespace cannot be a security boundary, a runnable check you can do in ten seconds, and a gate design that holds up.

The facts below come from the public CVE coverage and from reading the library's own source file. I did not run an exploit, and I am not publishing one.

_build_namespace function of CodeExecutor, in libraries/python/mcp_use/client/code_executor.py. Notice what is unusual here. Most agent CVEs describe a check that someone forgot or got wrong. This one describes a component whose documentation already says it is not a security control. The CVE exists because users treated a convenience feature as a boundary. That is a configuration and expectation failure, and it deserves attention in its own right.

The executor exists so an agent can write a short Python program that calls several MCP tools in a loop, instead of making one round trip per call. That is a reasonable idea: fewer tokens, fewer turns, and loops that the model would otherwise have to unroll by hand.

From the source, the flow is:

execute() builds a namespace by calling _build_namespace()._execute_code() wraps the model's text inside an async def __execute_wrapper__(): function so that top-level await and return work.exec(compiled_wrapped, namespace), then awaited under a timeout, with stdout and stderr captured. In _build_namespace(), the globals are assembled like this (paraphrased from the file):

namespace = {
    "__builtins__": safe_builtins,   # a hand-picked dict
    "asyncio": asyncio,              # "Allow async/await"
    "search_tools": search_tools,
}

safe_builtins includes everyday names such as print, len, sorted, isinstance, type, and getattr, plus a few exception types. Names like open and __import__ are left out. That omission is what makes the design feel safe. The module docstring is honest about it: the reduced builtins are "a convenience, not a security boundary", the class "is not a sandbox", code "runs in the client's own process with the client's permissions", and the advice is to run only trusted code or to run the whole client inside an isolated sandbox.

So the authors told readers the truth. The risk is that a reader sees __builtins__ being filtered, sees that open is gone, and concludes the dangerous parts have been removed.

Because the boundary you want is "this code cannot cause effects outside what I approved", and a namespace is not an effects boundary. There are three separate reasons, and each one is visible in this file.

The namespace hands the model the whole asyncio module "to allow async/await". The intent is to let the model write await asyncio.gather(...). The effect is that the model now holds every public name on that module. You can count them yourself:

import asyncio
names = [n for n in dir(asyncio) if not n.startswith("_")]
print(len(names))                       # 117 on Python 3.12.10
print(hasattr(asyncio, "create_subprocess_shell"))  # True
print(asyncio.subprocess.__name__)      # 'asyncio.subprocess'

On the Python 3.12.10 build I tested, that is 117 public names, and they include create_subprocess_exec and create_subprocess_shell. Those are process-spawning functions. Nobody wrote import os or import subprocess, and the code never needed to. The capability arrived with the module object. Whether a given call succeeds in a given environment depends on details I will not enumerate, but the design question is already answered: a gate that needs to say "this program cannot start a process" cannot be built from a namespace that includes asyncio wholesale.

getattr and type are on the allowed list. Python's object model is deeply connected: from almost any object, attribute access and type introspection lead to classes, functions, and their globals. This is the old lesson of Python sandboxing, which has been rediscovered many times. Removing open and __import__ from the builtins removes two names. It does not remove the paths by which an object can reach the rest of the runtime. A filter on names is a filter on spellings, and the model, or an attacker steering the model, is free to choose a different spelling.

Every connected MCP server appears in the namespace as an object whose methods call session.call_tool. That is the point of the feature. It also means the code runs with whatever authority those tools have: the files they can read, the tokens they carry, the networks they can reach. Even with a perfect language-level sandbox, a program that loops over tool calls can do everything the tools allow, faster and with fewer human checkpoints than a one-call-at-a-time agent.

This third point is the one teams miss most often. They imagine the risk as "Python escapes". The more common risk is "Python works exactly as designed, with the permissions of the process, driven by text that an attacker influenced".

Model-written code is a function of the model's context, and the context includes tool output, retrieved documents, web pages, and tool descriptions. If any of that is attacker-controlled, the attacker is writing a draft of your program. An executor that runs the draft inside the client process turns prompt injection into code execution in one step. That is why the CVE is classified as code injection even though the "injection" happens through ordinary-looking model output.

This is also why the CVSS vectors read as network-reachable with no privileges: the attacker does not need an account on your machine. They need a place where their text enters the model's context.

Treat "the model wrote code" as an action with its own approval path, and put the boundary at the operating system or a virtual machine, never at the language runtime. A practical order of controls:

gather(*calls) function you wrote, not the whole asyncio module. Each exposed function should do one thing and take validated arguments. Here is the shape of a minimal broker-side check for the fourth item. It is illustrative, not a drop-in library:

from dataclasses import dataclass

@dataclass(frozen=True)
class Call:
    server: str
    tool: str
    args: dict

POLICY = {
    ("docs", "search"): {"max_calls": 50},
    ("files", "read"):  {"max_calls": 20, "root": "/scratch"},
}

def allow(call: Call, counts: dict) -> bool:
    rule = POLICY.get((call.server, call.tool))
    if rule is None:
        return False                      # unknown tool: deny
    key = (call.server, call.tool)
    counts[key] = counts.get(key, 0) + 1
    if counts[key] > rule["max_calls"]:
        return False                      # batching does not escape the budget
    root = rule.get("root")
    if root and not str(call.args.get("path", "")).startswith(root + "/"):
        return False
    return True

A real implementation must also resolve paths to the object the operating system will open, not compare strings, but the structure is the point: the decision lives where every call must pass, and it does not depend on which Python names the generated code can spell.

Is mcp-use unsafe to use at all?

The advisory concerns the built-in Python code executor. The maintainer says that component is not meant for production and points to external sandboxes. Using the library's other features does not depend on that component, but read the project's notes for your version.

Does removing open and __import__ from builtins make exec safe?

No. Builtins filtering changes which names are visible, not which effects are possible. Exposed modules, introspection functions, and live tool objects all provide routes to effects.

Why do two CVSS systems give different severity labels?

CVSS 4.0 gave 6.9 (Medium) and CVSS 3.1 gave 7.3 (High) for this entry. Version 4.0 changed how it weighs attack requirements and subsequent-system impact, so the same flaw can land in different bands. Treat the number as a starting point and score the risk against your own deployment.

Is a timeout enough protection for model-written code?

A timeout limits how long the code runs, not what it does while running. You need process, memory, network, and filesystem limits enforced outside the interpreter.

What is the safest way to let an agent batch tool calls?

Give it a small, purpose-built batching function and enforce policy in the tool broker, so every call is checked no matter how it was issued. Run any free-form code in an isolated environment with no standing credentials.

Who is at risk if nobody attacks the library directly?

Anyone whose agent reads untrusted text. The attacker only needs the text to reach the model's context. From there, the model's output becomes the program.

── more in #ai-agents 4 stories · sorted by recency
── more on @mcp-use 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/reduced-builtins-are…] indexed:0 read:7min 2026-12-03 · —