Skip to content
Back to search

codemode

Generate typed, sandboxed Code Mode for AI agents from your .proto files, for Cloudflare Workers and Go.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/the-protobuf-project--codemode/badge.svg)](/listings/the-protobuf-project--codemode)

HTML

<a href="/listings/the-protobuf-project--codemode"><img src="/api/listings/the-protobuf-project--codemode/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 211 lines
  1. <!-- markdownlint-disable MD041 -->
  2. <h1 align="center">Code Mode</h1>
  3. <p align="center">
  4. <strong>Typed, sandboxed Code Mode for AI agents, generated from your <code>.proto</code> files.</strong>
  5. </p>
  6. <p align="center">
  7. <a href="https://github.com/the-protobuf-project/codemode/actions/workflows/ci.yaml"><img src="https://github.com/the-protobuf-project/codemode/actions/workflows/ci.yaml/badge.svg" alt="CI"></a>
  8. <img src="https://img.shields.io/badge/status-work%20in%20progress-orange" alt="Status: work in progress">
  9. <a href="LICENSE"><img src="https://img.shields.io/badge/license-Apache%202.0-blue.svg" alt="License: Apache 2.0"></a>
  10. <img src="https://img.shields.io/badge/runtimes-Node%20%7C%20Bun%20%7C%20Deno%20%7C%20Workers-informational" alt="Runtimes">
  11. </p>
  12. > [!WARNING]
  13. > **Work in progress.** The plugin, runtime and example work end to end and are
  14. > tested on Node, Bun and Deno, but nothing is released yet and the APIs may change.
  15. ## Overview
  16. [Code Mode](https://developers.cloudflare.com/agents/tools/codemode/) gives a
  17. model one tool that runs code instead of one tool per API call. The model writes
  18. a short async function against a typed API; a sandbox runs it. The function can
  19. chain calls, loop, branch and return only what it needs.
  20. `protoc-gen-codemode` builds that API from the protobuf services you already have:
  21. - **Typed messages** as TypeScript interfaces, with protojson and binary codecs
  22. - **Clients** over HTTP transcoding (`google.api.http`) or Connect, JSON or binary
  23. - **Connectors** that expose each service in the sandbox, with approval, replay and rollback
  24. - **A catalog** and `sandbox.d.ts` that tell the model what it can call, including what comes back
  25. Code Mode built from MCP tools types results as `unknown`, because most MCP tools
  26. have no output schema. A proto describes the full response, so the model knows
  27. the result's shape and chains calls correctly.
  28. <p align="center">
  29. <img src="docs/architecture.svg" alt="How Code Mode works: protos generate typed TypeScript; at run time the model writes one function that a sandbox runs against your services" width="100%">
  30. </p>
  31. ## Try it with Claude
  32. The library example runs as an MCP server on stdio, with one `code` tool. You
  33. need [Bun](https://bun.sh) and a GitHub token that can read packages, because
  34. the runtime comes from GitHub Packages:
  35. ```sh
  36. gh auth refresh -s read:packages && export GITHUB_TOKEN=$(gh auth token)
  37. git clone https://github.com/the-protobuf-project/codemode.git
  38. cd codemode && bun install
  39. ```
  40. **Claude Code**
  41. ```sh
  42. claude mcp add library -- bun "$PWD/examples/library/src/mcp.ts"
  43. ```
  44. **Claude Desktop**: add this to `claude_desktop_config.json` (Settings → Developer →
  45. Edit Config), using absolute paths. Desktop apps do not see your shell's `PATH`,
  46. so give the full path of `bun` (`which bun`):
  47. ```json
  48. {
  49. "mcpServers": {
  50. "library": {
  51. "command": "/absolute/path/to/bun",
  52. "args": ["/absolute/path/to/codemode/examples/library/src/mcp.ts"],
  53. "env": { "CODEMODE_DB": "/absolute/path/to/library.db" }
  54. }
  55. }
  56. }
  57. ```
  58. **Other MCP clients** (Cursor, VS Code, Zed, the MCP Inspector) take the same
  59. command. To look at the tools first:
  60. ```sh
  61. bunx @modelcontextprotocol/inspector bun examples/library/src/mcp.ts
  62. ```
  63. Then ask something that needs several calls, for example *"Which shelves have
  64. books, and lend the shortest poetry book to Ada for a week"*, or *"Archive the
  65. fiction shelf"* to see an approval pause. `CODEMODE_DB` is optional: set it to
  66. keep executions in SQLite across restarts. The library itself is in memory and
  67. resets when the server starts.
  68. > [!NOTE]
  69. > When the client supports MCP elicitation, approvals are asked there. Otherwise
  70. > the server returns `paused` and the model resumes with `codemode_approve`, so
  71. > leave that tool on "ask before running" in your client: its permission prompt
  72. > is the human approval.
  73. ## How it works
  74. **1. Annotate.** Annotations from [`protoc-gen-mcp`](https://github.com/the-protobuf-project/mcp)
  75. work as they are. `codemode.v1` adds rollback, replay, snippets and the sandbox namespace.
  76. ```proto
  77. service LibraryService {
  78. option (codemode.v1.service) = { namespace: "library" };
  79. rpc CreateBook(CreateBookRequest) returns (Book) {
  80. option (google.api.http) = { post: "/v1/{parent=shelves/*}/books" body: "book" };
  81. option (codemode.v1.method) = {
  82. revert: { method: "DeleteBook" fields: { key: "name" value: "result.name" } }
  83. };
  84. }
  85. rpc ArchiveShelf(ArchiveShelfRequest) returns (ArchiveShelfResponse) {
  86. option (mcp.v1.tool) = { destructive: true }; // pauses for approval
  87. }
  88. }
  89. ```
  90. **2. Generate** with `buf generate`. Every message gets an interface and a codec:
  91. ```ts
  92. export interface Book {
  93. name?: BookName; // `shelves/${string}/books/${string}`
  94. title: string;
  95. state?: BookState; // "BOOK_STATE_AVAILABLE" | "BOOK_STATE_LENT" | ...
  96. pageCount?: string; // 64-bit integers stay exact
  97. createTime?: string; // RFC 3339
  98. }
  99. export const BookCodec: MessageCodec<Book>; // fromJson, toJson, encode, decode
  100. ```
  101. **3. Run.** Generated code builds on [runtime-ts](https://github.com/the-protobuf-project/runtime-ts)
  102. (the `@the-protobuf-project/*` runtime-ts packages on GitHub Packages), the TypeScript runtime
  103. shared by every plugin. Wire the
  104. generated connectors into its Code Mode runtime and hand the model one tool:
  105. ```ts
  106. import { createCodemode } from "@the-protobuf-project/codemode";
  107. import { QuickJSExecutor } from "@the-protobuf-project/codemode/quickjs";
  108. import { httpTransport } from "@the-protobuf-project/network";
  109. import { catalog, config, connectors, libraryV1 } from "./gen/index.ts";
  110. const client = new libraryV1.LibraryServiceClient(httpTransport({ baseUrl: "https://library.example.com" }));
  111. const runtime = createCodemode({ catalog, config, connectors: connectors({ library: client }), executor: new QuickJSExecutor() });
  112. await runtime.execute({ code: `async () => {
  113. const page = await library.listBooks({ parent: "shelves/poetry" });
  114. return page.books.map((b) => b.title);
  115. }` });
  116. // { status: "completed", result: ["Leaves of Grass", "Odes", "Ariel"] }
  117. ```
  118. A call that needs approval returns `{ status: "paused", pending: [...] }`;
  119. `runtime.approve()` resumes it, replaying earlier calls from the log instead of
  120. running them again. `runtime.rollback()` undoes applied calls through their
  121. generated reverts.
  122. ## Features
  123. | Feature | Where it comes from |
  124. | --- | --- |
  125. | Typed inputs **and outputs** | Proto messages, enums, `google.api.resource` names |
  126. | `search` and `describe` | Generated catalog; progressive or inline discovery |
  127. | Approval pauses with durable resume | `mcp.v1.tool.destructive`, `mcp.v1.elicitation`, `codemode.v1.method.approval` |
  128. | Replay and `codemode.step()` | Recorded call log; `codemode.v1.method.replay` |
  129. | Rollback | `codemode.v1.method.revert` generates the compensating call |
  130. | Snippets | `codemode.v1.service.snippets`, plus `saveSnippet()` at run time |
  131. | History, limits, hooks, truncation | Runtime, configured by `codemode.yaml` |
  132. | Sandboxes | QuickJS (Node, Bun, Deno, browser), Deno subprocess, Cloudflare Worker Loader, iframe |
  133. | Stores | Memory, SQLite (`bun:sqlite`, `node:sqlite`), Durable Object SQL |
  134. | Surfaces | Framework-neutral tool, MCP server (`code` or `search` + `execute`), Vercel AI SDK |
  135. | Allowlisted `fetch` | `executor.outbound: allowlist`; responses replayed with the log |
  136. ## Layout
  137. ```
  138. protobuf/codemode/v1/ codemode.v1 annotations (protobuf/codemodepb: Go types)
  139. plugin/ protoc-gen-codemode, on protokit
  140. examples/library/ annotated protos, generated code, an in-memory service, tests
  141. schema/ JSON Schema for codemode.yaml
  142. docs/ annotations, configuration, generated code, runtime, security
  143. ```
  144. The runtime the generated code imports lives in its own repository,
  145. [runtime-ts](https://github.com/the-protobuf-project/runtime-ts), next to
  146. [runtime-go](https://github.com/the-protobuf-project/runtime-go).
  147. ## Documentation
  148. - [Annotations](docs/annotations.md): what `codemode.v1` adds and how `mcp.v1` is read
  149. - [Configuration](docs/configuration.md): `codemode.yaml` and plugin parameters
  150. - [Generated code](docs/generated-code.md): the folder structure and the TypeScript it contains
  151. - [Runtime](docs/runtime.md): executions, approvals, replay, rollback, executors, stores, MCP
  152. - [Security](docs/security.md): what the sandbox can and cannot reach
  153. ## Development
  154. Requires Go 1.26+, [buf](https://buf.build), [Bun](https://bun.sh) and
  155. [just](https://just.systems); Node 22.18+ and Deno to run those suites. Set
  156. `GITHUB_TOKEN` as in [Try it with Claude](#try-it-with-claude) before `bun install`.
  157. ```sh
  158. bun install
  159. just generate # build the plugin and regenerate examples/library/gen
  160. just test # Go tests (including a golden test of the example), type-check, Bun tests
  161. just test-runtimes # the example's tests on Node and Deno too
  162. just lint # buf lint, go vet, and the 200-line limit on hand-written files
  163. ```
  164. ## License
  165. Licensed under the [Apache License, Version 2.0](LICENSE).
  166. Copyright 2026 The Protobuf Project authors.

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.