ctxcap
Adds a GitHub Actions workflow that compares context-file token counts against a committed baseline, comments the token delta on pull requests, and can fail CI when a configured budget is exceeded.
Generates a Shields.io endpoint badge JSON and README badge line that display the repository's context token count.
ctxcap
AGENTS.md, CLAUDE.md, and prompt files are loaded into agent sessions over
and over, and they only grow. ctxcap counts what they cost in tokens, flags
pull requests that grow them, and finds the references in them that point at
files and scripts that no longer exist.
It runs offline: no API key, network call, telemetry, or config. Node 20 or newer.
npx ctxcap --staleTOKENS DELTA FILE
45 0 AGENTS.md
---
total 45 (0)
approximate count (gpt-tokenizer@3.0.1)
stale findings 2 (reclaimable 21 tokens)
stale-path AGENTS.md:6 src/auth/session.js
dead-command AGENTS.md:7 npm run lintWhat it does
Measures. Token counts per file and in total, as text, JSON, or SARIF.
Gates pull requests. A GitHub Action compares against a committed baseline, comments the delta on the pull request, and fails only when you ask it to.
Finds stale references. Paths and
npm runscripts named in a context file that no longer resolve in the repository.Plans a trim. A ranked list of edits to get under a budget, with a verify step. This is the newest part; review its diffs before you accept them. See Trim to a budget.
By default it scans CLAUDE.md, AGENTS.md, .github/copilot-instructions.md,
prompts/**, *.prompt, and .cursor/rules/**.
Related MCP server: parecode
Quick start
Run it in the repository you want to inspect. Nothing is installed or written:
npx ctxcap # token table
npx ctxcap --json # the same as JSON
npx ctxcap --stale # add dead paths and scriptsTo 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 themAgents 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 |
| Files | Cost in the context window |
Claude Code |
|
| 84 tokens per session for the skill's name and description, 323 once the skill loads |
Cursor |
|
| 140 tokens when a |
Codex |
| A 2-line block in | 51 tokens per session |
Copilot |
| A 3-line block in | 101 tokens per session |
CI |
|
| None |
README badge |
|
| None |
MCP server, opt-in |
| A server entry in | 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 two 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.
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.
Each hook starts npx, which takes about a second once the package is cached.
That second is added to every edit Claude Code makes.
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 |
|
| After every Edit, Write, or MultiEdit in Claude Code |
|
| Each time Claude Code finishes responding |
|
| When the agent follows the skill |
| ||
| ||
| ||
| ||
|
| When Cursor follows the rule |
| ||
| ||
|
| When the agent follows the instruction |
|
| When Copilot follows the instruction |
| ||
|
| On every pull request |
| ||
|
| When the client starts, with |
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.5.1, and the action as
Naeha-S/ctxcap@v1.
Flag | Effect |
| Apply the diff. Without it, nothing is written |
| Print the diff and exit 0 |
| Comma-separated subset of |
| Undo what |
| Overwrite a file or entry at a |
| Write |
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
_ctxcapkey records the version that wrote the entries.Files that
initcreates whole (the skill, the Cursor rule, the workflow,.ctxcap/.gitignore) carry actxcap:managedmarker. A file at one of those paths without the marker is yours, andinitleaves it alone.A
.ctxcap/line in your.gitignorewould hide the badge, and git does not read a.gitignoreinside an ignored directory.initreplaces that line with.ctxcap/plans/and.ctxcap/*.stampbetween# ctxcap:beginand# ctxcap:end, and keeps the original line inside the block.--removeputs it back exactly. A.gitignorewithout that line is not touched..ctxcap/badge.jsoncannot carry a marker, because shields.io rejects keys it does not know.initwrites.ctxcap/badge.ownedbeside it instead.--removedeletes the badge only while that file is there, so a badge you made yourself withctxcap --badgeis 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 doctorclaude partially wired: missing .claude/skills/ctxcap/SKILL.md
cursor not wired
codex stale pin: AGENTS.md has 1.5.0, current is 1.5.1
copilot wired
ci wired: by .github/workflows/lint.yml, not written by ctxcap init
badge wired
mcp not wireddoctor 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 --badgewrites .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.5.1 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.md287
+78
llms.txt84
-70
fail-on decides when the check goes red:
Value | Fails when |
| Never; the action only reports |
| The total grew since the merge base and the baseline was not updated |
| A budget in |
| The stale pass has findings (needs |
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.
Inputs:
Input | Default | Description |
|
|
|
|
| Path to config file |
|
| Root directory to lint |
|
| Post the sticky pull request comment |
|
| Upload SARIF to code scanning |
|
| Run the stale-reference pass |
|
| 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. 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 nothingThe 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.jsis checked;origin/main,feat/x, and@scope/pkgare not);without a slash, the name must end in a known file extension and exist nowhere in the repository (
gone.config.tsis checked;console.logand1.2.3are not);npm run <script>must be a script in somepackage.jsonin the repository.
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.
What real repositories spend
Measured with ctxcap --stale 1.4.0 on 15 November 2026, at the commit shown:
Repository | Commit | Context files | Tokens | Stale findings |
|
|
| 4,685 | 0 |
|
|
| 4,658 | 0 |
|
|
| 4,025 | 0 |
|
|
| 2,223 | 0 |
|
|
| 823 | 0 |
|
|
| 296 | 0 |
These repositories are how the stale pass was tuned. 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 rules above are what
was left after removing every false one.
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 landedThree rules for the agent:
Splice by
startLine/endLine. Never rewrite a file from scratch.Never cut a span listed in
preserve. The one exception is acondensefinding on that span: apply itscondensedTextexactly as given.If
satisfiableis false, reportminAchievableand 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.5.1 --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 # restoreUse 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/ctxcapThen 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:
{
"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 |
| The JSON report for the current working directory |
| A ranked plan with safety classes and preserve spans |
| Missed edits and preserve violations after a plan is applied |
| Deprecated alias for |
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 --stale --json` and keep the total from growing.CLI
Command | Effect |
| Measure the context files and print the table |
| Wire |
| Undo that |
| Report whether the wiring is complete and current |
| What the Claude Code hooks run. Not meant to be run by hand |
Flag | Effect |
| Machine-readable JSON report on stdout |
| SARIF 2.1.0 on stdout |
| Include compression suggestions |
| Find dead paths, commands, and references |
| Include globs that match no files |
| Print a deletion diff; never writes files |
| When to exit 1 (default: |
| Read the baseline from a git ref (CI uses the merge base) |
| Write |
| Write |
| Config file path (default: |
| Working directory (default: |
| Print a ranked edit plan |
| Apply the generated plan |
| Verify a saved plan |
| Target budget for |
| Budget a conditional or manual load class |
| Exclude every preserve span from plans |
| Maximum replacement length (default: 320) |
| 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 |
|
|
|
|
|
|
| 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 |
CLI, GitHub Action, and MCP server | |
|
The MCP server is listed in the
official MCP Registry as
io.github.Naeha-S/ctxcap.
License
MIT.
Available Tools
4 toolscontext_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
Scored across 4 tools
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.
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.
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.
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
Related MCP Connectors
Deterministic memory & code intelligence MCP for 15 IDEs (100% LongMemEval in 12.9ms, 0 LLM tokens).
Codebase knowledge graph — architectural awareness for AI coding agents via MCP
Persistent memory and cross-session learning for AI coding assistants (hosted remote MCP).
Codebase intelligence for agents: 152 structured artifacts across 21 programs, one call.
Related MCP Servers
- AlicenseBqualityDmaintenanceA lightweight MCP server that enables AI agents to perform deep codebase analysis by leveraging Gemini's massive context window for cross-file analysis and intelligent file selection.428MIT
- AlicenseAqualityCmaintenanceAn MCP server giving coding agents context-window-aware code search and safe, atomic multi-file edits — built to cut token usage on large codebases without sacrificing correctness.359 npm5MIT
- AlicenseNot gradedqualityCmaintenanceMCP server that reduces AI agent token usage by up to 90% through intelligent context compression. Enables efficient code exploration, multi-file refactoring, and debugging by providing tools for smart reading, searching, and managing code context.4MIT
- FlicenseNot gradedqualityDmaintenanceAn MCP server that cuts AI coding-agent token usage by 60–80% via framework-aware context optimization.-