---
title: "Code mode"
description: "Code mode on Shotcup: a model writes a short program that calls your tools as functions, and only the result goes back to it."
canonical: "https://shotcup.dev/docs/code-mode"
last_updated: "2026-10-18"
---
# Code mode

In code mode a model does not call tools one turn at a time: it writes a
short program that calls the tools as functions, and only the program's
result goes back to the model. [Cloudflare](https://blog.cloudflare.com/code-mode/)
named the pattern in September 2025, and
[Anthropic](https://www.anthropic.com/engineering/code-execution-with-mcp)
described the same approach as code execution with MCP in November 2025.

## Why it works

Cloudflare's post turns MCP tools into a TypeScript API and asks the model
to write code against it. Its argument is that models have seen far more
real code than examples of tool calls, so they are better at writing code.
Anthropic's post starts from the context window: tool definitions and
intermediate results take up tokens, and a program can filter or join a
large result before anything reaches the model. Both run the program in a
sandbox, and Anthropic notes that model-written code needs a secure
execution environment with sandboxing, resource limits and monitoring.

That environment is what Shotcup is. You send the program and its files,
Shotcup runs it and answers with the output.

## Why Shotcup suits it

- **A fresh engine per run.** Each program starts in a new GocciaScript
  engine with only the files you send, under hard limits on time, memory
  and instructions, and the sandbox is thrown away when the run ends.
  Creating that engine took 2.07 ms at p50 on a development
  MacBook (6 October 2026).
- **The same result for the same program.** Runs are deterministic by
  default: the clock is fixed, randomness is seeded and there is no network
  access. Run the program again with the same files and the same tool
  answers and you get the same output, so you can test a model's program
  and compare two of them.
- **Live tool calls.** Declare tools with the run and the program calls
  them as `await tools.crm.listCustomers({ segment: "enterprise" })`. Your
  process answers each call while the run is going, through the
  [stream endpoint](#the-same-program-with-live-tools) or the SDK's tool
  handlers. Inside the runtime an awaited tool call cost
  20–37 µs in a prototype on a MacBook
  (6 October 2026); a call your process answers adds the
  round trip to you. Shotcup answers a small set of tools itself, the
  server-side tools; today that set is `echo`, which returns its argument
  and is useful for testing.
- **Pause and resume for approvals.** A tool declared with
  `approval: true` pauses the run at its first call. You get the pending
  call, and the run resumes by its id when a person or a system has
  answered. [Durable code mode](https://shotcup.dev/docs/durable-code-mode) covers how.
- **Answers you can use.** Every run answers with stdout and stderr, a diff
  of the files it changed and the files it wrote under `/out`, so a program
  can hand back a chart, a spreadsheet or a JSON summary instead of rows.
- **Fast enough to sit inside a model's turn.** A small run took
  5.9 ms of server time at p50 on the run endpoint and
  85.7 ms through the API on shotcup.dev
  (9 October 2026). The [performance page](https://shotcup.dev/performance) has the
  method and the other figures.

## A worked example: the orchestrator

The `code-mode-orchestrator` template is a program of the kind a model
writes in code mode. It imports three tool modules, calls them at once with
`Promise.all`, joins and aggregates 3,472 rows of customers, invoices and tickets,
and writes a compact summary for the agent that asked:

```text
main.js
tools/crm/listCustomers.js
tools/billing/getInvoices.js
tools/support/getTickets.js
data/customers.json
data/invoices.json
data/tickets.json
```

The start and the end of `main.js`:

```js
import fs from "fs";
import { listCustomers } from "./tools/crm/listCustomers.js";
import { getInvoices, daysOverdue } from "./tools/billing/getInvoices.js";
import { getTickets } from "./tools/support/getTickets.js";

const [customers, invoices, tickets] = await Promise.all([
  listCustomers(),
  getInvoices({ since: "2025-10-01" }),
  getTickets({ openOnly: true }),
]);

// ... revenue by segment and plan, overdue aging, top customers, churn risk ...

fs.mkdirSync("/out", { recursive: true });
fs.writeFileSync("/out/summary.json", JSON.stringify(summary, null, 2));
console.log(`rows=${customers.length + invoices.length + tickets.length} revenue=${summary.revenue.total} overdue=${overdue.length} churnRisk=${churnRisk.length} top=${topCustomers[0]?.name}`);
```

In the template each tool is a module that reads fixture data from
`/data`, so the program runs on its own:

```js
// Tool: crm.listCustomers: reads the CRM fixture and applies optional filters.
import fs from "fs";

export const listCustomers = async ({ segment, plan, region } = {}) => {
  const { customers } = JSON.parse(fs.readFileSync("/data/customers.json", "utf8"));
  return customers.filter((c) => (!segment || c.segment === segment) && (!plan || c.plan === plan) && (!region || c.region === region));
};
```

The 3,472 rows stay in the sandbox. The model gets one line of stdout and a
summary of about 5 KB.

### Run it over the API

Send the template's files with `files` and name the `entry`. This script
reads a copy of the template's `files` directory and runs it:

```ts
import { readdirSync, readFileSync, statSync } from "node:fs";
import { join } from "node:path";

const root = "code-mode-orchestrator/files";
const files = readdirSync(root, { recursive: true, encoding: "utf8" })
  .filter((name) => statSync(join(root, name)).isFile())
  .map((name) => ({ path: `/${name}`, content: readFileSync(join(root, name), "utf8") }));

const response = await fetch("https://shotcup.dev/api/v1/runs", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.SHOTCUP_API_KEY}`,
    "Content-Type": "application/json",
    // optional: tells Shotcup the run came from this guide
    "X-Shotcup-Integration": "code-mode",
  },
  body: JSON.stringify({ files, entry: "/main.js" }),
});
const { run } = await response.json();
console.log(run.status, run.stdout);
// succeeded rows=3472 revenue=2609567.28 overdue=921 churnRisk=49 top=…
const summary = run.artifacts.find((artifact) => artifact.path === "/out/summary.json");
```

The data files come to about 540 KiB, well inside a request. The summary
comes back as an artifact: inline when it is small, and with a link either
way. The template lives in the `@shotcup/templates` package, which is not
published to npm yet.

### Run it from a model over MCP

Connected over [MCP](https://shotcup.dev/docs/mcp), a model writes `main.js` itself and calls
`run_disposable` with the file set. Large inputs travel by URL, so the model
does not have to write the data into its tool call:

```json
{
  "entry": "/main.js",
  "files": [
    { "path": "/main.js", "content": "import fs from \"fs\";\n..." },
    { "path": "/tools/crm/listCustomers.js", "content": "..." },
    { "path": "/data/customers.json", "url": "https://example.com/exports/customers.json" }
  ]
}
```

Shotcup downloads each `url` file before the run, within your plan's
import limits. The MCP tools take files and URL imports. They do not take
declared tools, so a program run over MCP cannot call back into your
systems; use the API or the SDK for that.

### The same program with live tools

To reach your own systems, replace the modules with declared tools. The
script calls `tools.<name>`, and dotted names become nested objects:

```js
const [customers, invoices, tickets] = await Promise.all([
  tools.crm.listCustomers(),
  tools.billing.getInvoices({ since: "2025-10-01" }),
  tools.support.getTickets({ openOnly: true }),
]);
```

Start the run on the stream endpoint and declare the tools:

```sh
curl -N https://shotcup.dev/api/v1/runs/stream \
  -H "Authorization: Bearer $SHOTCUP_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"start": {"files": [...], "entry": "/main.js",
       "tools": [{"name": "crm.listCustomers"}, {"name": "billing.getInvoices"}, {"name": "support.getTickets"}]}}'
```

The response is a stream of server-sent events. `started` carries the
run's id, and each tool call arrives as a `call` event:

```text
event: call
data: {"runId":"…","callId":"c2","name":"billing.getInvoices","args":[{"since":"2025-10-01"}]}
```

Answer it with `POST /api/v1/runs/:id/calls`, with a `value` or an
`error` the script sees as a rejected promise:

```sh
curl https://shotcup.dev/api/v1/runs/$RUN_ID/calls \
  -H "Authorization: Bearer $SHOTCUP_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"results": [{"callId": "c2", "value": [{"id": "inv_0001", "customerId": "cus_0001", "amount": 120, "status": "paid"}]}]}'
```

The three calls are made at once, and you may answer them in any order. The
closing `run` event carries the finished run. A call left unanswered for
`callTimeoutMs` (30 s by default) ends the run as `host-error`, and closing
the stream cancels the run.

The [TypeScript SDK](https://shotcup.dev/docs/quickstart#5-the-typescript-sdk) does the same
with handlers, once it is published:

```ts
const run = await shotcup.runs.create(
  { files, entry: "/main.js" },
  {
    tools: {
      crm: { listCustomers: async (query) => crm.customers(query) },
      billing: { getInvoices: async (query) => billing.invoices(query) },
      support: { getTickets: async (query) => support.tickets(query) },
    },
  },
);
```

Tell the model which functions exist and what they return, in its system
prompt or in the description of the tool that runs its code. A tool
declaration's `description` and `inputSchema` are there for that, but
Shotcup does not show them to your model for you.

## Writing code the engine accepts

Shotcup runs TypeScript and JavaScript as ES modules in GocciaScript. The
default profile, `engine.compat: "strict"`, accepts semicolon insertion at
line breaks, `var`, `function`, classic `for`, `while`, labels and
`for...in`, with strict semantics. `==`, `arguments` and sloppy mode need
`"non-strict"`; a construct the run's profile leaves out fails with a
`hint` that says what to write instead. When the repair is mechanical,
`hint.fix` carries edits and a unified diff the model can apply before it
runs the code again; otherwise it is `null`. The
[quickstart](https://shotcup.dev/docs/quickstart#3-mind-the-language-profile) lists the rules.

## Next

- [Durable code mode](https://shotcup.dev/docs/durable-code-mode): pause a program for a
  person, resume it later and retry it safely.
- Guides for the [Vercel AI SDK](https://shotcup.dev/docs/ai-sdk),
  [TanStack AI](https://shotcup.dev/docs/tanstack-ai), [eve](https://shotcup.dev/docs/eve),
  [Cloudflare's Code Mode](https://shotcup.dev/docs/cloudflare-code-mode), and
  [MCP clients](https://shotcup.dev/docs/mcp) such as Claude Code.
