@sontoriyama/mcp-code-mode 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,148 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project
6
+ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [0.4.0] - 2026-12-06
9
+
10
+ ### Added
11
+
12
+ - **`--serve-mcp`: dual-era MCP stdio server.** Exposes `run_code` and `read_spill` (plus `list_tools` when the
13
+ embedded catalog exceeds the ~6 KB budget) so a host can batch any number of upstream calls in one turn.
14
+ Serves modern `2026-07-28` requests carrying per-request `_meta` (`io.modelcontextprotocol/protocolVersion`,
15
+ `clientCapabilities`, `clientInfo`) statelessly, and answers the legacy `initialize` handshake (echoing the
16
+ requested version, else `2025-11-25`) for dual-era clients. `server/discover` advertises supported versions,
17
+ capabilities, server info and short instructions; unsupported versions return `-32022` with
18
+ `{ requested, supported }`; unknown tools/methods return `-32602`/`-32601` without crashing.
19
+ - **`listTools(filter)` and `callTool(name, args, opts)` inside `run_code`**: discovery and execution in the
20
+ same call, so the embedded catalog is a hint instead of a hard limit.
21
+ - **`read_spill`** with `offset`/`maxChars` returning `{ text, totalChars, offset, truncated, nextOffset }`,
22
+ path-contained to `CODEMODE_OUT_DIR`.
23
+ - **`--allow-tools <csv>`** (exact names or `prefix*`): filters `tools/list`, `listTools()` and the embedded
24
+ catalog, and rejects denied calls through `tools.*`, `callTool()` and `tools.call()`.
25
+ - **`--timeout-ms`** hard timeout per `run_code` (default `120000`).
26
+ - Shared `src/executor.mjs` used by both front-ends: `executeProgram()` owns console/stdout/exit capture, the
27
+ spill envelope and an optional `AbortSignal`/timeout.
28
+ - CI `pack-smoke` now drives `--serve-mcp` over the installed tarball (`server/discover` + `tools/list`), which
29
+ catches files missing from the package.
30
+
31
+ ### Changed
32
+
33
+ - **MCP client negotiation is now dual-era and spec-verified.** It probes `server/discover` first on stdio,
34
+ caches the era per server process, accepts the version the server announces, and falls back to `initialize`
35
+ on any non-modern error. `clientInfo.version` comes from `package.json` instead of a hardcoded string.
36
+ - `run_code` calls are serialized in a FIFO queue: one global stdout/console/exit patch per execution, no races
37
+ across concurrent MCP calls, while `mapBounded` keeps parallelism inside a program. Queued calls can be
38
+ cancelled before they start.
39
+ - Cancellation aborts only the affected `run_code` (per-request `AbortController`); shared upstream clients are
40
+ never killed for a cancellation. A client that ignores cancellation and accumulates timeouts is recycled and
41
+ its in-flight requests fail with an explicit error.
42
+ - `process.stdout.write` and `process.exit` are captured while a program runs, so a program cannot corrupt
43
+ the JSON envelope or the MCP transport. In `--serve-mcp` the stdout writer is additionally diverted to
44
+ stderr for the whole server lifetime, so late writes from timers or floating promises after a run cannot
45
+ corrupt the JSON-RPC stream.
46
+ - **Renamed the package to `mcp-code-mode`** (was `agent-maxicodemode`) ahead of the first npm publish. The CLI
47
+ binary, `bin` entry and MCP `serverInfo`/`clientInfo` names follow the package name; GitHub repository URLs
48
+ are unchanged.
49
+
50
+ ### Fixed
51
+
52
+ - `run_code` output in `--serve-mcp` is now bounded to `CODEMODE_MAX_OUTPUT_CHARS`: when the envelope spills,
53
+ the host receives a compact, valid-JSON envelope with `truncated`, `totalChars` and `spill.path` instead of
54
+ the full payload. `read_spill` still pages the complete envelope.
55
+ - A `run_code` timeout now aborts in-flight upstream calls: the timeout fires the same `AbortController` the
56
+ scoped tools receive, and per-call signals (e.g. `mapBounded`) are composed instead of shadowing it, so
57
+ upstreams get `notifications/cancelled` instead of being left running.
58
+ - Removed an unused helper from `src/run.mjs`.
59
+ - In `--serve-mcp`, writes that outlive a `run_code` (fired timers, floating promises, an aborted program)
60
+ are diverted to stderr instead of the JSON-RPC stdout, so a stray `console.log`/`process.stdout.write` can
61
+ no longer corrupt the transport.
62
+ - `read_spill` resolves symlinks with `realpath`, rejects non-regular files (FIFO/device/directory) via
63
+ `lstat`, and reads the file in bounded chunks instead of loading it whole, so a large spill cannot OOM the
64
+ server; paging also no longer splits surrogate pairs at page boundaries.
65
+ - `--allow-tools ""` (or any explicit empty list) now denies every tool instead of silently allowing all;
66
+ only an absent flag disables the filter.
67
+
68
+ ### Security
69
+
70
+ - `--serve-mcp` is the only opt-in. No consent theatre flag is added; `--allow-tools` is documented as the only
71
+ enforceable control.
72
+ - `gh`/`engram` plugins stay disabled by default in server mode.
73
+ - README documents the prompt-injection threat model and warns against declaring the same upstreams twice
74
+ (host + wrapper).
75
+
76
+ ## [0.3.3] - 2026-12-06
77
+
78
+ ### Added
79
+
80
+ - `--version` / `-v` and `--help` / `-h`: both print to stdout and exit `0`.
81
+ - Every envelope now carries `version`. When stdout had to be truncated it also carries
82
+ `spill.path`, so an agent can filter the full file on the next turn without parsing stderr.
83
+ Keeping the path out of non-truncated envelopes avoids paying ~30 tokens per call for a path the
84
+ caller does not need (visible in `bench/benchmark.mjs`).
85
+ - Tests for the CLI meta flags, usage errors, envelope fields, and module-syntax detection.
86
+ - Benchmark scenario with synthetic ~4 KB payloads (10.3k payload tokens across 10 direct calls
87
+ vs ~102 in one turn) and a reproducible Node/platform/date header. The tiny-payload scenario now
88
+ states that it saves turns, not tokens.
89
+ - `CHANGELOG.md`, a `prepublishOnly` test gate, and a publish workflow that uses npm provenance.
90
+ - CI installs the packed tarball into a clean prefix and runs the installed binary.
91
+
92
+ ### Changed
93
+
94
+ - Unknown `--flags` are usage errors with exit `2`. They are no longer imported as program paths,
95
+ which used to fail with exit `1` and leave a `--version-*.json` spill behind.
96
+ - Snippet vs. module detection now comes from the parser: `new AsyncFunction` is tried first and
97
+ the `data:` module path is used only for real module syntax. Export-like text inside strings no
98
+ longer misroutes a snippet.
99
+ - CI matrix adds Node 24 on Linux, macOS and Windows.
100
+ - README: reframed around who the tool is for (shell-only harnesses without native Code Mode),
101
+ added explicit limitations and security model, a harness-fit table, an FAQ ("why not `node -e`?"),
102
+ the real Install section, and refreshed flags/exit-code docs.
103
+
104
+ ## [0.3.2] - 2026-12-06
105
+
106
+ ### Added
107
+
108
+ - Contributor `AGENTS.md` with the repository's architectural invariants.
109
+ - PiG variant of the skill (`skills/pig/SKILL.md`) and `docs/pig.md` mapping PiG's native
110
+ `codemode` tool against this runner.
111
+
112
+ ### Changed
113
+
114
+ - README: package size wording and release metadata.
115
+
116
+ ## [0.3.1] - 2026-12-06
117
+
118
+ ### Added
119
+
120
+ - Credits for the Code Mode lineage, Engram and gentle-ai.
121
+
122
+ ### Fixed
123
+
124
+ - CI: list test files explicitly so Windows + Node 20 pass.
125
+
126
+ ## [0.3.0] - 2026-12-06
127
+
128
+ ### Added
129
+
130
+ - `spill.read()` for follow-up filtering without re-running tools.
131
+ - Reproducible benchmark and a Linux/macOS/Windows CI matrix.
132
+ - Zero-dependency stdio MCP client (`--mcp` / `--mcp-config`) with `.cmd`/`.bat` support,
133
+ bidirectional ping, buffer caps and process-tree teardown on Windows.
134
+ - Package metadata and hardened `mapBounded` concurrency/abort handling.
135
+
136
+ ## [0.2.0] - 2026-12-06
137
+
138
+ ### Added
139
+
140
+ - Inline (`-e` / `--code`) and stdin (`-` / `--stdin`) execution.
141
+ - Declarative CLI manifests (`--manifest`) and progressive tool discovery (`--list-tools`).
142
+
143
+ ## [0.1.0] - 2026-12-06
144
+
145
+ ### Added
146
+
147
+ - Initial release: zero-dependency local Code Mode runner with bounded stdout, lossless disk spill
148
+ and an honest non-sandbox security model.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 sontoriyama
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,207 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # mcp-code-mode
2
+
3
+ [![CI](https://github.com/sontoriyama/agent-maxicodemode/actions/workflows/ci.yml/badge.svg)](https://github.com/sontoriyama/agent-maxicodemode/actions)
4
+ ![Node.js >= 20](https://img.shields.io/badge/node-%3E%3D20-339933)
5
+ ![Dependencies: 0](https://img.shields.io/badge/dependencies-0-blue)
6
+ ![Size: ~28 kB packed](https://img.shields.io/badge/packed-~28_kB-informational)
7
+ ![License: MIT](https://img.shields.io/badge/license-MIT-lightgrey)
8
+
9
+ **Batch N stdio MCP or CLI tool calls into 1 shell turn, with bounded stdout and lossless disk spill.**
10
+ Pure Node.js (`>= 20`) ESM, `~42 kB` packed (`~139 kB` unpacked), zero dependencies, no daemon, no cloud sandbox.
11
+
12
+ > **Who this is for:** coding harnesses that have a shell tool but **no native Code Mode** (plus CI/cron scripts that need a zero-dep stdio MCP batch client). If your harness already ships native Code Mode, use its built-in tool instead.
13
+
14
+ ### Before vs. After (fetch 10 GitHub issues, return only open ones)
15
+
16
+ | | Direct MCP tool calls | `mcp-code-mode` |
17
+ | :--- | :--- | :--- |
18
+ | **LLM turns** | 10 sequential turns + approval prompts | **1 turn** |
19
+ | **Context window** | 10 raw JSON payloads dumped into context | **Filtered JSON only** (full payload spilled to `.agent/out/`, `0600`) |
20
+ | **Execution** | Serial round-trips | **Bounded concurrency** (`mapBounded`) |
21
+
22
+ ```bash
23
+ # 1 turn, zero temp files for the program — lazy-spawns only the touched MCP server from .mcp.json
24
+ # (from a clone; once 0.4.0 is on npm, replace this with: mcp-code-mode --no-default-plugins ...)
25
+ node src/run.mjs --no-default-plugins --mcp-config .mcp.json -e '
26
+ const issues = await mapBounded(args.ids, 4, (id, _i, signal) =>
27
+ tools.mcp.github.get_issue({ id }, { signal })
28
+ );
29
+ return issues.filter((x) => x.state === "open").map(({ id, title }) => ({ id, title }));
30
+ ' '{"ids":[1,2,3,4,5,6,7,8,9,10]}'
31
+ ```
32
+
33
+ ### Explicit Limitations & Security Model
34
+
35
+ - **Not a sandbox:** Scripts execute with normal host Node.js privileges (`execTool` and `execJson` are in scope). Argument/manifest validation prevents accidental flag injection and context blowups, not hostile code. Designed for read/filter/batch orchestration; keep writes and external side effects in explicit, visible tool calls.
36
+ - **stdio MCP only:** Supports local stdio JSON-RPC 2.0 MCP servers (`tools/list`, `tools/call`, `ping`, `notifications/cancelled`). No HTTP/SSE transport, no MCP `resources`/`prompts`, and no built-in OAuth/auth layer.
37
+ - **Requires agent instructions:** An agent will not invoke this CLI automatically unless you drop [`SKILL.md`](./SKILL.md) into its skills folder or add a short rule to `AGENTS.md` (e.g., use for `>= 4` homogeneous read queries).
38
+ ---
39
+
40
+ ## Harness Fit
41
+
42
+ | Environment | Recommended? | Why |
43
+ | :--- | :---: | :--- |
44
+ | **Shell-only coding harnesses** (e.g. Command Code, or any agent with shell access and no native Code Mode) | **Yes** | Collapses multi-step MCP/CLI fan-outs into 1 shell turn with bounded stdout. |
45
+ | **PiG (`pig`)** | **No (use native)** | PiG ships an in-process QuickJS `codemode` tool. See [`docs/pig.md`](./docs/pig.md) for the 5 fallback cases where this runner still helps. |
46
+ | **Harnesses with parallel native file tools** (e.g. Antigravity) | **Partial** | Keep file reads/edits on native tools; use this runner only for batched stdio MCP or external CLI (`gh`, `engram`) queries. |
47
+ | **Non-agentic automation** (CI, cron, local scripts) | **Yes** | Deterministic, zero-dep CLI to query stdio MCP servers and emit compact JSON with spill. |
48
+
49
+ ---
50
+
51
+ ## Why this exists
52
+
53
+ Direct tool-by-tool calling breaks down on multi-step read workflows in two ways:
54
+
55
+ 1. **The N+1 round-trip tax:** Chaining 6–20 MCP or CLI calls burns turns, latency, and repeated approval prompts.
56
+ 2. **Context rot from large intermediate payloads:** Dumping 10 raw 2–10 KB JSON objects into the context window inflates token costs and degrades reasoning. (On tiny payloads, batching saves turns and approvals rather than tokens—see the benchmark below.)
57
+
58
+ **What the runner provides:**
59
+
60
+ - **Zero-dep stdio MCP bridge (`--mcp-config` / `--mcp`):** Reads standard `mcpServers` configs (`claude_desktop_config.json`, `.mcp.json`), lazy-spawns servers only when touched via `Proxy`, compacts JSON Schemas in `--list-tools`, handles bidirectional JSON-RPC 2.0 (`ping`), tolerates dirty stdout, wires `notifications/cancelled` to `AbortSignal`, and cleans up process trees on exit (POSIX process groups + Windows `taskkill /T /F` + `.cmd`/`.bat` shim support).
61
+ - **No temp files for the program:** Run one-shot scripts inline (`-e` / `--code`) or via `stdin` (`-`, capped by `CODEMODE_MAX_STDIN_BYTES`, default `1 MiB`). `mapBounded(items, concurrency, fn)` is injected automatically (`1..16` concurrency clamp + shared `AbortSignal`).
62
+ - **Bounded stdout + lossless spill + `spill.read()`:** Full valid JSON is always written to `.agent/out/` (`0o600`, `wx`). Oversized stdout is truncated head+tail so one huge payload never blows up a session, and follow-up turns can filter the spilled file in JS via `spill.read()` without re-running tools.
63
+ - **Declarative CLI manifests & optional plugins:** Plug in internal CLIs with `--manifest <file>` (typed validation + anti-flag-injection via `execFile` without shell) or use the optional `gh` / `engram` plugins (`--plugins` / `--no-default-plugins`).
64
+
65
+ > **Important:** Keep `.agent/out/` in your project's `.gitignore` so spilled payloads are never committed accidentally.
66
+
67
+ ## Honest Benchmark (`node bench/benchmark.mjs`)
68
+
69
+ Reproducible local benchmark against the pure-Node mock MCP server (`Node v24.22.1`, `win32/x64`, `2026-12-06`). It includes a tiny-payload case (token parity), a synthetic ~4 KB payload case (where the context win actually comes from), and a 1-step case where direct calling wins. Timings vary ±10–20% per run; run it yourself:
70
+
71
+ | Scenario | Direct tool calls | `mcp-code-mode` | Winner |
72
+ | :--- | :---: | :---: | :--- |
73
+ | 1. 10x small MCP fetch + aggregate | 10 turns \| ~55 ms \| ~56 stdout tok | **1 turn** \| ~117 ms \| ~54 stdout tok | **`mcp-code-mode`** (10x fewer turns; tiny payloads) |
74
+ | 2. 10x ~4 KB synthetic MCP payloads + filter | 10 turns \| ~48 ms \| ~10,321 stdout tok | **1 turn** \| ~113 ms \| **~102 stdout tok** | **`mcp-code-mode`** (~101x fewer payload tok; scenario-specific) |
75
+ | 3. 6x concurrent slow MCP ops (40 ms) | 6 turns \| ~325 ms \| ~20 stdout tok | **1 turn** \| **~177 ms** \| ~49 stdout tok | **`mcp-code-mode`** (parallel + 6x fewer turns) |
76
+ | 4. Single 1-step MCP call | **1 turn \| ~50 ms \| ~6 stdout tok** | 1 turn \| ~109 ms \| ~54 stdout tok | **Direct call** (lower overhead) |
77
+
78
+ *Note: wall-clock times measure local Node process + IPC only, and `stdout tok` measures returned payload bytes (`chars / 4`, including the runner's ~50-token JSON envelope). In real agent sessions, each extra LLM turn also adds 2–10 s and prompt/history overhead.*
79
+
80
+ ## Install
81
+
82
+ Requires Node.js >= 20. Zero npm dependencies.
83
+
84
+ ```bash
85
+ # Run on demand (once published to npm)
86
+ npx mcp-code-mode --version
87
+
88
+ # Or install globally
89
+ npm install -g mcp-code-mode
90
+
91
+ # Or clone and run directly from source
92
+ git clone https://github.com/sontoriyama/agent-maxicodemode.git
93
+ cd agent-maxicodemode
94
+ npm test
95
+ ```
96
+
97
+ If `npx` returns a 404, that version is not on the registry yet; use the source route.
98
+
99
+ ## Quick Start (from source)
100
+
101
+ *Shell note: examples below use POSIX / PowerShell single quotes; on Windows `cmd.exe`, use double quotes or `--stdin`.*
102
+ *(The mock MCP fixture ships only in the repo, not in the npm tarball.)*
103
+
104
+ ```bash
105
+ # 1. Discover tools from the bundled mock MCP server (or pass --mcp-config .mcp.json)
106
+ node src/run.mjs --no-default-plugins --mcp 'mock=node test/fixtures/mock-mcp-server.mjs' --list-tools
107
+
108
+ # 2. Batch 4 MCP calls in 1 turn (writes full JSON spill to .agent/out/)
109
+ node src/run.mjs --no-default-plugins --mcp 'mock=node test/fixtures/mock-mcp-server.mjs' -e '
110
+ return await mapBounded([1, 2, 3, 4], 4, (id, _i, signal) =>
111
+ tools.mcp.mock.echo_item({ id, tag: id % 2 === 0 ? "b" : "a" }, { signal })
112
+ );
113
+ '
114
+
115
+ # 3. Filter the spilled JSON from step 2 without re-running tools
116
+ node src/run.mjs -e 'return spill.read().result.filter((x) => x.tag === "b");'
117
+
118
+ # 4. Declarative CLI manifest discovery
119
+ node src/run.mjs --no-default-plugins --manifest examples/codemode.tools.json --list-tools
120
+ ```
121
+
122
+ ## MCP Server Mode (`--serve-mcp`)
123
+
124
+ `--serve-mcp` turns the runner into a local stdio MCP server that exposes **two or three** tools instead of one per upstream:
125
+
126
+ - **`run_code`** — runs a JS program with `tools.<ns>.<tool>()`, `args`, `mapBounded`, `execTool`, `execJson` and `spill.read()`, plus `listTools()` and `callTool()` injected into the program scope. Discovery and execution happen in the same turn, so the embedded catalog is a hint, not a hard limit. Output is bounded; oversized envelopes carry `spill.path`.
127
+ - **`read_spill`** — paginated read of a spilled envelope (`offset`, `maxChars`) returning `{ text, totalChars, offset, truncated, nextOffset }`. Last resort: prefer returning summaries from `run_code`.
128
+ - **`list_tools`** — only exposed when the upstream catalog does not fit in the ~6 KB embedded budget.
129
+
130
+ Wire format: JSON-RPC 2.0 over NDJSON. The server is **dual-era**: modern `2026-07-28` requests carry `_meta` (`io.modelcontextprotocol/protocolVersion`, `.../clientCapabilities`, optional `.../clientInfo`) and are served statelessly; legacy clients use `initialize`, and the handshake echoes the requested version (or `2025-11-25`). `server/discover` returns supported versions, capabilities, server info and short instructions. Unsupported versions fail with `-32022` plus `{ requested, supported }`; unknown tools and methods return `-32602`/`-32601`, never a crash. `run_code` calls are serialized in a FIFO queue — the parallelism you want is `mapBounded` *inside* the program — so the one console/stdout/exit patch per execution never races.
131
+
132
+ ```json
133
+ {
134
+ "mcpServers": {
135
+ "codemode": {
136
+ "command": "npx",
137
+ "args": ["-y", "mcp-code-mode", "--serve-mcp"]
138
+ }
139
+ }
140
+ }
141
+ ```
142
+
143
+ To batch upstream MCP servers, declare them **inside** the wrapper (inline `--mcp` or a config file):
144
+
145
+ ```json
146
+ {
147
+ "mcpServers": {
148
+ "codemode": {
149
+ "command": "npx",
150
+ "args": [
151
+ "-y", "mcp-code-mode", "--serve-mcp",
152
+ "--mcp-config", "C:\\Users\\you\\.codemode\\upstreams.json"
153
+ ]
154
+ }
155
+ }
156
+ }
157
+ ```
158
+
159
+ **Do not declare the same upstream twice** (once at the host level and once inside the wrapper): you duplicate the tools, the context cost and the spawned processes. In server mode the `gh`/`engram` plugins are disabled by default; enable them explicitly with `--plugins`.
160
+
161
+ **`--allow-tools` is the only enforceable control:** a CSV of exact names or `prefix*` patterns (e.g. `mcp.gh.*`). It filters `tools/list`, `listTools()` and the embedded catalog **and** rejects denied calls made through `tools.*`, `callTool()` or `tools.call()` — filtering alone would be cosmetic. Cancellation is per `run_code` (`notifications/cancelled` aborts only that call); shared upstream clients are never killed for cancelling one execution, and a client that keeps ignoring cancellation and timing out is recycled with an explicit error so no zombies remain. Hard timeout defaults to `120 s` (`--timeout-ms`, or per-call `timeoutMs`).
162
+
163
+ > **Threat model:** this is not a sandbox. `--serve-mcp` *is* the opt-in. Anything the host can invoke runs with your user privileges, and untrusted content read by a program (a file, an issue body, a web page) is a prompt-injection path into `run_code`. Stdout/console/`process.exit` interception covers JavaScript writes only — not `fs.writeSync(1)` nor child processes with inherited stdio.
164
+
165
+ ### CLI Modes, Flags & Environment Variables
166
+
167
+ - `<program.mjs> [jsonArgs]`: execute a local ESM module exporting `run({ tools, args, mapBounded, spill })` or a default function (supports relative `./` imports).
168
+ - `--code <js>` / `-e <js>`: execute inline async JS body (`tools`, `args`, `mapBounded`, `execTool`, `execJson`, `spill` in scope).
169
+ - `-` / `--stdin`: read inline JS body or ESM `export async function run` module from `stdin` (ESM snippets via `data:` URL do not support relative `./` imports; use `<program.mjs>` for local imports).
170
+ - `--mcp-config <file>` / `CODEMODE_MCP_CONFIG`: load standard `{ "mcpServers": { ... } }` JSON config.
171
+ - `--mcp "alias=cmd arg1 arg2"`: attach an inline stdio MCP server (repeatable).
172
+ - `--manifest <file>` / `CODEMODE_MANIFEST`: load declarative CLI tools from JSON.
173
+ - `--plugins <csv>` / `CODEMODE_PLUGINS` / `--no-default-plugins`: select or disable built-in plugins (`gh,engram`).
174
+ - `--list-tools [filter]`: print compact JSON catalog (including compacted MCP schemas) and exit.
175
+ - `--serve-mcp`: run as a dual-era stdio MCP server (see [MCP Server Mode](#mcp-server-mode---serve-mcp)). Implies `--no-default-plugins` unless `--plugins` is passed explicitly; never reads a program from stdin.
176
+ - `--allow-tools <csv>`: enforce a tool allowlist (exact names or `prefix*`) in `tools/list`, `listTools()` and execution.
177
+ - `--timeout-ms <n>`: hard timeout per `run_code` in server mode (default `120000`).
178
+ - `--version` / `-v`, `--help` / `-h`: print the version or the usage text to stdout and exit `0`.
179
+ - `CODEMODE_MAX_OUTPUT_CHARS` (`32000`), `CODEMODE_MAX_STDIN_BYTES` (`1048576`), `CODEMODE_OUT_DIR` (`.agent/out`), `CODEMODE_MCP_VERBOSE` (`1`).
180
+
181
+ Unknown `--flags` are usage errors (`exit 2`), never treated as program paths. Every run prints a JSON envelope with a `version` field; when stdout had to be truncated the envelope also carries `spill.path`, so the next turn can filter the full file without parsing stderr. The spill file always holds the unbounded envelope, and stderr names it on every run. Exit codes: `0` program ran (`ok: true`), `1` program threw (`ok: false` plus `error`), `2` invalid usage or `jsonArgs` (nothing runs, no spill).
182
+
183
+ ## FAQ
184
+
185
+ **Why not just run `node -e`?**
186
+ For plain CLI commands, `node -e` is fine. What `node -e` cannot do out of the box is talk JSON-RPC 2.0 to stdio MCP servers configured in `.mcp.json`, lazy-spawn and tear down process trees cleanly (including Windows `.cmd` shims), wire `AbortSignal` to `notifications/cancelled`, or cap stdout while spilling the full JSON for a follow-up `spill.read()` pass.
187
+
188
+ **Why not write a normal checked-in script?**
189
+ If you run the same workflow every week, a checked-in script is better. `mcp-code-mode` is for ad-hoc, one-shot batching during an agent session where you do not want to create throwaway `.mjs` files or re-implement MCP client boilerplate on every task.
190
+
191
+ ## Agent Integration
192
+
193
+ Drop [`SKILL.md`](./SKILL.md) into your agent's skills directory or copy its rules into your `AGENTS.md`.
194
+
195
+ ### PiG (`pig`)
196
+
197
+ PiG ships code mode natively (`codemode`: JavaScript in QuickJS/WASM, in-process, no Node), so this runner is **not** the right tool there. [`docs/pig.md`](./docs/pig.md) has the API mapping, the one settings line that enables the native tool, a one-turn verification recipe, and the five cases where the runner still wins. A ready-to-install PiG skill lives in [`skills/pig`](./skills/pig/SKILL.md).
198
+
199
+ ## Credits
200
+
201
+ - **Engram** — persistent memory system for AI coding agents ([Gentleman-Programming/engram](https://github.com/Gentleman-Programming/engram)). It is also a reference integration for this tool: many homogeneous read-only CLI queries collapse into one turn. The optional `engram` plugin wraps its read-only CLI; this credit is a thank-you to the Gentleman Programming ecosystem, not a dependency or an official endorsement.
202
+ - **gentle-ai** — agent configuration harness and ODD workflow ([Gentleman-Programming/gentle-ai](https://github.com/Gentleman-Programming/gentle-ai)), which shaped the local agent workflow this tool was extracted from. Thanks to Alan Buscaglia and the Gentleman Programming community.
203
+ - **Code Mode lineage** — inspired by Cloudflare's Code Mode, Anthropic's Code Execution with MCP, the `run_code` design in dsh (deepseek-harness), and qwen-code's `exec`/CodeModeOnly. This is an independent implementation: it reuses their ideas, not their code.
204
+
205
+ ## License
206
+
207
+ MIT © 2026 [sontoriyama](https://github.com/sontoriyama) — also building [Vozflow](https://vozflow.dev), fast voice dictation.
package/SKILL.md ADDED
@@ -0,0 +1,42 @@
1
+ ---
2
+ name: mcp-code-mode
3
+ description: Batch 4+ homogeneous read-only MCP or CLI queries into one tool call via inline/stdin/file JS execution with lazy stdio MCP bridge, progressive tool discovery, bounded output, and disk spill.
4
+ ---
5
+
6
+ # Agent MaxiCodeMode
7
+
8
+ Use local Code Mode when a task needs **>= 4 read-only MCP or CLI calls** (or multi-step chaining/filtering/pagination) and you want a compact summary without flooding the context window.
9
+
10
+ ## When to use
11
+
12
+ - **Use `mcp-code-mode`** for:
13
+ - Multi-step MCP workflows (`--mcp-config .mcp.json` or `--mcp "alias=cmd args"`) where you need to chain calls, filter/paginate in RAM, or fan out concurrently with `mapBounded`.
14
+ - >= 4 homogeneous CLI read queries (`--manifest` or built-in `gh`/`engram` plugins).
15
+ - Filtering a previous large spill from `.agent/out/` via `spill.read()` without re-running tools.
16
+ - **Do NOT use it** for:
17
+ - Single 1-step queries (direct tool call has lower overhead).
18
+ - Local file reads, searches, or edits when your harness already provides fast native parallel file tools.
19
+ - Irreversible writes or external side effects (comments, pushes, merges, deletes) — keep those in explicit, visible tool calls.
20
+
21
+ ## Usage
22
+
23
+ ```bash
24
+ # 1. Progressive discovery (compacted MCP + CLI schemas)
25
+ node src/run.mjs --no-default-plugins --mcp-config .mcp.json --list-tools [filter]
26
+
27
+ # 2. Inline MCP batching (no temp file)
28
+ node src/run.mjs --no-default-plugins --mcp-config .mcp.json -e '
29
+ return await mapBounded(args.ids, 4, (id, _i, signal) => tools.mcp.server.tool({ id }, { signal }));
30
+ ' '{"ids":[1,2,3,4]}'
31
+
32
+ # 3. Follow-up filter on the latest spilled output in .agent/out/
33
+ node src/run.mjs -e 'return spill.read().result.slice(0, 10);'
34
+ ```
35
+
36
+ ## Rules
37
+
38
+ 1. Prefer `-e` / `stdin` (`-`) for one-off batches so you do not leave temp `.mjs` files on disk.
39
+ 2. Always pass `{ signal }` from `mapBounded(items, concurrency, (item, idx, signal) => ...)` to `tools.mcp.*` / `tools.*` so failures cancel in-flight work immediately.
40
+ 3. Return compact summaries (counts, statuses, short excerpts), never raw unedited payloads.
41
+ 4. `run.mjs` is an output-bounding runner, not a security sandbox; keep programs strictly read-only.
42
+ 5. Ensure `.agent/out/` is in `.gitignore`.
package/docs/pig.md ADDED
@@ -0,0 +1,131 @@
1
+ # Using this with PiG (`pig`)
2
+
3
+ **Short version: on PiG you should not use this runner.** PiG ships code mode natively — a
4
+ `codemode` tool that runs JavaScript in QuickJS compiled to WebAssembly, inside the `pig`
5
+ process, with no Node.js involved. This page exists so PiG users find that out before wiring
6
+ a Node runner they do not need, and so the five cases where the runner still wins are
7
+ written down honestly.
8
+
9
+ Measured against `pig` 1.7.0 on Windows 11 (Node 24.22.1 available).
10
+
11
+ ## The native equivalent
12
+
13
+ ```jsonc
14
+ // ~/.pig/agent/settings.json
15
+ {
16
+ "defaultTools": ["+codemode"],
17
+ "codemode": { "mode": "on", "inlineBudget": 3000 }
18
+ }
19
+ ```
20
+
21
+ `+codemode` keeps the default `read`, `bash`, `edit`, `write` and adds the script tool.
22
+ `tool_search` is deliberately left out: with no MCP servers configured it has nothing to
23
+ search, and PiG activates it by itself for a server with `deferred` exposure.
24
+
25
+ Reference: `pig docs path` → `codemode.md`.
26
+
27
+ ## API mapping
28
+
29
+ Same job, different runtime. The differences that bite when you port a script:
30
+
31
+ | This repo (Node) | PiG `codemode` |
32
+ | --- | --- |
33
+ | `mapBounded(items, n, fn)` + `{ signal }` | `Promise.allSettled([...])` — there is **no** `mapBounded` |
34
+ | `tools.mcp.github.get_issue(...)` | `tools.mcp__github__get_issue({...})` (double underscore) |
35
+ | `tools.gh.*`, `tools.engram.*` plugins | `tools.bash({ command })`, or an MCP server's tools |
36
+ | `--mcp-config .mcp.json` / `--mcp "alias=cmd"` | `mcp.json` managed by `pig` / `/mcp`; exposure `codemode` by default |
37
+ | `--list-tools [filter]` | `searchTools(q)`, `describeTool(name)`, `describeNamespace(ns)`, `ALL_TOOLS` |
38
+ | `--manifest tools.json` | no equivalent — see *Where the runner still wins* |
39
+ | `CODEMODE_MAX_OUTPUT_CHARS` (32000) | `// @options: {"max_output_tokens": N}` (default 10000) |
40
+ | `spill.read()` on `.agent/out/` | the tool result names a temp file; `tools.read({ path })` it |
41
+ | `jsonArgs` argument | `args` is not a thing; inline the data in the script or `load(key)` it |
42
+ | (none) | `store(key, value)` / `load(key)` between calls |
43
+ | (none) | `models.classify()` / `models.generateImages()` |
44
+
45
+ An options line must be the **first line** of the script:
46
+
47
+ ```js
48
+ // @options: {"max_output_tokens": 2000, "timeout_ms": 60000}
49
+ const [a, b] = await Promise.allSettled([
50
+ tools.bash({ command: "gh pr view 1 --json state,title" }),
51
+ tools.bash({ command: "gh issue view 2 --json state,labels" }),
52
+ ]);
53
+ return [a, b].map((r) => (r.status === "fulfilled" ? r.value.output.trim().slice(0, 200) : r.reason.message));
54
+ ```
55
+
56
+ The sandbox has no Node APIs, no file system of its own, no network and **no timers**. A script
57
+ reaches the outside world only through `tools.*` and `models`. The script is isolated; the tools
58
+ it calls are not — `tools.bash` runs on the host with your privileges. Keep reads inside the
59
+ script and external side effects in explicit tool calls, exactly as `SKILL.md` says.
60
+
61
+ Limits worth knowing: 256 MB per VM, at most two live VMs per `pig` process
62
+ (`PI_CODEMODE_MAX_WORKERS`), no nested `codemode` calls.
63
+
64
+ ## Verify it in one turn
65
+
66
+ ```bash
67
+ pig -p 'Use the codemode tool ONCE: inside the script call tools.bash three times in
68
+ parallel (Promise.allSettled) with "node --version", "git --version" and "echo hello".
69
+ Return only {nodeVersion, gitVersion, echo}. Do not use any other tool.'
70
+ ```
71
+
72
+ Observed on 2026-12-06, pig 1.7.0: **one** `codemode` call, and the model received only
73
+ `{"nodeVersion":"v24.22.1","gitVersion":"git version 2.51.0.windows.2","echo":"hello"}`. Same
74
+ three commands through this runner cost one `node` startup (~130 ms) plus a `cmd.exe` quoting
75
+ hazard on Windows.
76
+
77
+ Two traps the recipe deliberately avoids, both found the hard way:
78
+
79
+ - **Use version commands, not repository ones.** `git rev-parse --short HEAD` outside a git
80
+ repository returns `fatal: Needed a single revision`, which lands in your summary as a value
81
+ (`head: "fatal: ..."`) instead of failing the script — `tools.bash` resolves for non-zero exit
82
+ codes too. Inside a repository, prefer `git -C <path> rev-parse` so the answer does not depend
83
+ on the session's working directory.
84
+ - **Record only output you produced.** A doctored "observed" line, even for a cosmetic edit, is
85
+ the one thing this page cannot afford.
86
+
87
+ ## Where the runner still wins
88
+
89
+ Be specific, keep it short. Inside PiG, reach for `src/run.mjs` only when one of these applies:
90
+
91
+ 1. **The program needs Node APIs.** `fs`, `net`, `crypto`, `timers`, `process`, a local socket, a
92
+ library from `node_modules`. `codemode` forbids all of it.
93
+ 2. **You want declarative CLI manifests.** `--manifest` gives typed argument validation and
94
+ `execFile` without a shell, which is what keeps flag injection and context blowups out. PiG's
95
+ `codemode` has no manifest layer.
96
+ 3. **You want the spill inside the repo.** `.agent/out/` is a stable, `.gitignore`-able path you
97
+ own; PiG writes to its own temp files with generated names.
98
+ 4. **One script shared across harnesses.** A `.mjs` program that Claude Code, Codex and Command
99
+ Code run unchanged has value that an in-session script does not.
100
+ 5. **A stable tool catalog as an artifact.** `--list-tools` prints compacted JSON you can commit,
101
+ diff, or use in CI. `codemode`'s discovery lives inside the session.
102
+
103
+ For everything else on PiG — N homogeneous read queries, fan-out with a concurrency cap, filtering
104
+ a payload before it reaches the model — the native tool is faster to start and has no quoting
105
+ layer.
106
+
107
+ ## Installing the skill variant
108
+
109
+ `SKILL.md` at the repository root is written for harnesses where this runner is the only code
110
+ mode. Feeding it to PiG would send the model down the wrong path, so the PiG variant ships
111
+ separately:
112
+
113
+ ```bash
114
+ cp -r skills/pig ~/.agents/skills/mcp-code-mode-pig
115
+ # or: ~/.pig/agent/skills/mcp-code-mode-pig/SKILL.md
116
+ ```
117
+
118
+ It says: use native `codemode`; fall back to `node <path>/src/run.mjs` only for the five cases
119
+ above. Check it loads with `pig --skill mcp-code-mode-pig -p 'say ok'`, or just look at the
120
+ skill list in a session.
121
+
122
+ ## What a genuinely PiG-native variant would be
123
+
124
+ Not implemented, and probably not worth it now that `codemode` exists: a Go extension that
125
+ declares `gh` and `engram` as codemode **namespaces**, so a script calls `tools.gh.pr_status(...)`
126
+ instead of `tools.bash({ command: "gh pr view ... --json ..." })`. That is the only piece of this
127
+ runner PiG lacks, and it is a `durable.Extension` with a `ToolNamespace`, not a Node program.
128
+
129
+ Everything else here — the stdio MCP bridge, parallel fan-out (`Promise.allSettled`), the output
130
+ bounding, the spill — PiG already does in-process. Duplicating it as a Node sidecar would add a
131
+ process, a config file and a quoting layer to buy nothing.
@@ -0,0 +1,23 @@
1
+ {
2
+ "tools": {
3
+ "git.status": {
4
+ "description": "Short git status for a repository directory",
5
+ "cmd": "git",
6
+ "args": ["-C", "{{dir}}", "status", "--short"],
7
+ "params": {
8
+ "dir": { "type": "string", "default": "." }
9
+ },
10
+ "parse": "text"
11
+ },
12
+ "git.recentCommits": {
13
+ "description": "List recent git commit subjects in a repository directory",
14
+ "cmd": "git",
15
+ "args": ["-C", "{{dir}}", "log", "-n", "{{limit}}", "--oneline"],
16
+ "params": {
17
+ "dir": { "type": "string", "default": "." },
18
+ "limit": { "type": "int", "default": 10 }
19
+ },
20
+ "parse": "text"
21
+ }
22
+ }
23
+ }
@@ -0,0 +1,64 @@
1
+ // Example program: batch PR status with bounded concurrency (default: 4 in flight).
2
+ // Usage:
3
+ // mcp-code-mode examples/pr-status.program.mjs '{"targets":[{"repo":"owner/repo","number":123}]}'
4
+
5
+ function summarizeChecks(rollup) {
6
+ if (!Array.isArray(rollup) || rollup.length === 0) return 'none';
7
+ const counts = {};
8
+ for (const c of rollup) {
9
+ const k = c.__typename === 'CheckRun'
10
+ ? (c.status === 'COMPLETED' ? (c.conclusion || 'unknown') : c.status)
11
+ : (c.state || 'unknown');
12
+ counts[k] = (counts[k] || 0) + 1;
13
+ }
14
+ return Object.entries(counts).map(([k, v]) => `${k}:${v}`).join(' ');
15
+ }
16
+
17
+ async function mapBounded(items, concurrency, fn) {
18
+ const results = new Array(items.length);
19
+ let next = 0;
20
+ async function worker() {
21
+ while (next < items.length) {
22
+ const idx = next++;
23
+ results[idx] = await fn(items[idx], idx);
24
+ }
25
+ }
26
+ const workers = Array.from({ length: Math.min(concurrency, items.length) }, () => worker());
27
+ await Promise.all(workers);
28
+ return results;
29
+ }
30
+
31
+ export async function run({ tools, args }) {
32
+ const targets = Array.isArray(args?.targets) ? args.targets : [];
33
+ const concurrency = Number.isInteger(args?.concurrency) && args.concurrency > 0 ? args.concurrency : 4;
34
+
35
+ if (targets.length === 0) {
36
+ return {
37
+ when: new Date().toISOString(),
38
+ results: [],
39
+ note: 'Pass {"targets":[{"repo":"owner/repo","number":123}]} as jsonArgs',
40
+ };
41
+ }
42
+
43
+ const results = await mapBounded(targets, concurrency, async (target) => {
44
+ try {
45
+ const d = await tools.gh.prStatus(target);
46
+ return {
47
+ repo: target.repo,
48
+ number: d.number ?? target.number,
49
+ state: d.state,
50
+ draft: d.isDraft,
51
+ review: d.reviewDecision ?? null,
52
+ mergeable: d.mergeable ?? null,
53
+ mergeState: d.mergeStateStatus ?? null,
54
+ checks: summarizeChecks(d.statusCheckRollup),
55
+ comments: d.comments?.length ?? 0,
56
+ reviews: d.reviews?.length ?? 0,
57
+ };
58
+ } catch (e) {
59
+ return { repo: target.repo, number: target.number, error: e.message };
60
+ }
61
+ });
62
+
63
+ return { when: new Date().toISOString(), results };
64
+ }