Practical technical guides / AI engineering: tool interoperability in code-mode agents (name resolution)

A Sandboxed Tool Named list Never Runs: Builtins Shadow Tool Names in Code-Mode Agents

In a code-mode sandbox that resolves builtins first, a tool named list or open never runs. pydantic-ai 2.67.0 rejects such names; check names at registration.

By Sandeep Belgavi · Published 2026-11-15

In a code-mode sandbox that resolves builtins first, a tool named list or open never runs. pydantic-ai 2.67.0 rejects such names; check names at registration.

A tool that was registered and never called

Code-mode agents change how tools are invoked. Instead of asking the model for one JSON tool call at a time, the agent gives the model a function per tool and lets it write a short program: fetch three orders, loop over their items, call a lookup for each, and return a summary. The program runs in a sandboxed interpreter, and every tool call inside it becomes a call back to the host. Fewer round trips and real control flow are the attraction.

The same change brings back a problem that JSON tool calling never had: name resolution. In JSON tool calling a tool name is a string the framework matches against a registry. In code mode it is an identifier in a program, and the interpreter decides what the identifier means. If the interpreter looks up its own builtins before the names the host provides, a tool called list is not the tool. It is the builtin list, and list() returns an empty list without the tool ever running.

Hansini's team at Belgavi's Book Store ran into exactly that shape while prototyping a help desk agent. Their case service exposes list (open cases), fetch (one case) and open (reopen a case). In a code-mode prototype the model wrote cases = list(), got [], and concluded that the queue was empty. Nothing raised. The tool's own logs showed no calls, which looked like a model that had decided not to use it.

The pydantic-ai fix and what it says about the sandbox

pydantic-ai has a CodeMode capability that runs model-written code in Monty, a Python interpreter built for sandboxed execution. PR 12698, merged on 6 November 2026 and released in v2.67.0 on 10 November 2026, describes the bug directly: "Monty resolves builtins before host names, so a CodeMode tool named list, open or dict never ran: list() returned [], and await open(path=...) raised a TypeError that didn't mention the tool." The fix makes CodeMode raise a UserError at setup for any tool whose name is in dir(builtins) of the running interpreter.

Two details of that decision are worth copying. The check uses the full CPython builtin list, not only the names Monty defines today, so tools named input, help, compile or exit, which worked before because Monty did not define them, now fail at setup too. The PR explains why: a builtin the sandbox adds later must not silently take over a working tool. And the suggested migration for toolsets whose names you do not control is to rename or prefix them, with toolset.prefixed(...) or toolset.renamed(...). The PR also notes that IPythonCodeMode, which runs on CPython, is unchanged, because there tools bound into the namespace already shadow builtins.

Measuring both resolution orders

The companion example records both orders offline, with no model involved. It runs four snippets in pydantic-monty 1.6.0 with host functions named list, fetch and len supplied through the external lookup, and then the same list() call in CPython with a host list in the globals.

SnippetMonty 1.6.0 resultHost function called
list()[]no
fetch()the synthetic case recordyes
len([1, 2])2no
list(range(3))[0, 1, 2]no
CPython, list() with a host list in globalsthe host's two case idsyes

In CPython, module globals are looked up before builtins, so a host function named list wins. In Monty, the builtin wins. Neither is wrong as language design; the problem is a tool contract that silently depends on which one you get. Note that len([1, 2]) returning 2 is exactly the result you would expect, which is why this class of bug survives casual testing: a tool shadowed by a builtin with a compatible signature produces plausible values.

A registration check

The fix belongs where tools are registered, not where they are called, because a failure at startup is cheap and a wrong answer in production is not. The example's check refuses three kinds of name:

import builtins
import keyword

RESERVED = frozenset(dir(builtins))


def problems(name):
    out = []
    if not name.isidentifier():
        out.append('not a Python identifier, so generated code cannot call it')
    if name in keyword.kwlist:
        out.append('a Python keyword')
    elif name in RESERVED:
        out.append('a Python builtin; a builtins-first sandbox calls the builtin instead')
    if name.startswith('__'):
        out.append('dunder names are reserved')
    return out

It also reports duplicate registrations, because two tools with one name in a code namespace means the second silently replaces the first. Soft keywords such as match and case are left alone: they are legal names in Python, and match() calls a function as usual. The reserved set matches the one pydantic-ai uses; the identifier, keyword and duplicate checks are additions in this example.

Run against the help desk prototype's tool list, the check flags list, open, dict and input as builtins, refund-status as not an identifier, and lookup_order as registered twice. fetch and match pass. After prefixing every name with shop_, the only remaining problem is shop_refund-status, which still contains a hyphen; prefixing does not fix a name that was never an identifier.

Choosing names for code mode

Prefixing is the blunt fix, and it works. A few habits make it less necessary:

  • Name tools with a verb and a noun, such as list_open_cases, fetch_case, reopen_case. Builtins are almost all single words, so two-word names rarely collide.
  • Keep the same name in JSON tool calling and in code mode. An agent that is moved from one mode to the other should not change behaviour because a name means something different.
  • Treat third-party toolsets, including tools discovered from MCP servers, as names you do not control. MCP tool names may contain characters such as hyphens and dots that are not Python identifiers at all, so they need mapping anyway; apply the prefix in the same step.
  • Put the tool list and the check in a unit test. The interpreter's builtin list changes between Python versions, so run the test on the version you deploy.

Why this is an interoperability problem

Each layer in this stack was reasonable on its own. The service team named its endpoints list, fetch and open, which are fine HTTP and JSON names. The agent framework exposed them as functions. The sandbox chose a resolution order that protects its own builtins from being replaced. The model wrote idiomatic code. The bug lives in the join, which is typical of agent interoperability: a name, schema or convention that is valid in one layer acquires a different meaning in the next. The general defence is the same as for any contract between independently built parts: make the assumption explicit, and check it when the parts are assembled rather than when the first wrong answer appears.

Failure modes

Names checked against the wrong interpreter. dir(builtins) in the host process is a proxy for what the sandbox resolves. The pydantic-ai PR notes that under IPython or Jupyter it also contains display and get_ipython, so a tool named display fails in a notebook but not in a script. Run the check in the same environment as production setup.

Attribute access instead of names. If tools are exposed as attributes, such as tools.list(), builtins cannot shadow them, but the model has to know the convention. Some frameworks do this; check which yours uses before renaming everything.

Compatible signatures hide the bug. As the len row shows, a shadowed tool whose builtin twin accepts the same arguments returns plausible data. Tests that only check types will pass.

Tool logs read as model behaviour. A tool with zero calls looks like a model that ignored it. When a code-mode agent stops using a tool after a rename or an upgrade, check resolution before tuning the prompt.

When you do not need this. In JSON tool calling, names are strings in a registry and never meet an interpreter. Validating identifiers there is still useful if you might move to code mode later, but builtins are not a risk.

Verification

The companion example pins the check's output in expected.json. Its tests assert that builtin names are refused, ordinary names pass, soft keywords stay legal while hard keywords are refused, non-identifiers and duplicates are reported, and prefixing clears builtin collisions. Two further tests read the recorded Monty run and confirm the two resolution orders: in Monty list() returned [] without calling the host, while in CPython a global list was called. The recording comes from an offline run of probe_monty.py with pydantic-monty==1.6.0, released on 11 November 2026.

Primary references and authorship

Original explanation and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/python/code_mode_builtin_names. Views are my own and do not represent any employer, past or present.