{"slug": "reduced-builtins-are-not-a-sandbox-what-the-mcp-use-codeexecutor-advisory-cve", "title": "Reduced Builtins Are Not a Sandbox: What the mcp-use CodeExecutor Advisory (CVE-2026-140133) Teaches Agent Builders", "summary": "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.", "body_md": "**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.\n\nThe 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.\n\n`_build_namespace` function of `CodeExecutor`, in `libraries/python/mcp_use/client/code_executor.py`.\nNotice 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.\n\nThe 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.\n\nFrom the source, the flow is:\n\n`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.\nIn `_build_namespace()`, the globals are assembled like this (paraphrased from the file):\n\n```\nnamespace = {\n    \"__builtins__\": safe_builtins,   # a hand-picked dict\n    \"asyncio\": asyncio,              # \"Allow async/await\"\n    \"search_tools\": search_tools,\n    # plus one object per connected MCP server, wrapping session.call_tool\n}\n```\n\n`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.\n\nSo 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.\n\nBecause 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.\n\nThe 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:\n\n``` python\nimport asyncio\nnames = [n for n in dir(asyncio) if not n.startswith(\"_\")]\nprint(len(names))                       # 117 on Python 3.12.10\nprint(hasattr(asyncio, \"create_subprocess_shell\"))  # True\nprint(asyncio.subprocess.__name__)      # 'asyncio.subprocess'\n```\n\nOn 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.\n\n`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.\n\nEvery 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.\n\nThis 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\".\n\nModel-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.\n\nThis 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.\n\nTreat \"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:\n\n`gather(*calls)` function you wrote, not the whole `asyncio` module. Each exposed function should do one thing and take validated arguments.\nHere is the shape of a minimal broker-side check for the fourth item. It is illustrative, not a drop-in library:\n\n``` python\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass Call:\n    server: str\n    tool: str\n    args: dict\n\nPOLICY = {\n    (\"docs\", \"search\"): {\"max_calls\": 50},\n    (\"files\", \"read\"):  {\"max_calls\": 20, \"root\": \"/scratch\"},\n}\n\ndef allow(call: Call, counts: dict) -> bool:\n    rule = POLICY.get((call.server, call.tool))\n    if rule is None:\n        return False                      # unknown tool: deny\n    key = (call.server, call.tool)\n    counts[key] = counts.get(key, 0) + 1\n    if counts[key] > rule[\"max_calls\"]:\n        return False                      # batching does not escape the budget\n    root = rule.get(\"root\")\n    if root and not str(call.args.get(\"path\", \"\")).startswith(root + \"/\"):\n        return False\n    return True\n```\n\nA 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.\n\n**Is `mcp-use` unsafe to use at all?**\n\nThe 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.\n\n**Does removing `open` and `__import__` from builtins make `exec` safe?**\n\nNo. 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.\n\n**Why do two CVSS systems give different severity labels?**\n\nCVSS 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.\n\n**Is a timeout enough protection for model-written code?**\n\nA 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.\n\n**What is the safest way to let an agent batch tool calls?**\n\nGive 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.\n\n**Who is at risk if nobody attacks the library directly?**\n\nAnyone 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.", "url": "https://wpnews.pro/news/reduced-builtins-are-not-a-sandbox-what-the-mcp-use-codeexecutor-advisory-cve", "canonical_source": "https://dev.to/ginigenai_hp_0ae441ead91f/reduced-builtins-are-not-a-sandbox-what-the-mcp-use-codeexecutor-advisory-cve-2026-140133-1lej", "published_at": "2026-12-03 08:42:23+00:00", "updated_at": "2026-12-03 08:46:53.465578+00:00", "lang": "en", "topics": ["ai-agents", "ai-safety", "ai-tools", "developer-tools"], "entities": ["mcp-use", "CodeExecutor", "CVE-2026-140133", "asyncio", "Python"], "also_reported_by": [], "takeaway": "Filtering __builtins__ is not containment: mcp-use's CodeExecutor exposes all 117 public asyncio names, including create_subprocess_shell, so model-written code can spawn processes without any import.", "recommendation": {"advice": "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.", "playbook": "agent-security", "playbook_url": "https://wpnews.pro/playbooks/agent-security"}, "alternates": {"html": "https://wpnews.pro/news/reduced-builtins-are-not-a-sandbox-what-the-mcp-use-codeexecutor-advisory-cve", "markdown": "https://wpnews.pro/news/reduced-builtins-are-not-a-sandbox-what-the-mcp-use-codeexecutor-advisory-cve.md", "text": "https://wpnews.pro/news/reduced-builtins-are-not-a-sandbox-what-the-mcp-use-codeexecutor-advisory-cve.txt", "jsonld": "https://wpnews.pro/news/reduced-builtins-are-not-a-sandbox-what-the-mcp-use-codeexecutor-advisory-cve.jsonld"}}