Skip to main content
Glama
README.md
# @orkestrate/codemode

One MCP tool (`execute`) that runs JS/TS glue code next to your downstream MCP
servers — with AST pre-flight validation, safe read-only auto-parallelization,
eager pre-warming, empirical output-schema learning, zero-copy image
passthrough, OAuth 2.1, and crash-checkpoint replay.

## Install

```sh
bun add -g @orkestrate/codemode
# or run without installing globally:
bunx @orkestrate/codemode --help
```

## Architecture

```
agent ──(1 tool: execute)──▶ codemode (upstream MCP, stdio or HTTP)
                                 │ compileScript (acorn + TS fallback)
                                 │ pre-flight → prewarm → Worker pool
                                 ▼
                     psychoscript sandbox (secret-free Bun Worker)
                                 │ mcp.* host namespace (postMessage RPC)
                                 ▼
                     McpPool (host) ──▶ downstream MCP servers (stdio / Streamable HTTP)
```

- `src/config.ts` — layered configs, `{env:VAR}`/`${VAR}` runtime-only
  expansion, 5-harness importers, self-wrap guard.
- `src/cache.ts` — structural output learner (key names + JSON types only).
- `src/artifacts.ts` — host-side zero-copy binary store (`$artifact` handles).
- `src/client.ts` — downstream MCP pool (stdio + Streamable HTTP + SSE).
- `src/catalog.ts` — TS signature rendering, token-budgeted `execute`
  description, fuzzy suggestions.
- `src/compiler.ts` — AST pre-flight + read-only auto-parallelizer.
- `src/worker.ts` / `src/sandbox.ts` — secret-free Worker + pool, timeouts,
  checkpoints, TypeError hints.
- `src/daemon.ts` / `src/mcp.ts` — upstream handler (exactly 1 tool) + shared
  daemon (unix socket + loopback HTTP).
- `src/oauth.ts` — MCP OAuth 2.1 (RFC 9728 PRM, RFC 8414 AS, DCR/PKCE, `0o600` token store).
- `src/cli.ts` — declarative help, strict flag parser, TTY formatting.

## CLI

```
codemode list [server] [--probe] [--json]
codemode add <name> <url> [--header "K: V"] [--local]
codemode add <name> -- <cmd> [args...] [--env K=V] [--local]
codemode rm <name> [--local]
codemode import [--from opencode|claude|codex|antigravity|fx|auto] [--write]
codemode refresh [server]
codemode exec <code | -> [--standalone] [--timeout <ms>] [--checkpoint <id>]
codemode mcp [--standalone] [--http [port]]
codemode serve [--port <n>]
codemode restart
codemode auth login <server> [--scope <scopes>] [--no-open]  (alias: codemode login)
codemode auth logout <server>                                 (alias: codemode logout)
codemode auth status
codemode setup <harness> [--http [url]]
codemode doctor [--tokens]
codemode trust [dir]
codemode untrust [dir]
codemode skill
codemode <cmd> -h | --help
```

`sync` → `refresh`, `print-config` → `setup`, `remove` → `rm` (hidden aliases).

## Sandbox `mcp` API

```js
// typed tool call (auto-unwrapped JSON; binary -> { $artifact } handle)
const issue = await mcp.github.get_issue({ owner: "a", repo: "b", number: 1 });

// dynamic dispatch / raw envelope / discovery
const r = await mcp.call("github", "get_issue", { owner: "a", repo: "b" });
const raw = await mcp.raw("github", "get_issue", { owner: "a", repo: "b" });
const all = await mcp.list();                    // { server: [tools...] }
const schema = await mcp.schema("github", "get_issue");

// attach binary for upstream ImageContent passthrough
const h = await mcp.attach("<base64>", "image/png");
return { img: h };
```

```js
// parallel fan-out over readonly tools (also auto-parallelized by the AST)
const [a, b] = await Promise.all([
  mcp.pg.query({ sql: "select 1" }),
  mcp.pg.query({ sql: "select 2" }),
]);
```

```js
// crash recovery: retry with the checkpoint from the error
// first attempt throws on line 2; retry replays call #1 in 0ms
try {
  await mcp.stripe.charge({ amount: 100 });
  throw new Error("boom");
} catch (e) { throw e; }
// retry: codemode exec --checkpoint <cp-id> '<same code>'
```

## Connect your harness (copy-paste)

OpenCode (`~/.config/opencode/opencode.json` → `mcp`):

```json
{ "mcp": { "codemode": { "type": "local", "command": ["codemode", "mcp"], "enabled": true } } }
```

(Or run `codemode setup opencode` — also supports
`claude`, `codex`, `antigravity`, `fx`. `codemode setup <harness> --http`
emits an HTTP snippet.)

Claude Code (`.mcp.json`):

```json
{ "mcpServers": { "codemode": { "command": "codemode", "args": ["mcp"] } } }
```

Codex (`~/.codex/config.toml`):

```toml
[mcp_servers.codemode]
command = "codemode"
args = ["mcp"]
```

Antigravity / fx (HTTP):

```json
{ "mcpServers": { "codemode": { "serverUrl": "http://127.0.0.1:3779/mcp" } } }
```

```json
{ "mcpServers": { "codemode": { "url": "http://127.0.0.1:3779/mcp" } } }
```

Tip: `codemode import --from auto` scans all five harnesses and prints a
merged config with secret placeholders preserved; add `--write` to save it to
`~/.config/orkestrate/codemode.json`.

## Config precedence

`~/.config/orkestrate/codemode.json` → `.codemode.json` → `--config <path>`
(`ORKESTRATE_CODEMODE_CONFIG` overrides). Placeholders `{env:VAR}` / `${VAR}`
expand only in memory at connect time — never on disk, never in logs.

## Zero-ritual hot-reload (no sync needed)

Edit `~/.config/orkestrate/codemode.json` (or `./.codemode.json`) or run
`codemode add` / `codemode rm` — the daemon hot-reloads automatically on the
next request (fast stat fingerprint, last-known-good kept on mid-edit
malformed JSON). New servers appear immediately as lazy: `execute` calls pass
pre-flight and connect on first use, while unchanged servers stay hot.

```
codemode add gh https://mcp.example.com/mcp --header "Authorization: Bearer {env:TOKEN}"
codemode add local -- bun ./my-server.mjs --env KEY=val
codemode add local -- bun ./my-server.mjs --local
codemode rm gh
codemode refresh [server]
codemode restart
```

OAuth 2.1: `codemode auth login <server> [--scope ...]` (`login` alias), `codemode auth logout <server>`,
`codemode auth status`. Tokens live in `~/.config/orkestrate/codemode-auth.json`
(0o600, `ORKESTRATE_CODEMODE_AUTH` overrides) — never in config, logs, or
Worker memory. Sandbox extras: `mcp.refresh(server?)`, and `mcp.schema(server)`
lazily probes an unprobed server.

## Security

- **Project trust gate:** `./.codemode.json` is skipped unless explicitly approved with `codemode trust` (stored in `~/.config/orkestrate/codemode-trusted.json`, `0o600`).
- **Secret-free sandbox:** Scripts run in `psychoscript` inside an isolated Bun Worker with zero `process.env`, filesystem, or network access; `maxToolCalls` defaults to `50` per execution.
- **HTTP `/mcp` protections:** Loopback `Host` and `Origin` validation plus `0o600` Bearer token auth (`~/.config/orkestrate/codemode-http-token`).
- **Reporting:** See [SECURITY.md](SECURITY.md).