Back to Blog
openclaw mcp code-mode agent-workflows cost-optimization

MCP Code Mode for OpenClaw: Cut Context Costs Without Expanding Permissions

MCP makes it easier to connect a personal AI agent to useful systems. It does not make every tool definition or every returned row worth putting in the model's context.

That distinction matters when an OpenClaw workflow grows from a single lookup into a daily report spanning issues, documents, and operational data. The agent can spend much of its context budget reading schemas and copying intermediate results rather than making decisions.

Recent coverage of code execution with MCP, including Maxim's discussion of Code Mode, brings this trade-off back into focus. The underlying pattern is established, not a new MCP protocol release: let a constrained program compose tool calls, then return only the evidence the model needs.

Here is how to evaluate that pattern for a personal-agent workflow without treating token savings as permission to weaken controls.

What the primary sources actually establish

Anthropic's engineering article identifies two distinct costs: loading too many tool definitions and repeatedly passing intermediate data through the model. It describes discovering tool interfaces on demand and processing results inside an execution environment.

Cloudflare's Code Mode explanation independently describes converting MCP tools into a TypeScript API and executing generated code in a sandbox. Its design keeps external access behind the connected tool interfaces rather than giving the generated program unrestricted internet access.

Both support the same architectural point: the model does not need to read every byte that moves between systems. They do not establish a universal performance improvement for every agent or workload.

Anthropic reports a reduction from 150,000 to 2,000 tokens in its illustrated workflow. That is a specific example, not a forecast for your OpenClaw installation. Do not turn it into a promise of an equivalent reduction in your total bill.

Separate three optimizations before choosing a runtime

A useful evaluation distinguishes three changes that are often bundled together:

  1. Selective tool discovery. Load the interfaces needed for the task instead of a large, unrelated catalog.
  2. Smaller results. Ask the source for the relevant fields and rows, or filter them before returning data to the model.
  3. Programmatic composition. Run a bounded sequence of calls and transformations without asking the model to coordinate every intermediate step.

You may get enough value from the first two without introducing generated-code execution. For a single calendar lookup or a short status query, ordinary tool calling can remain simpler to operate and audit.

This is an integration design guide, not an announcement of a Clawly feature or a universal OpenClaw configuration switch. Check the capabilities and permission model of your actual client, plugin, and execution runtime before implementing it.

Start with a read-only issue digest

Consider a daily digest of open bugs in one repository. A wasteful implementation returns full issue bodies, comments, and metadata, then asks the model to count and rank them.

A better first experiment uses only the fields required by the report: issue ID, title, severity, update time, and source URL. Push filtering and field selection into the source API where supported. Otherwise, perform those transformations inside the constrained execution environment.

The following is illustrative pseudocode, not an OpenClaw command or a documented MCP tool signature:

require an explicit repository and cutoff timestamp
set a maximum page count and a total execution deadline

for each permitted page of open issues:
    call the approved read-only issue-list tool
    validate the response structure
    retain only report fields
    aggregate counts using structured labels
    keep a bounded set of relevant issue references
    stop at the last page or the configured limit

return:
    repository and cutoff timestamp
    number of issues actually scanned
    counts for the scanned set
    selected issue IDs, titles, and source URLs
    whether pagination completed
    any failures or truncation

The model then writes the digest from a compact evidence object. It should say “among the issues scanned” if pagination stopped early, not present a partial count as a repository-wide total.

Keep enough provenance to check the answer. Returning only “seven urgent bugs” saves tokens but makes verification difficult. Returning the count, the urgency rule, the scan boundary, and a few source references is more useful.

Keep authorization outside generated code

Moving work out of the conversation does not move it outside your security obligations. The sandbox and tool dispatcher—not a comment in the script—must enforce the limits.

For the first rollout:

  • Expose only the read-only tools required for the digest. Do not include issue mutation, message sending, or arbitrary network access.
  • Keep credentials in the integration's protected authentication mechanism, not in generated source or console output.
  • Enforce repository and tenant boundaries at the tool or service layer. A variable named allowed_repository is not an access-control boundary.
  • Bound execution time, memory, tool calls, pagination, and returned output. Small model output can still hide excessive backend work.
  • Treat issue titles, comments, documents, and tool descriptions as untrusted data. Processing them in code does not make embedded instructions trustworthy.
  • Record tool names, scope, outcome, and timing in access-controlled audit logs without routinely copying sensitive payloads into them.

Cloudflare's restricted-network design and Anthropic's explicit warning about sandboxing, resource limits, and monitoring are important qualifications to the efficiency story. Code execution is additional infrastructure to secure, not a shortcut around tool permissions.

For a later write-enabled workflow, require policy enforcement at each underlying action. Approval of a script must not silently authorize every destination or mutation it could invoke. Separate preparing a proposed change from executing the approved change.

Measure cost per correct digest, not just input tokens

Compare the existing workflow with the candidate on the same saved dataset and task definition. Keep the model and sampling settings consistent, record cache effects, and repeat enough runs to expose failures rather than celebrating one successful demonstration.

Record:

Measure What it tells you
Input tokens, including cached portions Whether schema and result reduction helped
Output tokens Whether generating code offset some savings
End-to-end latency Whether discovery and sandbox startup added delay
Tool calls and source API usage Whether costs merely moved downstream
Correct counts and source references Whether the answer stayed accurate and checkable
Partial results and failure reporting Whether the workflow admits incomplete work
Runtime and hosting cost Whether the complete system is cheaper

Include a denied request, an empty dataset, a malformed response, and a page-limit breach. In each case, verify that the report distinguishes failure from “nothing found.”

Define the acceptance criteria before running the comparison. For example: no unauthorized calls, no missing warnings for incomplete scans, correct counts on the fixed dataset, and a measurable reduction in total cost per successful report. A latency increase may be acceptable for a nightly digest but unacceptable for an interactive assistant.

When to leave ordinary tool calls alone

Keep the simpler path when the tool catalog is small, responses are already compact, or the task needs frequent human decisions. A generated program may introduce more failure modes than it removes.

Code-based composition is most worth testing when the workflow is repetitive, intermediate payloads are large, and the transformations are deterministic: filtering, joining, counting, or copying approved data between systems.

For OpenClaw operators, the practical next step is modest: pick one read-only workflow, measure its current behavior, reduce what enters context, and preserve evidence of what actually ran. Expand only when the result is both cheaper and at least as trustworthy.

Sources

Protect your AI agent with Clawly

Deploy your OpenClaw agent in an isolated, hardened container with encrypted credentials and managed updates. No DevOps required.

Deploy Your Agent