Skip to content
Go back

Cloudflare Codemode: Let the Model Write Code to Commit Your Changes

I want an AI to commit my code. For that it needs two abilities: read my staged changes, and run the commit. I’ve put both behind an MCP server, the git tools server from part 1 of the MCP series.

Normally a model uses an MCP tool by writing a small block of JSON, which your program runs before sending the result back so the model can write the next block, and every step goes through the model.

In this post the model writes no JSON. It writes a short TypeScript program that reads the staged diff, builds a message from it and calls commit. That program runs in a sandbox with no internet, where the only way out leads to the git MCP server, and because it’s a running program it can be paused: I marked commit as needing my approval, so the code stops right at that line and waits for a click.

This approach is called Codemode, from Cloudflare.

We’ll build it from an empty folder: a small chat agent that reads the diff of your staged changes and commits them, plus a page with Approve and Reject buttons. I’ll also say plainly when Codemode is worth it and when it isn’t, because for this exact demo it barely saves anything.

The finished code is in the codemode-git-tools repo.

The problem Codemode goes after

The usual flow: your agent asks the MCP server what tools it has (names, descriptions, argument schemas) and pastes that whole list into the model’s context, which is everything the model can see at that moment: your instructions, the chat so far and those tool descriptions.

That list doesn’t go in once. It goes in on every request, for every tool, whether or not the model touches that tool this turn. Connect a GitHub server, a payments API and an internal API, and you’re carrying thousands of tokens of tool descriptions into every message, mostly for tools that never get used. You pay for that in tokens and latency, and it takes room the model could use to think.

When the model wants a tool, it writes a special marker and a JSON message naming the tool and its arguments. Your program runs it and feeds the result back.

In September 2025 Cloudflare published Code Mode: the better way to use MCP, which names two problems with this.

Models are only okay at tool calls. The post says the special tool-calling tokens are trained on synthetic data, while ordinary code shows up in training data in huge amounts from real projects. Its comparison: tool calling is like putting Shakespeare through a month-long class in Mandarin and then asking him to write a play in it. With many tools, or messy ones, the model starts picking the wrong one or filling in arguments badly.

Every result passes through the model. Say a job needs three calls in a row: list pull requests, pick one, fetch its comments. The first result has to enter the context so the model can copy a value out of it into the second call. You pay tokens and wait, and the model works one step at a time.

How Codemode works

Codemode gives the model one tool, named codemode, and that tool takes code. The model writes a short TypeScript function. For our job, that function gets the staged diff with git.git_diff(), builds a commit message, calls git.git_commit({ message }) and returns the result.

A runtime runs that code in a sandbox with no internet. The only way out is through the MCP servers you connect. Each server shows up in the sandbox as a typed object, so the model writes git.git_diff() and TypeScript types tell it what exists. Loops, filters and passing one result into the next call are just ordinary code. Values stay in the sandbox; only what the code returns goes back to the model.

That saves in three places:

When it’s worth it (not here)

I built this demo, and for this task Codemode saves very little. Our job is git_diff then git_commit, two calls either way, with no loop to remove and no chain of values to hide. The model has to read the diff anyway, since it can’t write a message about changes it hasn’t seen, and the diff is the biggest piece of data in the flow. Two tools is a tiny catalog. Codemode also adds its own fixed description of the sandbox, which can eat the small saving.

Codemode pays off with many MCP servers connected at once, or with tasks that pull in lots of data and boil it down. Here we use the project to learn the moving parts, especially the approval flow, which is useful whatever the token numbers say. Every response carries a stats object, so you can check this yourself in step 7.

There’s a catch on the model side, too: it has to write working code against an API it has never seen. A strong model does that in a step or two. A weak one forgets to return a value, calls methods that don’t exist, or burns several steps reading docs. We’ll use openrouter/free, which routes to whatever free model is available. That’s the weak case, on purpose.

In my runs, free models sometimes wrote await git.git_diff() with no return. The code ran fine and nothing came back. My fix is a hint: a short instruction with a literal example, placed where the model always sees it. We write it in step 3. If you can pay for a stronger model, set MODEL_ID and the hint matters less.

The whole system

Streamlit UI (ui/app.py)  ->  Worker + Chat agent (src/server.ts)  ->  Python git MCP server (:8000)
   approve / reject            Codemode runtime + sandbox

Three names to remember:

You need Node, Python 3.14 with uv, git, and a free OpenRouter API key. You don’t need a Cloudflare account; everything runs on your machine.

Step 1: the git server and a scratch repo

The server is the one from part 1, with a new --transport option. It used stdio before, where the app launches the server as a child process. A Worker can’t spawn processes, so the server has to listen on the network instead, which is what --transport streamable-http does.

If you skipped part 1, clone the server. If you have an older copy, git pull to get the transport option.

git clone https://github.com/nononsense-ai/git-tools-mcp-server.git
cd git-tools-mcp-server
uv sync

In a second terminal, make a scratch repo to test on. One commit, then a second change that we stage and leave uncommitted. That staged change is what the model will read.

mkdir scratch-repo && cd scratch-repo
git init
echo "hello" > notes.txt
git add notes.txt
git commit -m "init"
echo "a second line" >> notes.txt
git add notes.txt

Back in the first terminal, start the server, pointed at the scratch repo, over HTTP:

GIT_TOOLS_REPO=/absolute/path/to/scratch-repo uv run git-tools-mcp-server --transport streamable-http

It listens on port 8000 at /mcp. Leave this terminal alone.

Step 2: the project shell

One tool you haven’t met yet: Wrangler, Cloudflare’s command line for Workers. It runs your Worker locally, generates TypeScript types from your config and uploads to Cloudflare when you deploy (we won’t deploy here). You won’t call it much by hand, because npm run dev goes through Vite, and the Cloudflare Vite plugin reads the Wrangler config for you.

Make a folder for the project and run git init in it. Then package.json:

{
  "name": "codemode-git-tools",
  "version": "1.0.0",
  "private": true,
  "description": "Cloudflare Codemode demo: an agent that reads staged git diffs and commits with human approval",
  "type": "module",
  "scripts": {
    "dev": "vite dev",
    "build": "vite build",
    "deploy": "vite build && wrangler deploy",
    "typecheck": "tsc --noEmit",
    "types": "wrangler types"
  },
  "dependencies": {
    "@cloudflare/codemode": "^0.5.6",
    "@openrouter/ai-sdk-provider": "^3.1.0",
    "agents": "^0.34.0",
    "ai": "^7.0.179",
    "zod": "^4.6.7"
  },
  "devDependencies": {
    "@cloudflare/vite-plugin": "^1.70.1",
    "typescript": "^7.0.2",
    "vite": "^8.3.8",
    "wrangler": "^4.166.0"
  }
}

agents and @cloudflare/codemode give us the agent and the sandbox. ai (the AI SDK) and the OpenRouter provider talk to the model. zod describes tool inputs. Vite and Wrangler are only for development. Run npm install; it took about two minutes for me.

wrangler.jsonc

This is the single description of your Worker, and the same file drives local and production so they don’t drift:

{
  "name": "codemode-git-tools",
  "main": "src/server.ts",
  "compatibility_date": "2026-11-01",
  "compatibility_flags": ["nodejs_compat"],
  "durable_objects": {
    "bindings": [{ "name": "Chat", "class_name": "Chat" }]
  },
  "migrations": [{ "tag": "v1", "new_sqlite_classes": ["Chat"] }],
  "worker_loaders": [{ "binding": "LOADER" }]
}

Two fields matter most. durable_objects: a Durable Object is a small program with its own storage, and that storage stays around between requests. Our chat agent is one, so we list it here. The runtime keeps its log and its pending approvals in that storage, which is how a run can pause, wait for your click and carry on later. migrations tells Cloudflare to set up that storage for Chat.

worker_loaders gives us LOADER, our way to start sandboxes. Every script the model writes gets its own fresh sandbox.

vite.config.ts

import codemode from "@cloudflare/codemode/vite";
import agents from "agents/vite";
import { cloudflare } from "@cloudflare/vite-plugin";

// The codemode plugin appends the CodemodeRuntime export to src/server.ts.
export default {
  plugins: [agents(), codemode(), cloudflare()],
};

The Codemode plugin appends a CodemodeRuntime export to src/server.ts at build time. You never write it.

tsconfig.json

Short, so TypeScript knows about the Workers types:

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "es2022",
    "moduleResolution": "bundler",
    "strict": true,
    "skipLibCheck": true
  },
  "include": ["src/**/*.ts", "worker-configuration.d.ts"]
}

.gitignore and secrets

# Node / build
node_modules/
dist/

# Cloudflare / Wrangler local state
.wrangler/

# Secrets (copy .dev.vars.example to .dev.vars)
.dev.vars
.env

# Python
.venv/
__pycache__/
*.pyc

# OS
.DS_Store

.dev.vars is listed because it holds your secret. Keep a template called .dev.vars.example with no key in it; that one is safe to commit:

OPENROUTER_API_KEY=your-openrouter-key
# Optional: defaults to openrouter/free
MODEL_ID=openrouter/free

Copy it to .dev.vars and paste in your own OpenRouter key. The model already defaults to the free one, so you can leave that line alone.

Then generate the types:

npm run types

This reads wrangler.jsonc and .dev.vars and writes worker-configuration.d.ts, which defines the Env type. Our code can use Env without importing it, and TypeScript catches a typo in a variable name. The file is big; don’t edit it. Run the command again whenever you change the config.

Step 3: the connector

The connector is the bridge between the sandbox and the MCP server. The model’s code runs in the sandbox, and the sandbox has no internet, so when the code calls git.git_diff(), the call goes through the connector to the MCP server and the answer comes back.

McpConnector, a class from Codemode, already does most of the work. It reads the server’s tools and turns each one into a method the code can call, so our class is mostly settings. Create src/gittools.codemode.ts and start with the imports and two constants:

import {
  ConnectorTool,
  McpConnectionLike,
  McpConnector,
} from "@cloudflare/codemode";

// The sandbox global the model calls, as in git.git_commit(...).
export const GIT_CONNECTOR_NAME = "git";
export const GIT_CONNECTOR_HINT =
  "Read staged git diffs and commit them (commit needs user approval). Call git.git_diff() before git.git_commit({ message }) so the message matches the changes. Always return the result, e.g. `return await git.git_diff();`, otherwise you get no output.";

McpConnector is the class we build on, McpConnectionLike is the type of an MCP connection, and ConnectorTool describes one tool.

The first constant is the sandbox name, git. That’s why the model writes git.git_diff(). The second is the hint, the note telling the model to return its results, which openrouter/free sometimes forgets to do. We export both because the chat agent needs them too; you’ll see why in step 4.

Now the class:

// Exposes the Python git MCP server inside the sandbox. McpConnector turns each
// MCP tool into a typed method, so there is no per-tool code here.
export class GitToolsConnector extends McpConnector<Env> {
  constructor(
    // Inside a Durable Object this is DurableObjectState, which the base class accepts.
    ctx: DurableObjectState | ExecutionContext,
    env: Env,
    private conn: McpConnectionLike,
  ) {
    super(ctx, env);
  }

The constructor takes three things.

ctx is a handle to whatever is running your code right now. In a plain Worker it’s an ExecutionContext: it lives for one request and has no storage. In a Durable Object it’s a DurableObjectState: it lives as long as the object does and has saved storage. The runtime keeps its call log and pending approvals in a child object made from that storage, so an agent that has to pause and resume later must live in a Durable Object. Our connector accepts either type.

env holds everything your Worker was configured with: the bindings from wrangler.jsonc and the variables from .dev.vars. Its type is the Env we generated. A connector for an API that needs a key would read it from this.env, which keeps the secret in your code and out of the model’s reach. Our git server needs no key, but the base class wants env anyway.

conn isn’t part of the base class. It’s the MCP connection the agent already has open. We keep it in a private field so the connector doesn’t open a second connection.

The body passes ctx and env to the parent, which keeps both. Now the methods:

  name() {
    return GIT_CONNECTOR_NAME;
  }

  protected instructions(): string | undefined {
    return GIT_CONNECTOR_HINT;
  }

  // The agent already manages the MCP connection, so reuse it.
  protected createConnection(): Promise<McpConnectionLike> | McpConnectionLike {
    return this.conn;
  }

  // Called for every MCP tool. A gated call pauses the run until someone
  // approves it; everything else, like reading a diff, runs immediately.
  protected tool(name: string, t: ConnectorTool): ConnectorTool {
    return name === "git_commit" ? { ...t, requiresApproval: true } : t;
  }
}

name gives back the sandbox name, so the MCP server shows up in the sandbox as git. instructions gives back the hint; the model can read it if it calls codemode.describe(). createConnection tells the base class which MCP connection to use, and we return the one saved in the constructor.

tool is called once for each tool on the MCP server, and it holds the whole approval rule. If the tool is git_commit, we mark it as needing approval, so the run pauses whenever the code calls it. Every other tool, like reading the diff, just runs.

Step 4: the chat agent

Create src/server.ts. The imports:

import { generateText, stepCountIs } from "ai";
import { createOpenRouter } from "@openrouter/ai-sdk-provider";
import {
  createCodemodeRuntime,
  DynamicWorkerExecutor,
} from "@cloudflare/codemode";
import { Agent, callable, getAgentByName, routeAgentRequest } from "agents";
import {
  GIT_CONNECTOR_HINT,
  GIT_CONNECTOR_NAME,
  GitToolsConnector,
} from "./gittools.codemode";
// The codemode vite plugin appends the CodemodeRuntime export (the Durable
// Object facet that holds the audit log and approvals) to this file.

From the AI SDK, generateText calls the model and stepCountIs limits how many rounds it gets. createOpenRouter connects us to OpenRouter. From Codemode, createCodemodeRuntime builds the runtime and DynamicWorkerExecutor starts the sandbox. From the agents package, Agent is the base class for our chat agent, and getAgentByName and routeAgentRequest are for the Worker’s fetch function. We won’t use callable until step 5. Last, our connector and its two constants.

The class and the MCP connection

Agent from the agents package is a Durable Object underneath, so we get the private saved storage the runtime needs. Agent<Env> hands our generated Env type down, so this.env is type-checked. Everything that follows goes inside this class.

export class Chat extends Agent<Env> {
  async onStart() {
    // Start the Python git server first. If it's down, the connection won't be
    // "ready" and codemode() throws with a message saying so.
    await this.addMcpServer("git-tools", "http://127.0.0.1:8000/mcp", {
      id: "git-tools",
    });
  }

onStart runs when the agent starts. It connects to the Python git server on port 8000 and names the connection git-tools so we can find it later. If the server is down, the connection never becomes ready, and we catch that next.

The runtime

Building a runtime for every request would be wasteful, so we keep one:

  // One runtime per MCP connection. The connector holds on to the connection
  // object, so a reconnect gives us a new one and we have to rebuild.
  // Paused runs and the call log live in the facet's SQLite, not in this
  // handle, so rebuilding or a cold start loses nothing.
  private runtimeCache?: {
    conn: unknown;
    runtime: ReturnType<typeof createCodemodeRuntime>;
  };

The cache remembers which connection it was built for, because the connector holds on to the connection object and a reconnect gives us a new one. Rebuilding loses nothing, since paused runs and the call log live in the runtime’s own storage, not in this field.

  codemode() {
    const conn = this.mcp.mcpConnections["git-tools"];
    if (!conn || conn.connectionState !== "ready") {
      this.runtimeCache = undefined;
      throw new Error(
        `MCP server "git-tools" is not ready (state: ${conn?.connectionState ?? "missing"}). Is the Python server running on :8000 with --transport streamable-http?`,
      );
    }
    if (this.runtimeCache?.conn === conn) return this.runtimeCache.runtime;

    const runtime = createCodemodeRuntime({
      ctx: this.ctx,
      executor: new DynamicWorkerExecutor({ loader: this.env.LOADER }),
      connectors: [new GitToolsConnector(this.ctx, this.env, conn)],
    });
    this.runtimeCache = { conn, runtime };
    return runtime;
  }

First it finds our connection and checks that it’s ready. If not, it clears the cache and throws an error saying the Python server probably isn’t running in streamable HTTP mode. You’ll see that error if you skip step 1. If we already built a runtime for this connection, we return it. Otherwise we build one from three things: ctx, the agent’s storage, where the runtime keeps its log; the executor, which uses LOADER from wrangler.jsonc to start a sandbox for each script; and our connector.

The tool and the model

  // The hint goes into the tool description, which the model always sees.
  // The connector's instructions() only show up when the model calls
  // codemode.describe(), so we keep both and share one constant.
  codemodeTool() {
    return this.codemode().tool({
      connectorHints: { [GIT_CONNECTOR_NAME]: GIT_CONNECTOR_HINT },
    });
  }

  // Defaults to OpenRouter's free router; set MODEL_ID in .dev.vars to pin a model.
  model() {
    const openrouter = createOpenRouter({
      apiKey: this.env.OPENROUTER_API_KEY,
    });
    return openrouter(this.env.MODEL_ID || "openrouter/free");
  }

codemodeTool turns the runtime into the one codemode tool the model gets, and passes our hint in with connectorHints. This is why we exported the hint. The connector’s instructions() only reach the model if it calls codemode.describe(), and free models often skip that. A connector hint goes straight into the tool description, which the model always reads. So the same hint ends up in two places.

model creates an OpenRouter client with the key from .dev.vars and picks the model named in MODEL_ID, falling back to openrouter/free.

Handling one prompt

  // Runs one prompt through the model with the codemode tool. Returns a JSON
  // string, which crosses the Durable Object RPC boundary without surprises.
  async ask(message: string) {
    const started = Date.now();
    const result = await generateText({
      model: this.model(),
      messages: [{ role: "user", content: message }],
      tools: { codemode: this.codemodeTool() },
      stopWhen: stepCountIs(8),
    });

generateText gets four things: the model, the user’s message, the tools (just codemode) and a limit of 8 steps. A step is one round with the model: it answers, and if it asked for a tool, the tool runs its code in the sandbox and the result goes back. A normal run takes two steps: write the code, then read the result and answer. The limit stops a confused model from looping forever.

After the model finishes, we ask the runtime what’s waiting for approval:

    // pending() without an id returns every paused run, so an old one would
    // make this request look paused. Ask only about the executions this
    // request started, read from the tool results.
    const runtime = this.codemode();
    const executionIds = new Set<string>();
    for (const step of result.steps) {
      for (const r of step.toolResults) {
        const out = (r as { output?: { executionId?: string } }).output;
        if (out?.executionId) executionIds.add(out.executionId);
      }
    }
    const pending = (
      await Promise.all([...executionIds].map((id) => runtime.pending(id)))
    ).flat();

Every time the model uses the codemode tool, the result includes an execution ID for that run. The loop collects those IDs, and runtime.pending(id) returns that run’s paused actions. We ask only about this request’s runs, because calling pending() with no ID returns every paused run, and an old one would make a new request look paused.

    const elapsedMs = Date.now() - started;
    const stats = {
      elapsedMs,
      stepCount: result.steps.length,
      inputTokens: result.totalUsage.inputTokens,
      outputTokens: result.totalUsage.outputTokens,
      totalTokens: result.totalUsage.totalTokens,
    };
    console.log("[ask]", JSON.stringify(stats));
    return JSON.stringify({
      status: pending.length ? "paused" : "done",
      text: result.text,
      stats,
      steps: result.steps.map((s) => ({
        toolCalls: s.toolCalls,
        toolResults: s.toolResults,
      })),
      pending,
    });
  }
}

The stats are how long it took, how many steps, and the token counts. We also log them to the npm run dev terminal. Then we return one JSON string with five fields:

We return a string because it’s the simplest thing to pass from the Durable Object back to the Worker. That closes the class for now.

A first fetch

The Worker’s fetch function receives every HTTP request, in our case from the Streamlit app. For now it handles one: POST /chat.

export default {
  async fetch(request: Request, env: Env) {
    const url = new URL(request.url);

    if (url.pathname === "/chat" && request.method === "POST") {
      // Every client shares one agent. Fine for a local demo.
      const stub = await getAgentByName(env.Chat, "demo");
      const { message } = (await request.json()) as { message: string };
      return new Response(await stub.ask(message), {
        headers: { "content-type": "application/json" },
      });
    }

    return (
      (await routeAgentRequest(request, env)) ||
      new Response("Not found", { status: 404 })
    );
  },
} satisfies ExportedHandler<Env>;

It finds the agent named demo with getAgentByName, so every request shares the same agent. Anything else goes to routeAgentRequest, and if that finds nothing we return a 404.

Try it

Type-check, then start the dev server, which listens on port 5173:

npm run typecheck
npm run dev

In a third terminal, send the first request:

curl -s -X POST http://localhost:5173/chat \
  -H "content-type: application/json" \
  -d '{"message": "show me my staged diff"}'

Look at the stats first, and keep an eye on stepCount. Then find the code the model wrote in steps, with its return. If you get MCP server "git-tools" is not ready, the Python server isn’t running.

Now the real test:

curl -s -X POST http://localhost:5173/chat \
  -H "content-type: application/json" \
  -d '{"message": "commit my staged changes with a good message"}'

The status says paused, and git log in the scratch repo shows no new commit. The model’s code got to the commit call and the runtime stopped it right there.

Step 5: approve and reject

Right now a paused run is stuck. When the model’s code reaches git.git_commit(), the runtime saves the run and waits for a human to decide. But our only route is /chat, which only starts new runs. Nothing in our code can approve or reject, so the commit just sits there.

So what happens when you approve? The runtime runs the same code again from the start. Calls that already finished, like git_diff, get their answers from the saved log so they don’t run twice, while the call that was waiting now runs for real and the script carries on. That’s why the model’s code needs no pause or resume logic. Cloudflare’s runtime docs call this abort and replay.

Add six methods to the Chat class, each a thin wrapper over one runtime call. @callable() marks them as methods a client can call on the agent.

  // Every paused run, including old ones. ask() scopes its own list instead.
  @callable() async listPending() {
    return await this.codemode().pending();
  }

  // Replays the paused run and runs the approved action for real. The result
  // is completed, paused again (another gated call) or error.
  @callable() async approve(executionId: string) {
    return await this.codemode().approve({ executionId });
  }

  // False means the action was no longer pending (approved, rejected or expired
  // elsewhere), so this call rejected nothing and the action may have run.
  @callable() async reject(executionId: string, seq: number) {
    return await this.codemode().reject({ executionId, seq });
  }

  // Calls `revert` on each applied action that defines one. git_commit has
  // none, so rolling back a commit changes nothing.
  @callable() async rollback(executionId: string) {
    await this.codemode().rollback({ executionId });
    return { status: "rolled_back", executionId };
  }

  // Marks paused runs older than maxAgeMs (24 hours by default) as rejected.
  @callable() async expirePaused(maxAgeMs?: number) {
    return await this.codemode().expirePaused({ maxAgeMs });
  }

  // The audit trail, newest first.
  @callable() async executions(limit?: number) {
    return await this.codemode().executions(limit);
  }

The full fetch

Replace the simple fetch with the full one. First a list of the paths we handle:

// Routes the demo UI calls. Everything else goes to the agents router.
const DEMO_PATHS = new Set([
  "/chat",
  "/pending",
  "/approve",
  "/reject",
  "/rollback",
  "/expire",
  "/executions",
]);

Anything else goes to the agents router. Then the handler, with one route per method:

export default {
  async fetch(request: Request, env: Env) {
    const url = new URL(request.url);

    // Skip creating the agent stub for paths that don't need it.
    if (!DEMO_PATHS.has(url.pathname)) {
      return (
        (await routeAgentRequest(request, env)) ||
        new Response("Not found", { status: 404 })
      );
    }

    try {
      // Every client shares one agent, so everyone sees the same pending list.
      // Fine for a local demo; a real app would key this on a user or session.
      // None of these routes check auth either.
      const stub = await getAgentByName(env.Chat, "demo");

      if (url.pathname === "/chat" && request.method === "POST") {
        const { message } = (await request.json()) as { message: string };
        return new Response(await stub.ask(message), {
          headers: { "content-type": "application/json" },
        });
      }

      if (url.pathname === "/pending") {
        return Response.json(await stub.listPending());
      }

      if (url.pathname === "/approve" && request.method === "POST") {
        const { executionId } = (await request.json()) as {
          executionId: string;
        };
        return Response.json(await stub.approve(executionId));
      }

      if (url.pathname === "/reject" && request.method === "POST") {
        const { executionId, seq } = (await request.json()) as {
          executionId: string;
          seq: number;
        };
        const rejected = await stub.reject(executionId, seq);
        return Response.json({ status: rejected ? "rejected" : "not_pending" });
      }

      if (url.pathname === "/rollback" && request.method === "POST") {
        const { executionId } = (await request.json()) as {
          executionId: string;
        };
        return Response.json(await stub.rollback(executionId));
      }

      if (url.pathname === "/expire" && request.method === "POST") {
        const body = (await request.json().catch(() => ({}))) as {
          maxAgeMs?: number;
        };
        return Response.json(await stub.expirePaused(body.maxAgeMs));
      }

      if (url.pathname === "/executions") {
        const limit = Number(url.searchParams.get("limit")) || undefined;
        return Response.json(await stub.executions(limit));
      }

      return new Response("Not found", { status: 404 });
    } catch (e) {
      // Every route answers with JSON, so the UI can always call res.json().
      // A bad request body is the caller's fault; anything else (MCP server
      // down, runtime error) is reported as unavailable.
      const badBody = e instanceof SyntaxError;
      return Response.json(
        { status: "error", error: String(e) },
        { status: badBody ? 400 : 503 },
      );
    }
  },
} satisfies ExportedHandler<Env>;

We still get the agent named demo, so everyone shares one agent. That’s fine for a demo; a real app would use one agent per user. None of these routes check who you are either, so anyone who can reach the Worker can approve a commit. Keep it on localhost.

Each route reads the request, calls the method and sends back the result. /reject turns false into not_pending. Everything is wrapped in a try/catch, so every route answers in JSON: a bad request body gets a 400, and anything else that goes wrong, like the MCP server going down, gets a 503.

Test it

List the pending actions and copy the executionId:

curl -s http://localhost:5173/pending

Approve it with that ID, and git log in the scratch repo shows a new commit:

curl -s -X POST http://localhost:5173/approve \
  -H "content-type: application/json" \
  -d '{"executionId": "PASTE-ID-HERE"}'

Stage another change in the scratch repo and ask for another commit through /chat. This time reject it, using the executionId and the seq from the pending list:

curl -s -X POST http://localhost:5173/reject \
  -H "content-type: application/json" \
  -d '{"executionId": "PASTE-ID-HERE", "seq": 0}'

Last, /executions shows a record of every run so far:

curl -s http://localhost:5173/executions

Step 6: a Streamlit UI

A small Streamlit app gives us a chat box with Approve and Reject buttons. I won’t go through it line by line: all the Codemode ideas are in the Worker, and this app just calls the routes we wrote. Set it up in its own virtual environment:

python3 -m venv .venv
.venv/bin/pip install -r ui/requirements.txt

ui/requirements.txt:

streamlit>=1.67
requests>=2.34

Two things help when reading it. Streamlit runs the whole script again on every click, so anything we need to keep lives in session_state. And every pending action gets its own Approve and Reject buttons, keyed by the execution ID and the sequence number.

ui/app.py:

import requests
import streamlit as st

# The worker started by `npm run dev`.
BASE = "http://localhost:5173"

st.title("Codemode demo")

# Streamlit reruns this whole script on every interaction, so anything that
# must survive a click lives in session_state.
if "history" not in st.session_state:
    st.session_state.history = []
if "pending" not in st.session_state:
    st.session_state.pending = []

for role, text in st.session_state.history:
    st.chat_message(role).write(text)

if prompt := st.chat_input("Ask something"):
    st.session_state.history.append(("user", prompt))
    st.chat_message("user").write(prompt)

    # Generous timeout: the model can take several steps before it answers.
    r = requests.post(f"{BASE}/chat", json={"message": prompt}, timeout=180)
    data = r.json()

    with st.chat_message("assistant"):
        if r.ok:
            st.write(data["text"])
            with st.expander("What the model did"):
                st.json(data["steps"])
            st.session_state.history.append(("assistant", data["text"]))
            # Add this run's actions to the list; don't replace it, or an
            # earlier action still waiting for approval loses its buttons.
            known = {(p["executionId"], p["seq"]) for p in st.session_state.pending}
            st.session_state.pending += [
                p for p in data["pending"] if (p["executionId"], p["seq"]) not in known
            ]
        else:
            st.write(data["error"])
            st.session_state.history.append(("assistant", data["error"]))


# Removes one execution from the pending list, optionally adding new actions
# (when an approved run pauses again on another gated call).
def drop_execution(execution_id, extra=()):
    st.session_state.pending = [
        p for p in st.session_state.pending if p["executionId"] != execution_id
    ] + list(extra)


# A rerun wipes anything drawn this pass, so park the message in session_state
# and show it after st.rerun().
def flash(kind, message, detail=None):
    st.session_state.flash = (kind, message, detail)


if "flash" in st.session_state:
    kind, message, detail = st.session_state.pop("flash")
    getattr(st, kind)(message)
    if detail is not None:
        with st.expander("Details"):
            st.json(detail)

# One block per paused action, each with its own Approve and Reject buttons.
for action in st.session_state.pending:
    st.warning(f"Waiting for approval: {action['connector']}.{action['method']}")
    st.json(action["args"])
    key = f"{action['executionId']}-{action['seq']}"
    approve_col, reject_col = st.columns(2)

    if approve_col.button("Approve", key=f"approve-{key}"):
        res = requests.post(
            f"{BASE}/approve",
            json={"executionId": action["executionId"]},
            timeout=180,
        )
        result = res.json()
        status = result.get("status")
        if not res.ok or status == "error":
            flash("error", "Approve failed.", result)
        elif status == "paused":
            # The approved call ran, then the code reached another gated call.
            drop_execution(action["executionId"], result.get("pending", []))
            flash("info", "Approved; the run paused on another action.", result)
        else:
            drop_execution(action["executionId"])
            flash("success", "Approved and completed.", result.get("result", result))
            st.session_state.history.append(
                ("assistant", f"Approved {action['connector']}.{action['method']}.")
            )
        # Redraw now so the buttons for this action disappear.
        st.rerun()

    if reject_col.button("Reject", key=f"reject-{key}"):
        res = requests.post(
            f"{BASE}/reject",
            json={"executionId": action["executionId"], "seq": action["seq"]},
            timeout=60,
        )
        result = res.json()
        if res.ok and result.get("status") == "rejected":
            drop_execution(action["executionId"])
            flash("success", "Rejected.")
        else:
            flash(
                "error",
                "Action was no longer pending; it may already have run.",
                result,
            )
        st.rerun()

Session state gets two lists: history holds the chat and pending holds the actions waiting for you. Each rerun draws the old messages again. When you send a prompt, we post it to /chat and wait up to three minutes, because the model can take a while. The answer or the error goes into history. When a new run pauses, we add its actions to the list rather than replace it, so an action that’s still waiting keeps its buttons.

Two helpers: drop_execution takes a run off the pending list, and if an approved run pauses again, it adds the new actions. flash is for messages. Streamlit wipes the screen on every rerun, so we save the message in session state and show it once after the reload.

Approve calls /approve and can end three ways. If it fails, we show the error. If the code hits another call that needs approval, we show the new pending actions. Otherwise it’s done, so we remove the run and say it was approved. Reject sends the execution ID and the sequence number; if the action isn’t pending anymore, we tell you it may have already run. Both buttons end with a rerun, so that action’s buttons go away.

Run it

With the Worker still running from step 4:

.venv/bin/streamlit run ui/app.py

Stage a change in the scratch repo, then ask “show me my staged diff”. The model reads it with git.git_diff(), and the diff shows up in the chat.

Now ask “commit my staged changes with a good message”. The model reads the diff again and writes the message. When its code reaches git.git_commit(), the runtime pauses, and the UI shows the pending action with Approve and Reject buttons. Nothing has been committed yet. Click Approve: the runtime replays the code, and git log shows the new commit with the message the model wrote.

Stage another change, ask for a commit again and click Reject. The repo stays untouched.

Step 7: read the stats

Each request gets its own “What the model did” section in the UI, so open the one for the request you care about. The stats are in the chat response, and the npm run dev terminal prints them for every request.

Your numbers will differ from run to run, especially on openrouter/free, where the model behind the router can change between requests.

Want to compare with classic tool calling? Copy ask, give the model the same two MCP tools as plain AI SDK tools and run the same prompt. With this git server the difference will be small, for the reasons above. To see Codemode pull ahead, connect more MCP servers and give the model a task that needs data from several of them.

To see why the hint is there, delete the “Always return the result” sentence from it and send the same request again. A weak model may give you an empty result; put the sentence back and the answer returns.

Recap

The connector marks one tool, git_commit, as needing approval. The runtime pauses the model’s code at that call, saves everything and replays it when you approve; the UI is a pair of buttons that call /chat, /approve and /reject.

If you want to go further, the Codemode docs cover saved snippets the model can rerun by name, other connector types for OpenAPI specs and your own services, and more on approvals and the runtime.

Type it yourself first, then compare with the finished repo.

The earlier parts of the series: part 1, the MCP server, part 2, the client, and part 3, the agent loop.


Share this post:

Previous Post
MCP Agent in Python: Let a Model Call Your Git Tools