Listed from the MCP registry; nobody on Odel publishes it.

MCP server: One MCP server.

ctxcap

@naeha-sRun by its publisher: served from their own domain, namespace checked by the registry.MCP server · External

Offline context-budget MCP server for AI coding agents.

Version controlv0.1.10MITJavaScript
Freeno charge per call

Runs on your machine from its package; the steps are below.

What it does

  1. Reads
  2. Writes
  3. High impact

At most: only reads or looks up information.

What it costs

Free

Odel charges nothing per call. The publisher may charge for its own service.

Runs locally over stdio

This server isn't hosted — your MCP client launches it from a package registry. Use one of the commands below, or drop the config into your client (e.g. Claude Desktop).

npmctxcap-mcpv0.1.10

Run

npx -y ctxcap-mcp

MCP client config

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

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.

bash
npx ctxcap why
text
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.

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):

bash
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:

bash
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

bash
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--agentsFilesCost in the context window
Claude Codeclaude.claude/skills/ctxcap/SKILL.md, three hooks in .claude/settings.json, .ctxcap/.gitignore70 tokens per session for the skill's name and description, 362 once the skill loads
Cursorcursor.cursor/rules/ctxcap.mdc140 tokens when a CLAUDE.md or AGENTS.md is in the conversation
CodexcodexA 2-line block in AGENTS.md51 tokens per session
CopilotcopilotA 3-line block in .github/copilot-instructions.md101 tokens per session
CIci.github/workflows/ctxcap.ymlNone
README badgebadge.ctxcap/badge.json, one line under the README titleNone
MCP server, opt-inmcpA server entry in .mcp.json and in .cursor/mcp.jsonAbout 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 toCommandRuns
.claude/settings.jsonnpx -y ctxcap@1.6.0 hook post-editAfter every Edit, Write, or MultiEdit in Claude Code
.claude/settings.jsonnpx -y ctxcap@1.6.0 hook pre-compactBefore Claude Code compacts context
.claude/settings.jsonnpx -y ctxcap@1.6.0 hook stopEach time Claude Code finishes responding
.claude/skills/ctxcap/SKILL.mdnpx ctxcap@1.6.0 whyWhen 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.mdcnpx ctxcap@1.6.0 whyWhen Cursor follows the rule
npx ctxcap@1.6.0 --plan --budget <n>
npx ctxcap@1.6.0 --verify <planId>
AGENTS.mdnpx ctxcap@1.6.0 whyWhen the agent follows the instruction
.github/copilot-instructions.mdnpx ctxcap@1.6.0 whyWhen Copilot follows the instruction
npx ctxcap@1.6.0 --plan --budget <n>
.github/workflows/ctxcap.ymlactions/checkout@v4On every pull request
Naeha-S/ctxcap@v1.6.0
.mcp.json, .cursor/mcp.jsonnpx -y -p ctxcap@1.6.0 ctxcap-mcpWhen 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.

FlagEffect
--yesApply the diff. Without it, nothing is written
--printPrint the diff and exit 0
--agents <list>Comma-separated subset of claude,cursor,codex,copilot,ci,badge,mcp (default: all but mcp)
--removeUndo what init wrote, for every agent unless --agents is given
--forceOverwrite a file or entry at a ctxcap path that init did not write
--no-pinWrite 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.
bash
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

bash
npx ctxcap doctor
text
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

bash
npx ctxcap --badge

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

json
{"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

yaml
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

FileTokensDelta
AGENTS.md287+78
llms.txt84-70

fail-on decides when the check goes red:

ValueFails when
never (default)Never; the action only reports
increaseThe total grew since the merge base and the baseline was not updated
budgetA budget in .ctxcap.json is exceeded
staleThe 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:

InputDefaultDescription
fail-onneverincrease | budget | stale | never
config.ctxcap.jsonPath to config file
path.Root directory to lint
commenttruePost the sticky pull request comment
upload-sariftrueUpload SARIF to code scanning
stalefalseRun the stale-reference pass
stale-globfalseInclude 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

bash
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:

bash
npx ctxcap --compare
text
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:

RepositoryContext filesTokensStale findings
langchain-ai/langchainAGENTS.md4,6850
pydantic/pydantic-aiAGENTS.md4,6580
anomalyco/opencodeAGENTS.md4,0250
n8n-io/n8nAGENTS.md, CLAUDE.md6,2540
affaan-m/ECC42 files13,2860
ultraworkers/claw-code11 files9,0080
modelcontextprotocol/python-sdkAGENTS.md, CLAUDE.md2,2230
astral-sh/uvAGENTS.md8230
modelcontextprotocol/typescript-sdkCLAUDE.md2960

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.

ServerToolsTokens
Sentry7346,512
Firecrawl3217,764
Notion2417,163
Chrome DevTools336,753
Playwright253,936
GitHub263,548
ctxcap's own server4507

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.

MonthRepositoriesFoundConfirmedExcluded after reading
2026-1125 selected (23 scanned)523
  • 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

bash
npx ctxcap roast
text
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.

bash
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:

bash
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.

bash
# 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

json
{
  "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.

ToolDescription
measure_contextThe JSON report for the current working directory
context_budget_planA ranked plan with safety classes and preserve spans
context_budget_verifyMissed edits and preserve violations after a plan is applied
trim_to_budgetDeprecated 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:

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

CLI

CommandEffect
ctxcapMeasure the context files and print the table
ctxcap initWire ctxcap into the repository's coding agents. See Wire it up
ctxcap init --removeUndo that
ctxcap doctorReport whether the wiring is complete and current
ctxcap whyDiagnose ranked repository context, skills, MCP names, stale references, and risky content
ctxcap hook post-edit|pre-compact|stopWhat the Claude Code hooks run. Not meant to be run by hand
ctxcap roastOne deterministic line about the file. --json, --stale
FlagEffect
--jsonMachine-readable JSON report on stdout
--sarifSARIF 2.1.0 on stdout
--suggestInclude compression suggestions
--compareAdd this file's percentile in the Context Budget Index
--staleFind dead paths, commands, and references
--stale-globInclude globs that match no files
--stale-fixPrint a deletion diff; never writes files
--fail-on increase|budget|stale|neverWhen to exit 1 (default: never)
--baseline <ref>Read the baseline from a git ref (CI uses the merge base)
--update-baselineWrite ctxcap-baseline.json and exit
--badgeWrite .ctxcap/badge.json for a shields.io badge and exit
--config <path>Config file path (default: .ctxcap.json)
--root <path>Working directory (default: .)
--planPrint a ranked edit plan
--applyApply 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-preserveExclude 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:

json
{
  "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:

ClassFiles
alwaysCLAUDE.md
startupAGENTS.md
conditional.cursor/rules/**, AGENTS.md in subdirectories
manualEverything else

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

Report format

json
{
  "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

PackageDescription
ctxcapCLI, GitHub Action, and MCP server
ctxcap-mcpnpx-runnable MCP server; depends on ctxcap

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

License

MIT.

Similar modules

Browse Version control