OpenCode Code Mode explained: JavaScript instead of repeated tool calls

By

Updated

Tagged: AI

Learn how OpenCode Code Mode combines tool calls in JavaScript, when batching helps, and where permissions, errors, and side effects still need care.

Code Mode lets an OpenCode agent write a short JavaScript program that calls tools and processes their results before replying to you. I also tried Code Mode in Claude Code.

Say you need to compare a handful of records from a service. With regular tool calls, the model asks for one record, reads the full response, then asks for the next one. With Code Mode, it puts that repetitive work in a small script and gets back only the final comparison. The service still handles the same requests, while far less raw data lands in the conversation.

Code Mode is part of OpenCode v2. Let’s walk through both approaches using a small catalog example, then look at what you should check before letting a script modify real data.

A tool call is a request for an operation

A model can’t touch your filesystem or call your services directly. Instead, the coding app exposes a set of tools, each with a name, a description, and an input schema.

When the model wants to read a file, it sends a tool call request. The app runs that tool and hands the output back so the model can decide what to do next.

That back-and-forth makes sense when every step depends on the last one. Read a failing test, inspect the code behind it, then decide how to fix it. You can’t plan step three until you see what step two turned up.

Repeating the same independent read is a different story. If you already know you need four records, there’s nothing for the model to think through between the first fetch and the second.

The same job, two ways

Picture a catalog tool called get_product. You pass it a product ID, and it gives you back an object with id, name, and stock.

Suppose we want to find out which of these four made-up products have fewer than five units left:

IDProductStock
notebookNotebook18
pencilPencil3
mugMug0
bagBag12

In a regular sequential loop, the agent steps through them like this:

Model: call get_product({ id: "notebook" })
Tool: { id: "notebook", name: "Notebook", stock: 18 }

Model: call get_product({ id: "pencil" })
Tool: { id: "pencil", name: "Pencil", stock: 3 }

Model: call get_product({ id: "mug" })
Tool: { id: "mug", name: "Mug", stock: 0 }

Model: call get_product({ id: "bag" })
Tool: { id: "bag", name: "Bag", stock: 12 }

Model: Pencil and Mug have fewer than five units.

Some models and clients can already fire off several regular tool calls in a single turn. Code Mode goes further by letting the model write the filtering and control flow in code, including follow-up calls that depend on earlier results.

Inside Code Mode, the exact tool names and return shapes come from whatever your session discovers. If our catalog tool shows up as tools.catalog.get_product, the agent can run a short script instead:

const ids = ['notebook', 'pencil', 'mug', 'bag']
const products = await Promise.all(
  ids.map(id => tools.catalog.get_product({ id }))
)

return products
  .filter(product => product.stock < 5)
  .map(({ id, stock }) => ({ id, stock }))

Only pencil and mug come back to the model. The full records for the other products never clutter the context.

Fig 1 · 1/3Put the loop beside the tools
The model describes a short program for the operation.

What this can save

In the sequential version, the model takes several turns to run four lookups. Putting them into a script cuts down those round trips and keeps huge payloads out of the conversation. A tool might return dozens of fields, while the script hands back only the two you care about.

The catalog service still gets four get_product calls, though. If the API has a bulk endpoint, one bulk request beats four parallel single-record lookups. And if you’re using Code Mode for speed, measure the full task, because the payoff depends on both the service and the script.

It also helps when the next step follows a simple rule that fits right into JavaScript. A script can pull a list, grab the IDs that match, and fetch their details in one pass, instead of making the model run the same check on every record.

Try the data processing locally

Before handing the job to an agent, you can test the filtering logic locally without connecting a real catalog service. That locks down your expected input and output up front.

Save this complete example as catalog-demo.mjs:

import assert from 'node:assert/strict'

const products = new Map([
  ['notebook', { id: 'notebook', stock: 18 }],
  ['pencil', { id: 'pencil', stock: 3 }],
  ['mug', { id: 'mug', stock: 0 }],
  ['bag', { id: 'bag', stock: 12 }]
])

const tools = {
  catalog: {
    async get_product({ id }) {
      const product = products.get(id)
      if (!product) throw new Error(`Unknown product: ${id}`)
      return product
    }
  }
}

async function lowStock(ids) {
  const found = await Promise.all(
    ids.map(id => tools.catalog.get_product({ id }))
  )

  return found
    .filter(product => product.stock < 5)
    .map(({ id, stock }) => ({ id, stock }))
}

const result = await lowStock(['notebook', 'pencil', 'mug', 'bag'])

assert.deepEqual(result, [
  { id: 'pencil', stock: 3 },
  { id: 'mug', stock: 0 }
])

await assert.rejects(lowStock(['missing']), /Unknown product/)
console.log(result)

Run it with Node:

node catalog-demo.mjs

This runs in Node.js with fake tools, so you’re testing your own filtering rules and missing-record handling in isolation before running anything inside OpenCode.

What the OpenCode runtime can access

OpenCode exposes Code Mode through its execute tool. Under the hood, its interpreter implements a JavaScript-like language covering a subset of standard JavaScript APIs, and the tool documentation covers how this runtime calls tools from your session’s catalog.

Inside a Code Mode script, there’s no direct filesystem access, no imports, no timers, and no fetch. You can’t install packages from inside the script either. Whenever the code needs to read a file or talk to a remote service, it has to go through a tool exposed to the session.

That’s why you usually can’t paste a regular Node script straight into Code Mode. Our local catalog-demo.mjs uses import, assertions, and console.log, which belong to the test harness. The shorter script earlier is the kind of code the agent writes for Code Mode.

The release announcement shows how Code Mode discovers tools and exposes them under a tools namespace, with MCP servers included by default in v2.

Each tool still has its own return shape, so pay attention to whether you’re getting back a plain object, a list, or a wrapper containing raw text. The agent can’t read product.stock if the tool hands back a string that has to be parsed first.

Ask for a result rather than a guessed script

Connect only the integrations you need for the job, then describe the specific read you want:

Use the connected catalog tools to check these products:
notebook, pencil, mug, bag.

Use Code Mode for the independent reads if the tools support it.
Return only the IDs and stock counts below 5.
Report failed lookups separately. Don't change inventory.

Let the agent discover the real tool signatures from your session. Copying a script from another setup often leaves you with the right overall logic and the wrong parameter names.

After it runs, look at the generated script and the tool calls it made. Check which IDs it requested, how it handled missing records, and how much data it returned. Pulling back the entire catalog defeats the point of filtering in code.

Don’t rely on the final answer alone to verify the run. A model can easily invent believable stock numbers without ever querying the service.

Parallel work needs a limit

Running four independent lookups with Promise.all() is a fine example. Doing the same thing with ten thousand IDs will hammer the service or run straight into rate limits.

For big jobs, reach for a batch endpoint whenever the API offers one. If it doesn’t, process requests in small batches sized to whatever concurrency the service can handle.

Keep dependent steps sequential. If one call creates a record and the next call needs its ID, wait for the creation call to finish first.

The same goes for operations touching the same record. Reading a product’s stock and updating it inside one script doesn’t make those two calls atomic. Another process can still change the stock between the read and the write.

A failed script can leave completed operations

When one promise inside Promise.all() fails, the whole call rejects, but it won’t undo requests that already succeeded or stop requests already in flight.

For read-only lookups, that’s easy to live with. If one product fails to load, you can report the gap or retry that single item according to the service’s rules. When the runtime supports it, Promise.allSettled() helps you collect the outcome of every call instead of bailing out on the first error.

Writes are much trickier. Suppose a script creates four issues and the fourth call fails. If you just re-run the whole script, you can end up duplicating the first three.

Whenever a service supports idempotency keys, use them. If it doesn’t, hold on to the IDs that already succeeded so you can pick up from where the run stopped. A tool that accepts an operation key and rejects duplicates is a much safer contract for an agent than retrying and hoping for the best.

That’s also why it pays to split discovery, preview, and writes into separate steps. Have the agent show you the exact changes first, approve that list, and then run the write step against those approved items instead of regenerating an open-ended list on the fly. Here’s how that split looks in practice:

Recover a partially completed scriptIf four issue-creation calls fail partway through, retrying everything can duplicate completed work. Retain created IDs and use idempotency or deliberate resumption.YesNoCreate four issuesFourth call failsKeep IDs ofcompleted issuesService supportsidempotency?Retry usingoperation keysResume only missingwork

Permissions still apply

Allowing the execute tool turns on Code Mode, but it doesn’t automatically approve every tool in your session’s catalog.

Built-in tools and MCP tools still run their own permission checks when called from inside a script. If you build custom plugin tools, make sure they check permissions for whatever they’re allowed to do. (If you’re shipping your own tools as an npm package, see How to package and publish an OpenCode plugin.) And remember that removing fetch from the interpreter won’t make an unrestricted shell tool safe.

When you review a generated script, look at what each tool can do rather than how long the script is. A short call to a deployment tool can touch production, while a longer script doing read-only lookups carries far less risk.

Content coming back from external services is still untrusted, too. If a product description contains text telling the agent to export customer data, it’s still untrusted data from outside your app. Filtering down the returned fields gives the model less untrusted text to read, though you still need that boundary in place.

How I would use it

Code Mode works best for repeated reads with a clear filter, or when you want one small answer pulled from several independent sources.

Take my Mac apps, like Note Repo, CLI Tools Cabinet, and Tranquillity Maker. Each one ships from a GitHub repository’s Releases page. With a GitHub integration connected in OpenCode, asking for the latest release of each repo lets a single script return just the app names and version numbers, instead of watching the agent open every Releases page one turn at a time. Asking it to find failed builds across those repositories and return their URLs fits the exact same pattern.

For exploratory work, stick to regular tool calls. When the next step depends on what you just learned, you want the model pausing and reacting to each result. A script that swallows errors and keeps looping is the last thing you want when an unexpected failure should change your plan.

My advice is to stick to reads. Publishing a release or creating issues from a generated script brings back the partial-failure headaches we looked at earlier, so I’d rather approve those one at a time.

If you find yourself running the same Code Mode job every week, move that logic into a small standalone script with its own tests, credentials, and retry behavior, and call that instead.

Want me to talk about your product? You can sponsor this site.

Related posts about ai: