Skip to main content
Glama

ctxcap

context tokens

npm ci license

Your coding agent can only follow the context it can see. If that context is bloated, stale, or unsafe, useful rules can get buried and the agent can chase files and commands that are gone. ctxcap why diagnoses the repository context your agent can load: it ranks measured instruction and skill files, names configured MCP servers, and points to broken references and risky content.

npx ctxcap why
ctxcap why — repository context diagnosis
Largest known repository sources (full-file sizes; active use is client-dependent):
  1. AGENTS.md — 2,880 tokens [startup]
     Fix: fix the stale reference at line 18; move task-specific guidance to a skill
  2. skill: release-helper — 640 tokens [on-demand]
     Fix: remove obsolete guidance; the skill body loads only when invoked

Configured MCP servers (not launched; live tool-schema cost is unknown):
  MCP: playwright — cost unknown (stdio, .mcp.json)
     Fix: disable playwright in .mcp.json if unused; inspect the client's exposed tools for its session cost

Findings: 1
  AGENTS.md:18 ERROR stale-path — `src/old-auth.js` does not resolve
     Fix: update or remove the reference

Counts are approximate. ctxcap why never launches configured MCP servers and does not pretend to know what a client loaded in a particular session. Once installed, ctxcap runs offline: no runtime network calls, telemetry, or API key. A cold npx run may fetch the package from npm. Node 20 or newer.

The usual CLI, CI gate, and budget planner are still here; diagnosis is the reason to start with ctxcap.

What it does

  • Diagnoses. ctxcap why ranks repository instruction and skill files, names configured MCP servers, and gives a fix for each source or finding.

  • Finds defects and risky content. Checks instruction references against repository paths and scripts; flags recognizable credential patterns and explicit permission/sandbox bypass flags. Credential values are redacted.

  • Measures. Approximate file token counts as text, JSON, or SARIF.

  • Warns before compaction. Claude Code can name the largest known always/startup repository context file; this is not the full session total.

  • Supports follow-up. Optional PR reporting and a ranked trim plan help keep the configuration healthy over time. See Gate pull requests and Trim to a budget.

The security checks are deliberately narrow heuristics, not a full secret scanner or a certification that an agent setup is safe. Findings need human review.

By default the token CLI scans CLAUDE.md, AGENTS.md, .github/copilot-instructions.md, prompts/**, *.prompt, and .cursor/rules/**. ctxcap why also discovers repository skill files such as .claude/skills/**/SKILL.md, .agents/skills/**/SKILL.md, .cursor/skills/**/SKILL.md, and skills/**/SKILL.md.

Related MCP server: parecode

Quick start

Run it in the repository you want to inspect. It does not install into that project or write repository files (a cold npx run may fetch the package into the npm cache):

npx ctxcap why          # ranked diagnosis, stale/security findings, named MCP servers and skills
npx ctxcap --json       # token report as JSON
npx ctxcap --stale      # dead paths, commands, and references only
npx ctxcap --compare    # this file's percentile in the Context Budget Index

why counts repository context files and skill files in full. It labels skills as on-demand, lists MCP server names from .mcp.json, .cursor/mcp.json, .vscode/mcp.json, or .claude/settings.json without starting them, and reports live MCP tool-schema cost as unknown unless the connected client exposes that data.

To track growth, commit a baseline. Later runs report the delta against it:

npx ctxcap --update-baseline
git add ctxcap-baseline.json
git commit -m "Add ctxcap baseline"

To pin it as a dev dependency instead of using npx: npm i -D ctxcap.

Wire it up

npx ctxcap init          # print the diff of every file it would touch
npx ctxcap init --yes    # write them

Agents do not search npm. They read the config that is already in the repository. init writes that config for each agent, and you commit it, so every clone and every teammate's agent has ctxcap without running anything. Nothing is installed, and nothing runs at install time.

Agent

--agents

Files

Cost in the context window

Claude Code

claude

.claude/skills/ctxcap/SKILL.md, three hooks in .claude/settings.json, .ctxcap/.gitignore

70 tokens per session for the skill's name and description, 362 once the skill loads

Cursor

cursor

.cursor/rules/ctxcap.mdc

140 tokens when a CLAUDE.md or AGENTS.md is in the conversation

Codex

codex

A 2-line block in AGENTS.md

51 tokens per session

Copilot

copilot

A 3-line block in .github/copilot-instructions.md

101 tokens per session

CI

ci

.github/workflows/ctxcap.yml

None

README badge

badge

.ctxcap/badge.json, one line under the README title

None

MCP server, opt-in

mcp

A server entry in .mcp.json and in .cursor/mcp.json

About 500 tokens per session for four tool definitions

The costs are counted by ctxcap itself and are approximate. The blocks in AGENTS.md and the Copilot file, and the Cursor rule, are context files, so they show up in your own report. The MCP server is not written by default: it costs about 500 tokens in every session and starts a server process, for the same measure, plan, and verify steps the skill gives Claude Code for 84. What it adds is the same tools in Claude Code and Cursor. To include it, name it: npx ctxcap init --yes --agents claude,mcp.

The three Claude Code hooks stay quiet unless there is something to say:

  • After an edit to a context file, the agent gets one line with the new count and the total. Other edits print nothing.

  • Before compaction, Claude Code gets the largest known always/startup repository context source and its approximate file size. It explicitly does not claim to see the full session, loaded skills, or MCP tool schemas.

  • When the agent stops, you get one line if the total is over the budget in .ctxcap.json. It never blocks the agent from stopping.

Hooks start npx; once cached this is usually about a second. The pre-compact hook runs only when Claude Code is about to compact, not on every edit.

What it runs

init runs nothing: it writes files. These are the commands those files contain, word for word, and when each one runs. Every npx command downloads ctxcap from npm the first time and uses the npm cache after that. ctxcap itself makes no network calls.

Written to

Command

Runs

.claude/settings.json

npx -y ctxcap@1.6.0 hook post-edit

After every Edit, Write, or MultiEdit in Claude Code

.claude/settings.json

npx -y ctxcap@1.6.0 hook pre-compact

Before Claude Code compacts context

.claude/settings.json

npx -y ctxcap@1.6.0 hook stop

Each time Claude Code finishes responding

.claude/skills/ctxcap/SKILL.md

npx ctxcap@1.6.0 why

When the agent follows the skill

npx ctxcap@1.6.0 --json

npx ctxcap@1.6.0 --stale --json

npx ctxcap@1.6.0 --plan --budget <n>

npx ctxcap@1.6.0 --plan --budget <n> --apply

npx ctxcap@1.6.0 --verify <planId>

.cursor/rules/ctxcap.mdc

npx ctxcap@1.6.0 why

When Cursor follows the rule

npx ctxcap@1.6.0 --plan --budget <n>

npx ctxcap@1.6.0 --verify <planId>

AGENTS.md

npx ctxcap@1.6.0 why

When the agent follows the instruction

.github/copilot-instructions.md

npx ctxcap@1.6.0 why

When Copilot follows the instruction

npx ctxcap@1.6.0 --plan --budget <n>

.github/workflows/ctxcap.yml

actions/checkout@v4

On every pull request

Naeha-S/ctxcap@v1.6.0

.mcp.json, .cursor/mcp.json

npx -y -p ctxcap@1.6.0 ctxcap-mcp

When the client starts, with --agents mcp only

What they write: the post-edit hook touches .ctxcap/post-edit.stamp and, if .ctxcap/badge.json exists, rewrites it. --plan saves the plan under .ctxcap/plans/. Only --plan --budget <n> --apply edits a context file, and only an agent or a person runs it; no hook and no workflow does. With --no-pin the same commands are written without @1.6.0, and the action as Naeha-S/ctxcap@v1.

Flag

Effect

--yes

Apply the diff. Without it, nothing is written

--print

Print the diff and exit 0

--agents <list>

Comma-separated subset of claude,cursor,codex,copilot,ci,badge,mcp (default: all but mcp)

--remove

Undo what init wrote, for every agent unless --agents is given

--force

Overwrite a file or entry at a ctxcap path that init did not write

--no-pin

Write npx ctxcap instead of npx ctxcap@1.6.0

Commands are pinned to the version that wrote them, so a release cannot change what your agents run until you choose to upgrade. To upgrade, run init --yes with the new version: it brings everything init wrote up to date, pins included. A target that is already current is reported as skipped: <path> (already configured), and running init --yes twice changes nothing the second time.

--yes only ever touches what init wrote. If something init did not write sits where a target would go, such as a hand-written workflow or your own ctxcap entry in a JSON file, it is left alone and reported, and the exit code is 3. --force overwrites it. Exit codes: 0 done, 3 when a target was left alone and needs --force, 2 for a bad flag.

A workflow that already runs ctxcap, through the action or through npx, is reported as wired by user. It counts as wired, init does not add a second workflow beside it, and the exit code stays 0.

Every write is reversible

  • Markdown gets a block between <!-- ctxcap:begin --> and <!-- ctxcap:end -->. Text outside the block is never changed.

  • JSON files are parsed and merged, never rewritten. Your keys keep their order, indentation, and line endings. A top-level _ctxcap key records the version that wrote the entries.

  • Files that init creates whole (the skill, the Cursor rule, the workflow, .ctxcap/.gitignore) carry a ctxcap:managed marker. A file at one of those paths without the marker is yours, and init leaves it alone.

  • A .ctxcap/ line in your .gitignore would hide the badge, and git does not read a .gitignore inside an ignored directory. init replaces that line with .ctxcap/plans/ and .ctxcap/*.stamp between # ctxcap:begin and # ctxcap:end, and keeps the original line inside the block. --remove puts it back exactly. A .gitignore without that line is not touched.

  • .ctxcap/badge.json cannot carry a marker, because shields.io rejects keys it does not know. init writes .ctxcap/badge.owned beside it instead. --remove deletes the badge only while that file is there, so a badge you made yourself with ctxcap --badge is never deleted.

npx ctxcap init --remove          # print what would be removed
npx ctxcap init --remove --yes    # remove it

--remove deletes the blocks, the marked JSON entries, the files init created, and any file or directory that ends up empty. The test suite checks that init --yes followed by init --remove --yes leaves the repository byte-for-byte as it was, including one that already had hooks and an AGENTS.md.

Check the wiring

npx ctxcap doctor
claude   partially wired: missing .claude/skills/ctxcap/SKILL.md
cursor   not wired
codex    stale pin: AGENTS.md has 1.5.0, current is 1.6.0
copilot  wired
ci       wired: by .github/workflows/lint.yml, not written by ctxcap init
badge    wired
mcp      not wired

doctor exits 1 when an agent is partially wired or pinned to a different version than the one running, and 0 otherwise. --json prints the same as JSON. npx ctxcap init --yes brings stale pins up to date.

Badge

npx ctxcap --badge

writes .ctxcap/badge.json in the shields.io endpoint format:

{"schemaVersion":1,"label":"context","message":"476","color":"green"}

Under 500 tokens is green, under 2,000 is yellow, and anything above is red. init adds the badge under the README title, pointing at the raw GitHub URL of that file on the default branch.

shields.io fetches the file over the public internet, so the badge only works when the file is committed to a public repository. On a private repository it shows an error. The number is as fresh as the last commit of badge.json: the Claude Code hook rewrites it after a context file changes, and otherwise you run npx ctxcap --badge before you commit. init skips the badge when the repository has no GitHub remote.

Gate pull requests

name: ctxcap
on: pull_request

permissions:
  contents: read
  pull-requests: write
  security-events: write   # for SARIF upload; drop if you set upload-sarif: false

jobs:
  ctxcap:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with: { fetch-depth: 0 }
      - uses: Naeha-S/ctxcap@v1
        with: { fail-on: increase }

Pin Naeha-S/ctxcap@v1.6.0 if you want reproducible runs. A complete workflow is in examples/pull-request.yml.

The action posts one comment on the pull request and updates it in place:

ctxcap — +8 tokens (371 total), approximate — growth accepted by the baseline updated in this change

File

Tokens

Delta

AGENTS.md

287

+78

llms.txt

84

-70

fail-on decides when the check goes red:

Value

Fails when

never (default)

Never; the action only reports

increase

The total grew since the merge base and the baseline was not updated

budget

A budget in .ctxcap.json is exceeded

stale

The stale pass has findings (needs stale: true)

With fail-on: increase, a pull request that grows a context file on purpose passes when it also commits the refreshed baseline (npx ctxcap --update-baseline). The baseline diff is what the reviewer approves. The first pull request that adds the action passes the same way.

Commit the baseline before the first run, not after. --baseline <ref> reads ctxcap-baseline.json at that ref, so with no baseline in the repository there is nothing to compare against and the delta becomes each file's whole size: every pull request that touches a context file fails, including the one that only adds the workflow. Run npx ctxcap --update-baseline and commit ctxcap-baseline.json in the same pull request as the workflow. Existing repositories have this problem; a repository that started with a baseline does not.

Inputs:

Input

Default

Description

fail-on

never

increase | budget | stale | never

config

.ctxcap.json

Path to config file

path

.

Root directory to lint

comment

true

Post the sticky pull request comment

upload-sarif

true

Upload SARIF to code scanning

stale

false

Run the stale-reference pass

stale-glob

false

Include globs that match no files

Every run adds a job summary with the token table, and annotations on files that are over budget. The comment and the SARIF upload need a token that can write, which pull requests from forks do not get under plain pull_request. For forks, use pull_request_target as shown in examples/pull-request-target.yml. That event has a write-capable token: check out the PR into a subdirectory, pass the same directory as the action's path, and never run PR-controlled scripts or install PR dependencies in that job. The example keeps the checkout under pr/. On private repositories, code scanning needs GitHub Advanced Security; without it the SARIF upload does nothing.

Find stale references

npx ctxcap --stale                    # list them
npx ctxcap --stale --fail-on stale    # exit 1 if there are any
npx ctxcap --stale --stale-fix        # print a deletion diff; writes nothing

The stale pass prefers silence to guessing. It only checks references that are spelled like a path into this repository:

  • with a slash, the first segment must be an existing directory (src/gone.js is checked; origin/main, feat/x, and @scope/pkg are not);

  • without a slash, the name must end in a known file extension and exist nowhere in the repository (gone.config.ts is checked; console.log and 1.2.3 are not). A bare extension is a kind of file, not a file: .py, .tsx, and .go are never reported;

  • npm run <script> must be a script in some package.json in the repository.

Four more shapes are skipped because absence proves nothing about them: a path your .gitignore covers (.claude/settings.local.json is meant to be missing), a path introduced as an illustration (e.g., such as), a path named in a prohibition (forbidden strings: assets/old-hero.jpeg), and a path named in a statement that it is absent (No rustfmt.toml; stock defaults). If a real reference is skipped this way, delete it by hand.

Paths resolve against the repository root and the context file's own directory. Fenced code blocks, absolute paths, ../ paths, URLs, and anything containing ~, $, :, or < are skipped. Each finding names the dead reference in ref and the lines it would remove in startLine/endLine: the list item that holds the reference, or the paragraph when it is not in a list. Add <!-- ctxcap-ignore --> to a line to suppress it.

--stale-fix leaves out blocks that also hold a rule (must, never, always, do not); fix those by hand. There is deliberately no mode that deletes stale lines for you.

A clean result means no reference of those shapes failed to resolve. It does not mean the file is up to date.

The Context Budget Index

A named, monthly index of what the most-starred repositories on GitHub spend on agent instructions. The most-starred 25 repositories that have an AGENTS.md or CLAUDE.md at the root are counted; in November 2026, 25 of the top 56 had one. Every month has a permanent page, and the data is a JSON file in leaderboard/.

The point of a percentile is that it travels. ctxcap ships the distribution, so one command places the file you are looking at:

npx ctxcap --compare
AGENTS.md: 4,100 tokens — larger than 27 of 30 context files in The Context Budget Index (2026-11), 90th percentile.

The same lookup is a form on the index page: type a token count and it returns the percentile without sending anything anywhere. --json adds a comparison object with the month, rank, and sample size. The count is compared against the largest context file in the run, because the index ranks files, not totals.

The index does not say a large file is a bad file. Six thousand tokens of rules an agent needs are well spent. It says what the file costs, and how it compares.

The month's analysis asks the question the table invites — whether size falls as stars rise. It does not fall: the correlation is weakly positive and not distinguishable from zero, and the document says so rather than repeating the guess. The benchmark writeup puts the method and all three measurements — context files, MCP tool definitions, stale references — in one place.

The most-starred repositories compared

Measured with ctxcap --stale on 16 November 2026, from each default branch:

Repository

Context files

Tokens

Stale findings

langchain-ai/langchain

AGENTS.md

4,685

0

pydantic/pydantic-ai

AGENTS.md

4,658

0

anomalyco/opencode

AGENTS.md

4,025

0

n8n-io/n8n

AGENTS.md, CLAUDE.md

6,254

0

affaan-m/ECC

42 files

13,286

0

ultraworkers/claw-code

11 files

9,008

0

modelcontextprotocol/python-sdk

AGENTS.md, CLAUDE.md

2,223

0

astral-sh/uv

AGENTS.md

823

0

modelcontextprotocol/typescript-sdk

CLAUDE.md

296

0

The first two are how the stale pass was tuned for paths. An earlier version treated any dotted or slashed inline code as a path and reported 41 findings across opencode and langchain, nearly all of them wrong.

The last four were added by running it against the repositories in the monthly leaderboard, which is a harder test than a curated list because nobody chose those files to be clean. Four kinds of false positive came out of it, all now covered by the rules above: bare extensions (.py, .tsx) reported as missing files, a path their .gitignore covers, a path introduced with e.g., and a path listed under forbidden. affaan-m/ECC went from 12 findings to 0 and ultraworkers/claw-code from 2 to 0.

The MCP Context Cost Index

An MCP server's tool definitions are sent to the model at the start of every session, before the first question. Almost nobody knows what they cost. The index measures the pinned versions of 16 popular servers over stdio, with tools/list, and ranks them.

Server

Tools

Tokens

Sentry

73

46,512

Firecrawl

32

17,764

Notion

24

17,163

Chrome DevTools

33

6,753

Playwright

25

3,936

GitHub

26

3,548

ctxcap's own server

4

507

The largest sends 92 times the definitions of ctxcap's own four-tool server, which does the measure, plan, and verify steps the skill gives Claude Code. The count covers name, description, and inputSchema, which is a lower bound: title, annotations, and outputSchema are left out because not every client sends them. Servers that hide their tools until configured are listed as not measured, with the reason, rather than dropped. Data and method: mcp-index/.

Stale-reference receipts

The stale pass finds factual defects: a path in a context file that does not exist. Once a month, every repository in the index is checked this way, and every finding is read by a person before it is called a defect.

Month

Repositories

Found

Confirmed

Excluded after reading

2026-11

25 selected (23 scanned)

5

2

3

  • twbs/bootstrap AGENTS.md:3 says "Tool-agnostic; CLAUDE.md points here." There is no CLAUDE.md.

  • avelino/awesome-go AGENTS.md:38 says the workflow runs .github/scripts/check-quality.js. That path is a directory holding a Go program.

Both are one-line fixes, with a patch and a pull request body under receipts/prs/. The three excluded findings are published too: two scaffolding templates in AutoGPT and one "turbo.json or turbo.jsonc" alternative. Hiding the false positives would make the true ones worth less. The receipts are also a time-boxed audit series.

Roast it

npx ctxcap roast
6,249 tokens. This is a short story, not an instruction file.

One line, deterministic, no model and no network: the same repository gets the same sentence on every machine. It roasts the largest context file, and if --stale finds dead references that outranks size. --json returns {tokens, file, roast}. Exit code is always 0.

Start from a template

examples/boilerplate/ is a repository with a context budget from its first commit: an AGENTS.md, a 2,000-token .ctxcap.json, and a pull request workflow. Copy it, or run npx ctxcap init --yes, which writes the wiring for the agents the repository uses and prints the diff first. The template README also has the one line to paste into a scaffold or starter kit, for maintainers who want the measurement in every repository generated from it.

Trim to a budget

When a file is over budget, agents tend to rewrite it from memory and drop the ## Never rules on the way. --plan gives the agent line ranges to cut instead, and --verify checks the result.

npx ctxcap --plan --budget 400              # ranked plan, JSON
npx ctxcap --plan --budget 400 --apply      # apply it
npx ctxcap --verify <planId>                # check what landed

Three rules for the agent:

  1. Splice by startLine/endLine. Never rewrite a file from scratch.

  2. Never cut a span listed in preserve. The one exception is a condense finding on that span: apply its condensedText exactly as given.

  3. If satisfiable is false, report minAchievable and stop.

What a plan can contain:

  • Delete a block with a stale reference or a repeated block. Never offered for a block that holds a rule word (must, never, always, do not, don't).

  • Condense a prose paragraph over 300 tokens. The replacement is built from whole sentences: the leading ones that fit --max-condense-chars, plus every sentence with a rule word. Lists, tables, quotes, and code are left alone. Under a preserve heading (Never, Constraints, Must, Rules) or a <!-- ctxcap:preserve --> marker, only repeated sentences are dropped.

Verification is a guardrail, not a proof. It checks that planned text was removed, that applied files did not drift, that preserve text remains, and that every rule sentence of a condensed paragraph is still present. It cannot tell whether what remains still means the same thing, or whether an unmarked instruction was important. Review the diff before you commit it.

The plan JSON includes verifyCommand, the exact pinned command that checks that plan, for example npx ctxcap@1.6.0 --verify 6b8e55. It is also printed on its own line on stderr. While no agent in the repository is wired, the plan carries an initHint that points at ctxcap init.

Plans are saved to .ctxcap/plans/<planId>.json and expire after 24 hours; after that --verify returns PLAN_EXPIRED. Keep them out of git: ctxcap init sets that up, or add .ctxcap/plans/ to your own .gitignore. Run --apply on a clean tree, and do not run it in CI.

examples/case-study/ holds a run you can reproduce: two context files go from 1,504 tokens to 228 at budget 400, both rules survive, and verification reports no violations. The directory has the report before and after, the plan, the applied diff, and the verify output. The context files are committed in their before state:

npx ctxcap --plan --budget 400 --apply --root examples/case-study
npx ctxcap --verify 6b8e55 --root examples/case-study
git checkout examples/case-study    # restore

Use it from a coding agent

Agents do not go looking for tools. They use what is installed, and what the repository tells them to run. ctxcap init sets all of this up for a repository in one step. To set up one piece by hand, or for yourself rather than for a repository, there are three ways.

As a skill. The agent loads it only when you ask about context size or stale references, and it runs the CLI with npx. Nothing is added to the context window until then.

# Claude Code
claude plugin install ctxcap --marketplace Naeha-S/ctxcap

# Claude Code, Cursor, Codex, and other agents that read SKILL.md
npx skills add Naeha-S/ctxcap

Then ask "how many tokens do my context files cost?" or "is AGENTS.md stale?".

As an MCP server. The same measure, plan, and verify steps as tools. The four tool definitions cost about 500 tokens in every session, which is why ctxcap init leaves the server out unless you pass --agents claude,mcp:

Add to Cursor

{
  "mcpServers": {
    "ctxcap": {
      "command": "npx",
      "args": ["-y", "ctxcap-mcp"]
    }
  }
}

For Claude Code: claude mcp add ctxcap -- npx -y ctxcap-mcp. Codex setup is in the MCP package guide.

Tool

Description

measure_context

The JSON report for the current working directory

context_budget_plan

A ranked plan with safety classes and preserve spans

context_budget_verify

Missed edits and preserve violations after a plan is applied

trim_to_budget

Deprecated alias for context_budget_plan; never applies

The server speaks stdio, reads the client's working directory, and makes no network calls. It never edits files: the agent applies the plan and then calls verify. Plans are saved under .ctxcap/plans/, so verify also works in a later session. It is tested with the official MCP SDK client. Use ctxcap-mcp 0.1.7 or newer; earlier versions do not connect.

As a line in AGENTS.md. Agents read this file at the start of a session, so one line is enough:

- Before editing AGENTS.md or CLAUDE.md, run `npx -y ctxcap why` and fix stale references before trimming.

CLI

Command

Effect

ctxcap

Measure the context files and print the table

ctxcap init

Wire ctxcap into the repository's coding agents. See Wire it up

ctxcap init --remove

Undo that

ctxcap doctor

Report whether the wiring is complete and current

ctxcap why

Diagnose ranked repository context, skills, MCP names, stale references, and risky content

ctxcap hook post-edit|pre-compact|stop

What the Claude Code hooks run. Not meant to be run by hand

ctxcap roast

One deterministic line about the file. --json, --stale

Flag

Effect

--json

Machine-readable JSON report on stdout

--sarif

SARIF 2.1.0 on stdout

--suggest

Include compression suggestions

--compare

Add this file's percentile in the Context Budget Index

--stale

Find dead paths, commands, and references

--stale-glob

Include globs that match no files

--stale-fix

Print a deletion diff; never writes files

--fail-on increase|budget|stale|never

When to exit 1 (default: never)

--baseline <ref>

Read the baseline from a git ref (CI uses the merge base)

--update-baseline

Write ctxcap-baseline.json and exit

--badge

Write .ctxcap/badge.json for a shields.io badge and exit

--config <path>

Config file path (default: .ctxcap.json)

--root <path>

Working directory (default: .)

--plan

Print a ranked edit plan

--apply

Apply the generated plan

--verify <planId>

Verify a saved plan

--budget <n>

Target budget for --plan

--budget-class <class>=<n>

Budget a conditional or manual load class

--strict-preserve

Exclude every preserve span from plans

--max-condense-chars <n>

Maximum replacement length (default: 320)

--min-tokens <n>

Minimum size of a plan finding (default: 20)

Exit codes: 0 clean, 1 breach under --fail-on, 2 internal error.

Config

.ctxcap.json, all fields optional:

{
  "include": ["AGENTS.md", "prompts/**", ".cursor/rules/**"],
  "ignore": ["prompts/archive/**"],
  "budgets": {
    "total": 40000,
    "AGENTS.md": 500,
    "prompts/system.md": 8000
  },
  "preserveHeadings": ["Never", "Constraints", "Must", "Rules"],
  "failOn": "budget"
}

--fail-on budget uses the budgets in this file; --budget on the command line only sets the target for --plan.

Each file gets a load class, and reports total them in totalByClass:

Class

Files

always

CLAUDE.md

startup

AGENTS.md

conditional

.cursor/rules/**, AGENTS.md in subdirectories

manual

Everything else

budgets.total counts always and startup files only. total in the report is the sum of all classes.

Report format

{
  "schema": "ctxcap/v1",
  "approximate": true,
  "tokenizer": "gpt-tokenizer@3.0.1",
  "total": 371,
  "totalByClass": { "startup": 287, "manual": 84 },
  "totalBudget": 1200,
  "delta": 0,
  "over": false,
  "baselineFound": true,
  "acknowledged": false,
  "files": [
    { "path": "AGENTS.md", "tokens": 287, "delta": 0, "budget": null, "loadClass": "startup" },
    { "path": "llms.txt", "tokens": 84, "delta": 0, "budget": null, "loadClass": "manual" }
  ],
  "suggestions": [],
  "findings": [],
  "reclaimableTotal": 0
}

Schemas: schema/report.schema.json for reports and schema/plan.schema.json for plans (ctxcap/plan/v2).

Accuracy

Token counts use OpenAI's o200k_base encoding. They match GPT-4o-family models and are an estimate for everything else: Claude and Gemini tokenize differently, and the gap has not been measured here. Every report carries "approximate": true and the tokenizer ID. Compare deltas, not absolutes. CRLF line endings are counted as LF, so a Windows checkout gets the same numbers as CI on the same commit. confidence on a plan finding is a fixed value per finding kind, not a measurement.

What it does not do

It does not decide which instructions are worth their tokens. A useful review question is whether an agent could infer the line from the repository, its build scripts, or its linters; if so, it may not need always-loaded space.

How this differs from tokenlint

tokenlint hooks your editor and reminds you per turn about wasteful habits. ctxcap works at the repository: it measures context files against a committed baseline and reports the delta on every pull request. Use the first for nudges while you type and this one for a gate in CI and review.

When it is wrong

ctxcap reads your files with fixed rules, so it will misread some of them: a path flagged as dead that exists, or a plan that would cut a rule you need. Report the misread with the command, what it printed, and the lines it was reading.

Packages

Package

Description

ctxcap

CLI, GitHub Action, and MCP server

ctxcap-mcp

npx-runnable MCP server; depends on ctxcap

The MCP server is listed in the official MCP Registry as io.github.Naeha-S/ctxcap.

License

MIT.

Available Tools

4 tools
context_budget_planA

Use before appending more than ~50 lines or when CLAUDE.md, AGENTS.md, Cursor rules, or prompts exceed budget. Input: required integer budget plus optional maxFindings, includeDiff, and apply. Returns a deterministic ranked plan with file line ranges, tokensFreed, confidence, safety actions, preserve spans, and satisfiable/minAchievable stop state. Apply entries in order by startLine/endLine, never rewrite a file, never cut preserve spans except by applying the condensedText of a condense entry exactly as given, stop when satisfiable is false, and call context_budget_verify after edits. The plan is saved under .ctxcap/plans for 24 hours.

Inputs: budget (required), apply, includeDiff, maxFindings.

context_budget_verifyA

Use after applying a context-budget plan to catch missed edits, manual drift, or preserve-span violations. Input: the planId returned by context_budget_plan. Returns applied and missed finding IDs, violations with file and line ranges, remaining tokens, and satisfied. Do not consider the budget met until satisfied is true.

Inputs: planId (required).

measure_contextA

Use when CLAUDE.md, AGENTS.md, Cursor rules, or prompts may be too large or consuming too much context. Input: optional suggest, stale, and staleGlob booleans. Returns JSON token totals, per-file counts, baseline deltas, budget status, suggestions, and optional stale-reference findings. Runs offline and only reads the current working directory.

Inputs: stale, suggest, staleGlob.

trim_to_budgetA

Deprecated alias for context_budget_plan for clients using the old name. Input: required integer budget and optional maxFindings. Returns the same ranked, safety-classified plan with apply false; it never edits context files. Follow line ranges, preserve spans, satisfiable stop rules, and verification guidance from context_budget_plan.

Inputs: budget (required), maxFindings.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.7/5.0

    Scored across 4 tools

    Disambiguation3/5

    measure_context (reporting) and context_budget_verify (post-edit checking) are clearly distinct, but trim_to_budget is an explicit duplicate of context_budget_plan, forcing an agent to decide between two names for the same operation. The descriptions clarify the difference, but the deliberate alias overlap keeps boundaries fuzzy.

    Naming Consistency3/5

    Names mix conventions: measure_context is verb_noun, trim_to_budget is verb_to_noun, while context_budget_plan/context_budget_verify use a noun-prefix style with the action last. The context_budget_ pair is internally consistent, but the set overall is readable yet not uniform.

    Tool Count4/5

    Four tools is small but well-scoped for a context-budget domain: one measurement, one planner, one verifier, plus a compatibility alias. The deprecated alias is the only tool that does not earn an independent slot.

    Completeness4/5

    The core lifecycle (measure → plan → verify) is covered, including stale-reference detection and safety/preserve-span semantics. Minor gaps exist: no way to list or inspect saved plans in .ctxcap/plans, and no standalone apply/cleanup operation beyond the plan's apply flag.

    Maintenance

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers