Reduced Builtins Are Not a Sandbox: What the mcp-use CodeExecutor Advisory (CVE-2026-140133) Teaches Agent Builders
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
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.
What does the mcp-use CodeExecutor advisory say?
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.
-
Component: the
_build_namespacefunction ofCodeExecutor, inlibraries/python/mcp_use/client/code_executor.py. - Class of bug: code injection (CWE-94), reachable over the network with no privileges and no user interaction, according to the CVE summary.
- Severity: CVSS 4.0 scores it 6.9 (Medium) and CVSS 3.1 scores it 7.3 (High). The two systems disagree on the label, which is common when a flaw is easy to reach but its impact depends on what the host process is allowed to do.
- Exploit status: a proof of concept is reported as available; no active attacks were reported at the time of writing.
- Maintainer position: the built-in Python executor is "not intended for production use", and external sandbox providers are the recommended route.
- Affected versions: reported as up to 1.7.1. One news summary lists 1.7.0 and 1.7.1 in one place and "up to 1.7.1" in another, so check the project's own advisory before you rely on an exact range.
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.
What does the executor actually do with model-written code?
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 anasync def __execute_wrapper__():function so that top-levelawaitandreturnwork. - The wrapped text is compiled and run with
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,
# plus one object per connected MCP server, wrapping session.call_tool
}
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.
Why can't reduced builtins work as a boundary?
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.
1. A module is a bundle of capabilities, not a single capability
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.
2. Introspection builtins turn a short list into a long one
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.
3. The tool wrappers are the real power, and they are fully live
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".
Where does the attacker's text come from?
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.
How should you gate code execution for agents?
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:
- Run the executor out of process. Use a container, microVM, or a managed sandbox provider (the maintainer's own recommendation). The client process should hold no credentials the generated code does not need.
- Deny by default for network and filesystem. Allow specific hosts and a single scratch directory. Do this in the sandbox configuration, not in Python.
-
Pass capabilities, not modules. If the code needs to wait on several tool calls, expose a small
gather(*calls)function you wrote, not the wholeasynciomodule. Each exposed function should do one thing and take validated arguments. - Gate the tool calls inside the generated program. A loop that calls a tool 400 times should hit the same per-call policy as 400 separate calls. Put the check in the tool broker, so batching code cannot bypass it.
- Cap resources. Wall-clock timeouts are present in this executor, which is good. Add memory and process limits at the sandbox level, since a timeout does not limit what happens inside the window.
- Log the program text and every tool call it made, together, so a reviewer can reconstruct why an effect occurred.
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.
What should you do today if you use this library?
- Check which version you run and read the project's own advisory for the exact affected range and any patched release.
- If you enabled the code-execution mode, find out where that process runs and what credentials it holds. If the answer is "my laptop with my cloud login", move it into a sandbox first and investigate second.
- Review the MCP servers connected to that client. Every tool the generated code can call is part of the attack surface.
- Do not rely on a version bump alone. The maintainer's statement says the executor was never meant to contain code, so a patch to one function does not change the underlying assumption.
FAQ
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.
Sources
- CVE-2026-140133 coverage, including affected component, CVSS scores, and maintainer statement: tldrdailynews.com summary and the vuldb entry
- Library source and docstrings: code_executor.py in the mcp-use repository
- Namespace counts: measured locally on Python 3.12.10, reproducible with the snippet above
Further reading
- The Denied Call Still Leaked: Causality Laundering and Why Agent Gates Must Track Denials, Not Just Data (earlier post, same series)
- The Check Approved a Name, the OS Opened a Different Object: What Object-Bound Confinement Changes for Coding Agents (earlier post, same series)
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.