Code Execution with MCP - What Changes for Security When Agents Write Code to Call Tools
- Code execution with MCP means presenting MCP servers to an agent as code APIs (for example a folder of TypeScript files, one per tool) instead of loading every tool definition into context. The agent reads only the tools it needs and writes a script that calls them. Anthropic engineers Adam Jones and Conor Kelly described the pattern on November 4, 2025.
- The efficiency case is the headline. In Anthropic's example, loading only the needed tool files cut token usage "from 150,000 tokens to 2,000 tokens", which Anthropic calls "a time and cost saving of 98.7%". Intermediate results, such as a 10,000-row spreadsheet, can be filtered in code so the model sees a handful of rows. Cloudflare published the same idea as Code Mode in September 2025.
- Anthropic is explicit about the price: running agent-generated code "requires a secure execution environment with appropriate sandboxing, resource limits, and monitoring", which adds overhead and security considerations that direct tool calls avoid.
- For security teams, four things move: the sandbox becomes a required control, the approval point shifts from a single tool call to a whole script, data can move between systems without passing through the model (good for privacy, harder to observe), and agents can save their own code as skills that persist and get reused.
- What does not change: you still need to know which MCP servers and skills each agent can reach, whether they carry known vulnerabilities, and what each agent is allowed to run. That inventory and policy layer is where Anomity fits.
The short version: as agents connect to more MCP servers, the tool definitions alone can crowd the context window, and every intermediate result has to pass through the model on its way to the next tool. Anthropic's answer, published on November 4, 2025 in an article by Adam Jones and Conor Kelly, is to let the agent write code that calls MCP tools instead of calling them one by one. The efficiency gains are large. The security model changes too, because the thing you now have to govern is agent-written code running in an execution environment, and Anthropic says so plainly.
We have covered how MCP security works and how tool poisoning hides instructions in tool descriptions. This post looks at what happens to those risks when the model stops making tool calls directly and starts writing programs that make them.
What code execution with MCP is
Most MCP clients load every tool definition from every connected server into the model's context up front, then run a loop in which each tool call and each result passes through the model. Anthropic names two costs. Tool definitions overload the context window: with thousands of connected tools, an agent may need to process hundreds of thousands of tokens before it even reads the request. Intermediate results consume more tokens: in Anthropic's example of copying a meeting transcript from Google Drive into a Salesforce record, the full transcript flows through the model twice, which for a two-hour meeting could mean an additional 50,000 tokens. Large documents can exceed the context window outright, and the model can make mistakes copying data between calls.
The alternative is to present MCP servers as code APIs. Anthropic's TypeScript example generates a servers/ directory with a folder per server (for example google-drive and salesforce) and a file per tool, each a small typed wrapper around a generic MCP call. The agent lists the directory to find servers, opens only the tool files the task needs, and writes a short script that reads the transcript and writes it to Salesforce. The transcript never enters the model's context.
| Direct tool calls | Code execution with MCP | |
|---|---|---|
| Tool definitions | All loaded into context up front | Read on demand from files or a search tool |
| Intermediate results | Pass through the model between calls | Stay in the execution environment unless logged |
| Loops and conditions | One model turn per step | Run as ordinary code |
| Unit of review | A single tool call | A script that may make many calls |
| Extra infrastructure | None beyond the MCP client | A sandboxed execution environment |
Why teams use it: the numbers Anthropic reports
In Anthropic's example, letting the agent load only the definitions it needs reduced token usage "from 150,000 tokens to 2,000 tokens", described as "a time and cost saving of 98.7%". Treat that as Anthropic's figure for its own illustration, not a universal ratio. The article groups the other benefits into four areas:
- Progressive disclosure. Tools are read from the filesystem when needed, or found with a
search_toolstool that can return just names, names and descriptions, or full schemas. - Context-efficient results. Code can filter, aggregate or join data before anything returns to the model. Anthropic's example fetches a 10,000-row spreadsheet and shows the model five rows.
- Control flow in code. Loops, conditionals and retries run in the environment. Polling a Slack channel for a deployment message becomes one loop instead of alternating tool calls and sleeps through the agent loop.
- State and skills. With filesystem access, agents can write intermediate results to files and save working code as reusable functions, which a SKILL.md file can turn into a skill.
Anthropic notes that Cloudflare published similar findings as Code Mode in September 2025. A few weeks after the article, Anthropic shipped Programmatic Tool Calling in beta on the Claude Developer Platform, which lets Claude call tools from inside a code execution environment. Anthropic reported that on complex research tasks average usage dropped "from 43,588 to 27,297 tokens, a 37% reduction". Tools opt in to being called from code through an allowed_callers field, which is a useful control in its own right.
The caveat Anthropic puts in writing
The article does not oversell the pattern. It says code execution introduces its own complexity, that running agent-generated code requires a secure execution environment with appropriate sandboxing, resource limits, and monitoring, and that these requirements add operational overhead and security considerations that direct tool calls avoid. Its advice is to weigh the lower token cost, lower latency and better tool composition against those costs. That is the right frame: this is a move from a protocol problem to a code execution problem, and code execution has a long security history.
Security implication 1: the sandbox becomes a required control
With direct tool calls, the MCP client executes each call and the model never runs code. With this pattern, the model writes code and something runs it. That something has to be isolated. Anthropic's own writing on sandboxing Claude Code says effective sandboxing needs both filesystem and network isolation: without network isolation a compromised agent could exfiltrate files such as SSH keys, and without filesystem isolation it could escape the sandbox and gain network access.
Cloudflare's Code Mode shows what a strict version looks like. Its sandbox is isolated from the internet, the global fetch() and connect() calls throw errors, and the code reaches its MCP servers only through bindings. The supervisor holds the access tokens and adds them to requests, and Cloudflare says this means the AI cannot write code that leaks the keys, because the keys are never in the sandbox. Whatever runtime you use, the questions are the same:
- Can the code reach anything other than the MCP servers it was given?
- Are MCP and API credentials held outside the environment, or sitting in environment variables the code can read?
- Are CPU, memory, time and file limits set, as Anthropic recommends?
- Is the environment thrown away after each run, or does state carry over between tasks?
Security implication 2: the approval point moves from a call to a script
Many agent controls are built around the individual tool call: a client shows the call, a user approves it, or a hook evaluates it. When the model writes a script, one approved code-run step can make dozens of MCP calls in a loop, with arguments computed at runtime. A reviewer who sees the script sees intent, not the actual values each call will carry.
That does not make per-call control impossible. In Anthropic's design every tool file routes through a single client function, which is the natural place to enforce a policy, and Programmatic Tool Calling makes calling a tool from code an explicit opt-in. Our read is that controls should sit at two layers: what code may run at all (the code execution or shell step) and which MCP tools that code may reach, with what scope (the client or gateway that brokers each call). Approving a script on a quick read is the code execution version of approval fatigue.
Security implication 3: MCP server trust and the supply chain do not go away
Progressive disclosure changes when a server's metadata reaches the model, not whether it does. The generated tool files and any search_tools results are built from what each MCP server advertises, and the model reads them to decide how to call the tool. A poisoned description is read later, when the agent opens that file, rather than at startup. The server code also still runs with whatever access it was configured with.
So the basic hygiene stays the same: know every MCP server connected to every agent, where it came from, and which version is installed; check it against known vulnerabilities and malicious packages; and keep its credentials scoped to the task. A registry of approved MCP servers matters more, not less, once agents can chain those servers together in code. The Anomity vulnerability database tracks CVEs and advisories for MCP servers and AI agents for exactly this check.
Security implication 4: data moves without passing through the model
Anthropic presents this as a privacy benefit, and it is one. Intermediate results stay in the execution environment by default, so the model sees only what the code logs or returns. For sensitive workloads the article describes an MCP client that tokenizes personal data before the model sees it: the model works with placeholders such as [EMAIL_1], and the client swaps the real values back in when they are passed to the next tool. Anthropic adds that the same mechanism can enforce deterministic rules about where data may flow.
The flip side is visibility. A loop that copies every row of a spreadsheet into a CRM is a bulk data movement that may show up in the model's transcript as a single line such as "Updated 1,000 leads". If the code is steered by injected content, the same efficiency applies to exfiltration. That is the lethal trifecta in a more efficient form: private data, untrusted content and an outbound channel, joined by a loop. Data-flow rules belong in the client or gateway, and logs of what the code actually did belong outside the model's context.
Two smaller points follow from the same design. Whatever the code prints is returned to the model, so a careless log line can put the data back in context. And state written to the workspace, such as the CSV of leads in Anthropic's example, is now data at rest that needs the same handling as any other export.
Security implication 5: saved code becomes persistent skills
The most durable change is that agents can save their own code for later runs. Anthropic's example stores a function under ./skills/ and suggests adding a SKILL.md file so it becomes a skill the model can find and reuse, giving the agent, in Anthropic's words, a toolbox of higher-level capabilities. That is useful, and it means agent-written code now outlives the session that wrote it. A function written while the agent was reading untrusted content can be imported by a later, unrelated task.
Anthropic's own Agent Skills documentation sets the standard to apply: use skills only from trusted sources, audit every bundled file for unexpected network calls or file access, and remember that a malicious skill can call tools or run code in ways that do not match its stated purpose, and that skills which fetch from external URLs can change over time. The Agent Skills standard is now shared across many agents, so a skills folder deserves an inventory and a change log, and the Anomity Skill Risk Index shows what scanning public skills turns up.
What to monitor
- Which agents run code execution at all, and in which environment: a hosted sandbox, a local container, or the developer's own shell.
- Which MCP servers each agent can reach, with versions, sources and credential scope.
- Which tools are callable from code, for example through
allowed_callersor the equivalent setting in your client. - What the code did, at the MCP client or gateway: tools called, call counts and destinations, kept outside the model's context. See our guide to AI agent audit trails.
- New or changed skills and saved functions, treated like code changes rather than configuration.
How Anomity fits
Anomity does not run the execution sandbox and does not read the code an agent writes inside it. It covers the layer the pattern depends on. See it: the Anomity Endpoint Sensor discovers AI agents, MCP servers, skills, plugins, hooks, CLIs and local LLM runtimes on every managed machine, so you know which agents can reach which MCP servers and which skills are installed where. It flags secrets it recognizes in MCP server definitions and agent configs, reporting metadata only, with values redacted on the endpoint. Cloud discovery adds Google Workspace and GitHub OAuth grants. Check it: the vulnerability database and the Skill Risk Index give a starting point for judging what is installed.
Enforce before it runs: on agents that expose a pre-execution hook, such as Claude Code PreToolUse, Anomity can allow, deny or log a call, including the shell or code-run step, before it executes. Keep the record: inventory changes and decisions land in a 90-day audit trail and route to SIEM, Slack, email or Jira. Anomity is SOC 2 Type II and complements sandboxing, EDR, DLP and GRC tooling rather than replacing them. To see which MCP servers and skills your agents can reach today, book a 30-minute demo.
Frequently asked questions
What is code execution with MCP?
It is a way of connecting agents to Model Context Protocol servers in which the MCP tools are exposed as a code API rather than as direct tool calls. Anthropic's example generates a file tree with one folder per MCP server and one TypeScript file per tool. The agent lists the folders to discover servers, reads only the tool files it needs, and then writes code that calls those tools, filters the results and passes data between them. Only what the code logs or returns goes back into the model's context.
How many tokens does code execution with MCP save?
Anthropic's article reports that, in its example, loading only the needed tool definitions reduced token usage from 150,000 tokens to 2,000 tokens, which it describes as a time and cost saving of 98.7%. It also notes that passing a two-hour meeting transcript between two tools by direct tool calls could mean processing an additional 50,000 tokens. These are Anthropic's illustrative figures for its own examples, not a benchmark of every workload.
Is this the same as Cloudflare Code Mode or Programmatic Tool Calling?
They are closely related. Cloudflare's Code Mode, published on September 26, 2025, converts MCP tools into a TypeScript API and runs the agent's code in an isolated Workers sandbox. Anthropic's article cites it as similar findings. On November 24, 2025 Anthropic released Programmatic Tool Calling on the Claude Developer Platform in beta, which lets Claude call tools from inside a code execution environment; tools opt in through an allowed_callers field. The article itself describes a general pattern rather than one product.
Is code execution with MCP more secure than direct tool calls?
It is a trade, not an upgrade. Anthropic says the approach has security and state management benefits, mainly around privacy: intermediate results stay in the execution environment by default, and an MCP client can tokenize personal data so real values flow between tools without entering the model's context. It also says running agent-generated code requires a secure execution environment with sandboxing, resource limits and monitoring, and brings security considerations that direct tool calls avoid. Neither Anthropic's article nor Cloudflare's Code Mode post discusses prompt injection, so do not treat the pattern as a defense against it; the sandbox and the controls around it carry that weight.
What should the sandbox for agent-written code enforce?
Anthropic's own sandboxing work for Claude Code says effective sandboxing needs both filesystem isolation and network isolation: without the first an agent could escape, without the second it could exfiltrate files such as SSH keys. Cloudflare's Code Mode goes further by blocking general internet access and letting the code reach only its connected MCP servers through bindings, with API keys held outside the sandbox. Add the resource limits and monitoring Anthropic names, and keep long-lived credentials out of the environment.
Why do saved skills matter for security?
Anthropic describes agents saving working code as reusable functions, and adding a SKILL.md file to turn them into skills that later runs can use. That makes agent-written code persistent: it outlives the session and can be imported by future tasks. Anthropic's Agent Skills documentation advises using skills only from trusted sources, auditing every bundled file, and notes that a malicious skill can call tools or run code in ways that do not match its stated purpose. Saved skills deserve the same review and change tracking as any other code.
How does Anomity help with this?
Anomity does not run or inspect a code execution sandbox. It covers the layer around it. The Endpoint Sensor discovers agents, MCP servers, skills, plugins, hooks and CLIs on every managed machine, so you can see which MCP servers and skills each agent can reach, and it flags secrets in MCP server definitions while redacting values on the endpoint. On agents with a pre-execution hook, such as Claude Code PreToolUse, Anomity can allow, deny or log a call, including a shell or code-run call, before it runs. Changes land in a 90-day audit trail and route to SIEM, Slack, email or Jira. The Anomity vulnerability database tracks CVEs and advisories for MCP servers and AI agents. Anomity complements sandboxing, EDR and DLP rather than replacing them.




