# Show HN: Run-tool, keeps shell output out of Claude Code context

> Source: <https://github.com/ibrahim-bayer/claude-code-token-optimization-by-tool-call>
> Published: 2026-12-06 09:04:08+00:00

**Key takeaway:** Wrapping Bash calls with the run-tool PreToolUse hook cut 7 successful commands from 17,791 tokens to 0 and 7 failing commands from 16,935 to 3,188 tokens (−81%) by returning one line on success and a deterministic error extract with log line references on failure.

**run-tool** cuts the tokens AI coding agents spend reading shell output. It is a zero-dependency Node.js command runner that ships as a **Claude Code hook**, an **MCP server** and a CLI.

- **Success:** a passing test, build, install, lint or`git push` returns one line instead of hundreds.
- **Failure:** a failing one returns a**deterministic error extract** : the failing tests, compiler errors and stack frames that matter, with`L<a>-L<b>` line references into the full log on disk. It uses no LLM summary, so there is no extra model call and no invented error text.

Built by [IB Group](https://ibgroup.dev) while developing [LeanCart](https://leancart.global), and used there in day-to-day agent-driven development.

**Keywords:** Claude Code, Claude Code hooks, PreToolUse hook, MCP server, token optimization, context window, context engineering, AI coding agent, LLM cost reduction, test output summarizer, error extraction, jest, vitest, tsc, eslint, pytest, cargo, go test.

- **Tool output is paid for many times.** A coding agent re-reads its whole context on every API call. So 8,000 tokens of passing-lint output, printed once, is paid for again on each of the next dozens of calls.
- **How much it is:** in 14 days of real agent sessions on a large TypeScript monorepo (the LeanCart codebase), Bash output took about**27% of all input tokens** .
- **Executors are the target, reads are not.** Reads (`cat` ,`grep` ,`git diff` ) are the agent's work and must stay untouched. Executors (tests, builds, installs, lint, typecheck, git writes) mostly need one fact: did it pass? When they fail, the agent needs the failure, not the 400 lines of logger noise around it.

Requires Node.js >= 20. There are no dependencies and nothing to build.

```
npm install -g claude-code-token-optimization-by-tool-call   # run-tool, run-tool-hook, run-tool-mcp on PATH
npm install claude-code-token-optimization-by-tool-call      # as a library (see Library)
```

Or from source: `git clone https://github.com/ibrahim-bayer/claude-code-token-optimization-by-tool-call.git && cd claude-code-token-optimization-by-tool-call && npm test`.

**Claude Code hook (recommended).** The hook rewrites the agent's own Bash calls, so you need no new tool and no prompt changes. Add this to `~/.claude/settings.json` or the project's `.claude/settings.json`:

```
{
  "hooks": {
    "PreToolUse": [
      { "matcher": "Bash", "hooks": [{ "type": "command", "command": "run-tool-hook" }] }
    ]
  }
}
```

**MCP server** (any MCP-capable agent):

```
claude mcp add run-tool -- run-tool-mcp
```

**CLI:**

```
run-tool -- npm test
bash
$ npm test                     # 71 passing tests, 400 lines of logger output
0 (exit 0; 412 lines of output hidden by run-tool; log=/home/me/.cache/run-tool/logs/…-npm-test.log)

$ npx tsc --noEmit             # short failure: the whole output, nothing added
exit=2
src/shipping.ts(26,7): error TS2322: Type 'string' is not assignable to type 'number'.

$ npx jest                     # long failure: the failing tests, not the noise
exit=1 profile=jest-vitest lines=1243 log=/home/me/.cache/run-tool/logs/…-npx-jest.log
L212-L230:
  ● Cart › merging a guest cart sums the quantities of shared items
    - Expected  - 1
    + Received  + 1
…
```

The results are reported in full, including the parts that did not go our way.

**Live commands, output not piped** (a NestJS service, the way an agent runs them when it does not filter output itself):

|  | Plain Bash | run-tool | 
|---|---|---|
| 7 successful commands (install, build, tsc, eslint, jest, nest, node --test) | 17,791 tokens | 0 tokens | 
| 7 failing commands | 16,935 tokens | 3,188 tokens (−81%) | 

- **Long failures** shrink the most: eslint 8,571 → 361 tokens, jest 7,075 → 1,600.
- **Short failures** come back whole, at the same size as plain Bash.

**A/B test with real Claude Code sessions.** The task was "make CI green and commit" on a TypeScript project, run three times with the hook and three times without, using Sonnet 5.5. Every run solved the task, checked independently.

|  | Input tokens per session | Turns | Bash output chars | 
|---|---|---|---|
| without hook | 527k / 467k / 409k (mean 468k) | 10 | 32.4k | 
| with hook | 390k / 385k / 377k (mean 384k) | 8 | 27.8k (−14%) | 

- **The test is noisy.** A control arm whose hook wrapped nothing also came out 12% below the baseline. With 3 runs per arm, the session-level difference is within noise. The direct effect is the −14% in Bash output.
- **Modern agents already filter their own output** (`npm test 2>&1 | tail -80` ). For those agents the savings are modest. For agents and projects that don't filter, the savings are large.
- **A bare `0` confuses an agent that did not ask for it.** It re-ran installs looking for the "missing" output, and one session needed 18 turns. That is why hook mode prints one explanatory line on success.

**Replay over 14 days of LeanCart agent sessions** (1,916 executor calls; this codebase's own tooling already compacts output):

- Turning successes into a single line saves **0.04%–1.45% of all input tokens** . The range depends on how often the agent later needs the hidden output.
- The failure extract kept **100% of the identifiers** the agent cited next for short failures, and**86%** for long ones. The misses are mostly CSS classes that coincide with the agent's own new code.

| Use it | Don't use it | 
|---|---|
| commands where only pass/fail matters: tests, builds, installs, lint, typecheck, formatters, `git commit/push/fetch/rebase/worktree` , deploys, migrations | reading files or searching code ( `cat` ,`grep` ,`sed` ,`head` ,`git diff/log/show` ) | 
|  | commands whose stdout is the data you need ( `curl` GET bodies,`kubectl get` ,`ls` ,`jq` ) | 

```
node bin/run.mjs [--show-warning] [--cwd DIR] [--timeout SEC] [--budget CHARS] [--large-output BYTES] -- <command string>
node bin/run.mjs [options] -- <program> <arg>...   # an argument list, each argument quoted
node bin/run.mjs --last          # print the path of the latest log
```

- The command runs as `bash -o pipefail -c <command>` , with stdout and stderr merged in arrival order.
- **One word after `--` is a shell string** , run as written:`run -- 'npm test 2>&1 | tail -5'` .**Several words are an argument list** , as your shell split them, and each is quoted again:`run -- printf '%s\n' 'a; b'` prints`a; b` and runs nothing else.
- The CLI exits with the command's exit code.
- The default timeout is 600 s. On timeout:
  - The whole process group gets SIGTERM, then SIGKILL 5 s later.
  - The exit code is 124 and the header ends in  `timeout` .
- A command killed by a signal exits with 128 + signo.
- **Stopping run stops the command.** SIGINT, SIGTERM and SIGHUP (Ctrl-C, Esc in Claude Code, a closed terminal) go to the command's whole process group, the log is still written, and run exits with 128 + signo. A SIGKILL of run cannot be forwarded: the command then keeps running.

Success:

``` bash
$ node bin/run.mjs -- npm test
0
$ node bin/run.mjs --show-warning -- npm run build
0
warnings: 7 (2 unique) log=/home/me/.cache/run-tool/logs/20261205T101500-4242-npm-run-build.log
L12: (node:4242) DeprecationWarning: punycode is deprecated
6× L40,L41,L77,…: src/a.ts:N:N warning Unexpected any @typescript-eslint/no-explicit-any
```

Failure (long output):

```
exit=1 profile=jest-vitest lines=412 log=/home/me/.cache/run-tool/logs/20261205T101533-4250-pnpm-test.log
L203-L221:
 FAIL  src/cart.test.ts > cart > applies discount
AssertionError: expected 90 to be 81
 ❯ src/cart.test.ts:42:19
...

L398-L412:
 Test Files  1 failed | 12 passed (13)
      Tests  1 failed | 140 passed (141)
```

To read more of the log, ask for a line range (`sed -n '180,230p' <log>`) rather than the whole file.

When the cleaned output is bigger than 100 KB, the result gets one more line, on success and on failure:

``` bash
$ node bin/run.mjs -- pnpm test
0
warning: large output: 412 KB, 8210 lines (over 100 KB; ~118k tokens to read whole). Read line ranges of the log, and consider a quieter command (e.g. --silent, a dot reporter). log=/home/me/.cache/run-tool/logs/…-pnpm-test.log
```

- **Why 100 KB:** a log that size costs ~30k tokens or more to read whole, and Claude Code's Bash tool keeps only ~30k chars of a result. The warning tells the reader to read ranges, and tells the user the command is noisy.
- **Where it goes:** on success, under the`0` line (with the log path, unless that line already names it). On failure, right under the header. On failure it counts toward the budget; with a very small budget it shortens to`warning: large output: 412 KB (~118k tokens)` , or is left out.
- **Threshold:**`--large-output BYTES` , the`RUN_TOOL_LARGE_OUTPUT_BYTES` env var, or the MCP argument`largeOutputBytes` .`0` turns it off. The exit code never changes.

`bin/mcp.mjs` is a stdio MCP server (JSON-RPC 2.0, one message per line, protocol `2025-06-18`), written by hand with no SDK. It exposes one tool, `run`:

| Argument | Type | Required | Default | 
|---|---|---|---|
| `command` | string | yes |  | 
| `cwd` | string | no |  | 
| `showWarning` | boolean | no | `false` | 
| `timeoutSec` | number | no | `600` | 
| `largeOutputBytes` | number | no | `100000` (`0` = off) | 

It returns `{content:[{type:"text", text}], isError: exit !== 0}`. A `notifications/cancelled` for a running call stops its command's process group and the call gets no reply. SIGINT, SIGTERM or SIGHUP to the server stops every running command; when stdin closes, running commands finish first.

**The `run` tool is a shell with no rules of its own.** Claude Code's `Bash(…)` allow, ask and deny rules do not apply to an MCP tool: approving `mcp__run-tool__run` with "always allow" lets the agent run any command through it without a prompt. Allow it only where you would allow every Bash command, or keep it on ask.

Registration example (documentation only; nothing in this repo changes your config):

```
{
  "mcpServers": {
    "run-tool": {
      "command": "node",
      "args": ["/absolute/path/to/run-tool/bin/mcp.mjs"],
      "env": { "RUN_TOOL_LOG_DIR": "/absolute/path/to/logs" }
    }
  }
}
```

With Claude Code: `claude mcp add run-tool -- node /absolute/path/to/run-tool/bin/mcp.mjs`.

`bin/hook.mjs` is a `PreToolUse` hook. It rewrites the agent's own Bash calls, so the agent needs no new tool and no instructions.

```
{
  "hooks": {
    "PreToolUse": [
      { "matcher": "Bash", "hooks": [{ "type": "command", "command": "node /path/to/run-tool/bin/hook.mjs" }] }
    ]
  }
}
```

- 
**Pipelines are wrapped one at a time.** In`cd app && npm ci && npm test 2>&1 | tail -40; git log -1` , only`npm ci` and`npm test 2>&1 | tail -40` go through run. The`cd` and the`git log` stay in the outer shell.
- 
**A wrapped pipeline:** it starts with an executor (test runner, build, install, lint, typecheck, formatter, git write, docker build, …), and every later stage is a filter (`tail` ,`grep` ,`head` , …). Under run's pipefail, the executor's exit code decides the result.
- 
**Never wrapped:** reads (`cat` ,`grep` ,`git diff` ), unknown programs (`node script.js` ,`curl` ), and`run_in_background` .
- 
**The whole command is left alone** when it has:
  - a `&` ;
  - a heredoc;
  - control flow (`for` ,`if` , subshells);
  - shell state (`X=…;` ,`export` ,`source` );
  - a comment (`#` at the start of a word);
  - command or process substitution: `$(…)` , backticks,`<(…)` ,`>(…)` , also inside double quotes;
  - a redirect other than `2>&1` (`> file` ,`>> file` ,`&> file` ,`< file` );
  - ANSI-C quoting (`$'…'` ,`$"…"` ).
 A wrapped pipeline runs in a new bash and could not see shell state. The rest is refused because a wrapped pipeline becomes one quoted argument of run: a comment would swallow its closing quote and let the rest of the line run unwrapped, and a permission rule can no longer see what is nested inside it. A command the hook leaves alone runs exactly as written and goes through Claude Code's normal permission check.
- a 
- 
**Output on success:** the hook passes`--explain-success` , so a success prints one line:`0 (exit 0; N lines of output hidden by run-tool; log=…)` . With a bare`0` , an agent that never asked for run took the`0` as the command's own output. It went looking for the real output: it re-ran installs and inspected the package-manager binary.
- 
**Timeout:** the Bash tool's`timeout` (default 120 s) becomes`--timeout` minus 5 s, so run kills its process group before the Bash tool gives up. When one command has several wrapped pipelines, each gets that limit on its own. So a long first pipeline can still leave the Bash tool's limit to cut off a later one.

Claude Code checks permissions against the **rewritten** command (`node …/run.mjs -- '…'`), so your `Bash(npm test:*)` rules no longer match it. The hook therefore works like this:

| Mode | What the hook does | 
|---|---|
| `bypassPermissions` | wraps unless an `ask` or`deny` rule matches a stage, and returns no permission decision | 
| `plan` | does nothing | 
| any other mode | wraps only when your settings files allow every stage of the whole command and no `ask` or`deny` rule matches any stage; it then returns`allow` , otherwise it leaves the command alone | 

- **Stages that need no rule:**`cd` , and these filters after a wrapped executor:`head` ,`tail` ,`grep` ,`egrep` ,`fgrep` ,`wc` ,`cut` ,`tr` ,`uniq` (flags only),`column` ,`nl` ,`sort` (without`-o` ,`--output` or`--compress-program` ). A stage that can write a file or run a program (`awk` ,`sed` ,`find` ,`tee` ,`xargs` , …) needs its own allow rule, like any other command.
- **Why `ask` and `deny` count in every mode:** once a command is wrapped, the original is one quoted argument of`node …/run.mjs` , and a rule such as`Bash(rm:*)` no longer matches what is nested in it. So the hook never wraps a command that a rule would ask or deny as written.
- **What the hook reads:** the managed settings (`/etc/claude-code/` on Linux,`/Library/Application Support/ClaudeCode/` on macOS), the user settings, and the project's`settings.json` and`settings.local.json` . Rules given only on the command line (`--allowedTools` ,`--disallowedTools` ) are invisible to it: with them, keep the hook off or use settings files.
- **Switches:**  - `RUN_TOOL_HOOK=off` disables the hook.
  - `RUN_TOOL_HOOK=always` wraps without a permission decision. Use it only where your permission setup already allows the rewritten command.
  - `RUN_TOOL_HOOK_EXTRA=<regex>` marks more commands as executors, e.g.`^\./scripts/ci\.sh` .

Other tools import the same pieces instead of keeping their own ANSI regex or tail logic:

``` js
import { clean, tailLines, headLines, extract, largeOutput, run } from 'claude-code-token-optimization-by-tool-call';

const text = clean(rawCiLog);                 // ANSI, CI markers, \r redraws, control chars
const last120 = tailLines(text, 120);         // the last 120 lines
const shown = headLines(lines, 60, (k) => `… ${k} more lines in the log`);
const big = largeOutput(text);                // null, or { bytes, lines, tokens, threshold }
const summary = extract(text, { exitCode: 1, logPath });
```

| Export | What it does | 
|---|---|
| `clean(text)` | strip ANSI and CI markers, resolve `\r` , drop control chars; lines stay 1:1 | 
| `stripAnsi` ,`stripCiMarkers` ,`resolveCR` ,`toLines` ,`cutLine` | the steps of `clean` , and line splitting | 
| `tailLines(textOrLines, n)` | the last `n` lines | 
| `headLines(lines, max, more?)` | at most `max` lines, the last one saying how many were left out | 
| `extract(text, opts)` | the run result text ( `0` , or the failure extract) | 
| `outputSize(text)` ,`largeOutput(text, threshold?)` ,`largeOutputLine` ,`largeOutputThreshold(env)` | the large-output check | 
| `run(command, opts)` | spawn, time out, write the cleaned log; returns `{ exitCode, timedOut, aborted, logPath, text, lines }` .`opts.abortSignal` (an`AbortSignal` ) stops the process group; the library installs no signal handlers of its own | 
| `VERSION` | the package version | 
| `hookDecision(event, opts)` | the hook's decision, for a host with its own hook runner | 

- **Location:**`$RUN_TOOL_LOG_DIR` , or`~/.cache/run-tool/logs/` when that is unset.
- **File name:**`<YYYYMMDDTHHMMSS>-<pid>-<slug>.log` , where the slug comes from the first 40 chars of the command.
- **`last`:** a file in the same directory that holds the latest log path.
- **Contents:** the*cleaned* output. ANSI escapes and GitLab CI`section_start` /`section_end` markers are stripped, and`\r` progress redraws are resolved. Lines are never collapsed or cut, so line N of the file is exactly what the extract calls`L<N>` .
- **Cap:** when the cleaned output exceeds 20 MB, the log keeps the first 2 MB and the last 18 MB, with one marker line in between:`[run-tool: log capped, N lines (B bytes) omitted here; line numbers below are shifted]` .
  - **Line numbers after the marker shift:**`L<N>` still matches line N of the*file* , but no longer matches the command's original line N.
  - The extract is computed from the capped text, so its references stay consistent with the file.
- **Private, not masked.** Logs hold the full output, tokens and passwords included: run-tool masks nothing. A log directory run-tool creates is`0700` ; logs and`last` are`0600` . A directory that already exists keeps its own mode.
- **Retention** , on every run, only for files run-tool wrote (names matching the pattern above; other files in the directory are never touched):
  1. Delete logs older than 7 days.
  2. Then delete the oldest logs until they total at most 200 MB.
  3. Delete the raw temporary files (`.raw-<pid>-…` ) of runs whose process is gone.
- **Disk use while a command runs** is not capped: the raw output goes to a temporary file and the 20 MB cap applies when the command ends.

The header is always the first line on failure:

```
exit=<code> profile=<parser|generic|short> lines=<total log lines> log=<path>[ timeout]
```

A short failure (whole output returned) has the header `exit=<code>[ timeout]` only: the log path would add ~100 chars to most failures and tell the reader nothing new. A long failure keeps the absolute log path, since file-read tools do not expand `~`.

- **Short body:** 60 lines or fewer and within the budget. The text comes back whole, with consecutive duplicates collapsed to`line (×N)` .
- **Long body:**`L<a>-L<b>:` blocks in log order, separated by blank lines. The budget is 6000 chars by default; the header does not count toward it. The body is filled in this order:
  1. **The tail:** the last 15 non-empty lines, at most 1500 chars. It is always included.
  2. **Parser blocks** from the winning parser, ordered by priority (summary lines and final tracebacks rank higher), then earliest first. When another parser wins, npm/pnpm blocks are added next.
  3. **Generic error-regex hits** that are not already covered.
  4. **Context fill** (an extension; see below).
  5. If anything was dropped: `… +K more blocks (L…, L…) — see log` .

Shaping inside the blocks:

- A message repeated across blocks is shown once as `(×N, also L…)` .
- Stack traces keep at most 3 project frames; the rest become `(+N frames)` .
- Runs of git `hint:` lines fold to 2.
- Lines over 400 chars are cut to `…(+N chars)` .

Each parser in `src/parsers/` exports `{name, detect(lines), blocks(lines)}`. The one with the highest `detect` score of at least 0.5 wins.

- Detection reads the output only.
- The command matters only as a tie-break between scores within 0.05 of each other, through each parser's `hint` regex.

The parsers are tap, jest-vitest, playwright, tsc, eslint, nextjs-build, python, go, rust, npm-pnpm, docker, git, prettier and generic.

- 
**Context fill.** If budget remains after the parser and generic blocks, two more steps run:
  1. Add the head of the output: the first 10 non-empty lines, at most 1000 chars.
  2. Add whole gaps between the selected blocks, smallest first.
 Context never includes warning lines, or lines the winning parser marks as noise, such as eslint warning rows or git hints. On the dev corpus this step lifts long-bucket recall from 0.86 to 0.96, because agents often cite identifiers from lines near an error that no rule marks as one.
- 
**Light normalisation for cross-block dedupe.** Only volatile numbers are masked: hex ids, timestamps,`line:col` , durations, and decimals of 3+ digits. Messages that differ by a count or an index stay distinct.
- 
**Tail lines are pinned.** Cross-block dedupe never removes a tail line, so the summary is always visible.
- 
**Long-line cut only when rendering.** The log keeps full lines, so that`L` references and`sed -n` reads return the real text.
- 
**Frame folding without project frames.** When a trace has no project frames, its first frame is kept so the throw site stays visible.
- 
**The `prettier` parser** is extra:`[warn] file` lists and`[error]` blocks are common, and generic handles them poorly.
- 
**Library frames** follow the spec's list, plus`<frozen …>` and`/usr/lib/python` .
  - `node:child_process` and similar`node:` modules outside`node:internal` count as project frames.

```
node --test test/*.test.mjs  # unit, fixture, exec, mcp and cli tests
node scripts/replay.mjs    # recall/budget metrics over fixtures/corpus-dev.jsonl (gitignored)
node scripts/replay.mjs --show <id>   # print one record's extract
```

The test fixtures in `test/fixtures/` are synthetic. A line `@@NOISE n template@@` expands to n generated lines (see `test/helpers.mjs`).

- **The hook rewrites fewer commands.** Comments, command and process substitution, redirects other than`2>&1` and ANSI-C quoting leave the command alone in every mode (§ What it wraps). Before,`npm test # note; rm -rf x` became a wrapped`npm test` followed by an unwrapped`rm` .
- **`ask` and `deny` rules apply in every mode** ,`bypassPermissions` and`RUN_TOOL_HOOK=always` included, and only read-only filters follow a wrapped executor without a rule (§ Permissions). Before,`| awk 'BEGIN{system(…)}'` ,`| tee file` and`| sort -o file` passed as filters.
- **Stopping run stops the command** (CLI signals, MCP cancellation); before, the command kept running in its own process group.
- **Retention deletes only run-tool's own files** , and now also the raw files of dead runs. Before, any`*.log` older than 7 days in`RUN_TOOL_LOG_DIR` went.
- **Logs are private** (`0700` directory,`0600` files).
- **The CLI quotes an argument list.**`run -- printf '%s\n' 'a; b'` used to run`b` .
- The MCP server reports the package version; `package.json` declares`"os": ["linux", "darwin"]` (the code needs bash and POSIX process groups).

Found by testing on a held-out transcript half and live commands, not by the builder's own tests:

- **Markup dumps fold.** Testing Library`<body>` dumps (8+ markup lines) collapse to their first 2 lines plus`(+N lines of markup, La-Lb; rendered: "text" #testid …)` . The tags and classes are dropped; rendered text nodes and`data-testid` values are kept, because that is what a reader uses from a dump.
- **eslint context fill.** Warning-only files no longer come back through the context fill: they used to fill a 6000-char budget with 120 file headers. eslint rows have their column padding squeezed. Code frames keep their spacing, so carets still point at the right column.
- **`showWarning` on failure.** It now also applies on failure. The warnings section takes up to 25% of the budget.
- **Binary output.** Output containing a NUL byte, or with more than 10% U+FFFD, renders as`[binary output: N chars, not shown; see log]` .
- **Missing `--cwd`.** It reports` cwd does not exist: <dir>` instead of`spawn bash ENOENT` .

run-tool was built by **[IB Group](https://ibgroup.dev)**, the team behind **[LeanCart](https://leancart.global)**.

- **LeanCart:** a multi-tenant e-commerce SaaS platform built for zero-developer store management.
- **How LeanCart is developed:** largely with AI coding agents. That workflow made token cost and context-window size a daily engineering concern, and this tool came out of it.
- **How it was built:** the tool itself was built by a coding agent from[SPEC.md](https://github.com/ibrahim-bayer/claude-code-token-optimization-by-tool-call/blob/main/SPEC.md) . It was then reviewed, measured on held-out agent sessions and hardened by hand.

Want to build a product with AI-assisted engineering, or to run an e-commerce store without a developer team? Visit [ibgroup.dev](https://ibgroup.dev) and [leancart.global](https://leancart.global).

[MIT](https://github.com/ibrahim-bayer/claude-code-token-optimization-by-tool-call/blob/main/LICENSE) © ibrahim-bayer
