cag-mcp
# cag-mcp
An MCP server, shipped as a Claude Code plugin, that answers questions about a project's documentation by
**Cache-Augmented Generation** (CAG). The whole doc set is loaded into the context of a cheap model with a large
window and a long-lived prompt cache; every question is asked against that same cached prefix. The model replies
briefly and points at files and lines; the server checks every citation against the files on disk; the calling
agent then reads those lines itself.
## Why not vector search
With CAG the *model* does the search, over all of the docs at once. Embeddings are tuned to match a question to a
similarly worded question, while docs hold answers, often worded differently and spread over several files. A
whole-corpus read used to be too expensive per question; with a ~1M-token window and a prompt cache that lives for
hours, the doc set is written to the cache once and every later question reads it at the cached-input price.
Only OpenAI is implemented. Anthropic models are out of scope for this version because their cache lives one hour
at most.
## How it works
```
files of the checkout snapshot (rendered once, provider prompt cache
selected by include/exclude ─▶ stored on disk, never re-rendered) ─▶ (ttl 12h or 30m, minimum)
│ │
later edits ─▶ overlay (one cumulative │ │
diff against the snapshot)│ │
▼ ▼
request = [instructions + snapshot] [overlay] [question]
└──── cached prefix ───┘
│
▼
structured answer {answer, answered, citations: [{path, quote}]}
│
▼
each quote is searched in the current file on disk (whitespace-normalized)
found ─▶ path:start-end not found ─▶ marked unverified, no lines
```
The prefix is the fixed instructions followed by every selected file, sorted by path, each wrapped in
`<file path="...">`. It holds nothing that changes between requests (no timestamps, no absolute paths), so it is
byte-identical across runs and machines and the provider can serve it from cache. Nothing from one question is
carried into the next.
## Installation as a Claude Code plugin
Requirements: [uv](https://docs.astral.sh/uv/) on `PATH`, Python 3.12 or newer (uv can install it), and an OpenAI
API key in `CAG_MCP_API_KEY` or `OPENAI_API_KEY` (or `api_key` in the user config file).
The repository is the plugin: `.claude-plugin/plugin.json` is its manifest, `.mcp.json` starts the server with
`uv run --frozen --project ${CLAUDE_PLUGIN_ROOT} cag-mcp`, and `skills/` holds the two skills. For a session:
```sh
git clone <this repository> ~/src/cag-mcp
claude --plugin-dir ~/src/cag-mcp
```
To install it permanently, list it in a local marketplace: a directory with its own
`.claude-plugin/marketplace.json` (a `name`, an `owner` and a `plugins` entry `{"name": "cag-mcp", "source":
"./cag-mcp"}` with the path relative to that directory), then `claude plugin marketplace add <that directory>` and
`claude plugin install cag-mcp@<marketplace name>`. This repository ships only the plugin manifest, not a
marketplace file; see [Create a marketplace](https://code.claude.com/docs/en/plugin-marketplaces.md). The plugin is not
published to any marketplace.
One server serves every project: there is no per-project install. The project is `CLAUDE_PROJECT_DIR` when set,
else the working directory, raised to the git top level when inside a repository. Claude Code exports
`CLAUDE_PROJECT_DIR` (with `CLAUDE_PLUGIN_ROOT` and `CLAUDE_PLUGIN_DATA`) to the stdio MCP servers of a plugin;
its documentation does not specify the server's working directory, so cag-mcp relies on `CLAUDE_PROJECT_DIR`.
A project without `.cag-mcp.toml` gets a short hint from every tool naming the file and the `init` skill; the
server does not fail.
The server speaks MCP over stdio, including protocol revision 2026-07-28, through the official `mcp` SDK (2.x).
## Configuration
Precedence, lowest to highest:
1. built-in defaults;
2. the user file `$XDG_CONFIG_HOME/cag-mcp/config.toml` (default `~/.config/cag-mcp/config.toml`);
3. the project file `.cag-mcp.toml` at the project root;
4. environment variables `CAG_MCP_<KEY>` for every scalar setting.
Inside the project file, a `[corpus.<name>]` table overrides the project's top-level keys for that corpus; the
environment still wins over both. The configuration is read on every tool call, so edits apply without a restart.
Unknown keys and values of the wrong type are errors that name the key.
**Trust rule.** `provider`, `api_key` and `url` are read only from the user file and the environment. A project
file (or a corpus table) that sets one of them is an error naming the offending key: otherwise a cloned repository
could redirect the docs and your key to its own endpoint.
| Key | Default | Environment variable | Meaning |
|---|---|---|---|
| `provider` | `openai` | `CAG_MCP_PROVIDER` | only `openai` is implemented; `fake` is an offline test double that quotes the best-matching line of the snapshot as the overlay changes it (diffs applied, deleted files dropped) |
| `api_key` | none | `CAG_MCP_API_KEY` | API key. Order: `CAG_MCP_API_KEY`, then the user file, then `OPENAI_API_KEY` |
| `url` | `https://api.openai.com/v1` | `CAG_MCP_URL` | API base URL |
| `model` | `gpt-6-luna` | `CAG_MCP_MODEL` | answering model |
| `cache_ttl` | `12h` | `CAG_MCP_CACHE_TTL` | `30m` or `12h`, sent as `prompt_cache_options.ttl` |
| `cache_read_extends_ttl` | `false` | `CAG_MCP_CACHE_READ_EXTENDS_TTL` | how the ledger predicts expiry: from the last write only, or from the later of the last write and the last read. The research harness is to decide the real value |
| `reasoning_effort` | lowest the model accepts | `CAG_MCP_REASONING_EFFORT` | unset: `none` for `gpt-6-luna` and `gpt-6.1-terra`; for other models no effort is sent |
| `respect_gitignore` | `true` | `CAG_MCP_RESPECT_GITIGNORE` | inside git, select tracked files only |
| `max_input_tokens` | `900000` | `CAG_MCP_MAX_INPUT_TOKENS` | a larger corpus (or request) is an error |
| `long_prompt_tokens` | `272000` | `CAG_MCP_LONG_PROMPT_TOKENS` | a larger corpus is a warning in `status` |
| `state_dir` | `$XDG_CACHE_HOME/cag-mcp` (default `~/.cache/cag-mcp`) | `CAG_MCP_STATE_DIR` | where snapshots and ledgers live |
| `overlay.enabled` | `true` | `CAG_MCP_OVERLAY_ENABLED` | `false`: any change rebuilds the snapshot |
| `overlay.max_percent` | `10` | `CAG_MCP_OVERLAY_MAX_PERCENT` | overlay size as % of the snapshot; `0` disables this limit |
| `overlay.max_tokens` | `0` | `CAG_MCP_OVERLAY_MAX_TOKENS` | absolute overlay limit in tokens; `0` disables this limit |
| `overlay.whole_file_percent` | `50` | `CAG_MCP_OVERLAY_WHOLE_FILE_PERCENT` | a changed file whose diff exceeds this % of the new file is sent whole |
| `corpus.<name>.include` | required | none | list of glob masks |
| `corpus.<name>.exclude` | `[]` | none | list of glob masks |
| `prices.<model>.input`, `.cached_input`, `.output` | built-in for two models | none | USD per 1M tokens for the cost estimate; merged per model and per key: built-in < user file < project file < corpus table |
Booleans in the environment accept `true/false`, `1/0`, `yes/no`, `on/off`; an empty variable counts as unset.
`include`, `exclude` and `prices` are tables or lists, not scalars, so they have no environment variable. Corpus
tables belong in the project file only; the user file may set every other key, including `prices`. A price table
may set only some of the three values: a project file that sets `prices.m.output` keeps the user file's
`prices.m.input`. A corpus table may carry its own `prices` as well (`[corpus.<name>.prices.<model>]`).
Masks match paths relative to the project root with `/` separators: `**` crosses directories (`docs/**`,
`**/*.md`), `*` and `?` do not, `[abc]` and `[!abc]` are character classes. A file matching any `exclude` mask is
left out.
A project needs at least one corpus; the conventional name is `default`, which every tool uses unless told
otherwise. A corpus name is one path component of the state directory: letters, digits, `_`, `.` and `-`,
starting with a letter or digit, at most 64 characters; any other name is an error. A corpus table may override
any non-credential key:
```toml
# .cag-mcp.toml
[corpus.default]
include = ["README.md", "docs/**/*.md"]
exclude = ["docs/generated/**"]
[corpus.api]
include = ["api/**/*.md"]
model = "gpt-6.1-terra"
[corpus.api.overlay]
max_percent = 5
```
```toml
# ~/.config/cag-mcp/config.toml
api_key = "sk-..."
cache_ttl = "12h"
# Prices of a model without built-in ones, in USD per 1M tokens, copied from its pricing page:
# [prices."<model>"]
# input = ...
# cached_input = ...
# output = ...
```
Built-in prices (USD per 1M tokens, from the model pages, checked 2026-11-28):
| Model | input | cached input | output |
|---|---|---|---|
| `gpt-6-luna` | 0.10 | 0.01 | 0.50 |
| `gpt-6.1-terra` | 1.00 | 0.05 | 5.00 |
Cache writes are billed at 1.25x the input price for the `30m` tier and 2.5x for `12h`, instead of the ordinary
input price; uncached input is `input - cached - written`. A request with more than 272,000 input tokens is billed
at 2x the input and cache rates and 1.5x the output rate for the whole request (both model pages). Every request is
priced on its own, and the ledger keeps the tokens of such long requests apart, so the cumulative estimate in
`status` keeps both tiers. For other models `status` reports tokens only, unless `prices` gives all three values.
Other environment variables: `CLAUDE_PROJECT_DIR` (the project), `XDG_CONFIG_HOME` (the user file),
`XDG_CACHE_HOME` (the default `state_dir`), `OPENAI_API_KEY` (fallback key). The research and benchmark harnesses
read `CAG_MCP_API_KEY` / `OPENAI_API_KEY` and `CAG_MCP_URL` only.
## Tools
- **`ask(question, corpus = "default")`**: one Responses API call with a JSON-schema structured output (a brief
answer, whether the docs answer the question at all, citations as `{path, quote}`). Each quote is resolved in the
*current* file on disk by a whitespace-normalized match and returned as `path:start-end`: the cited files of the
corpus are read again after the provider has replied, so an edit made while the question was in flight is seen.
A quote that cannot be found, a path outside the corpus, or a file that is gone, not UTF-8 or reached through a
symlink is returned marked unverified with the quote and no lines; it is never dropped and never given invented
lines. In the prompt every path sits in a `path="..."` attribute with `&` written as `&` and `"` as `"`;
a cited path is read back by reversing exactly that, so `R&D.md` is the file `R&D.md` and
`R&amp;D.md` the file `R&D.md`, and only then looked up among the selected files.
- **`status(corpus?)`**: for the named corpus, or, with no argument, for every corpus of the project file in name
order: the file count and estimated tokens, skipped (non-UTF-8) files, the snapshot
a question would use now with its age and predicted cache expiry, the overlay size against both limits, the last
request's cached and written tokens, cumulative tokens by kind over the local snapshots, an estimated cost, the
counts of cache-prediction mismatches, and warnings (over `long_prompt_tokens` or `max_input_tokens`). A snapshot
whose cache was never written (just after `rebuild`) is shown as "provider cache not written yet".
- **`rebuild(corpus = "default")`**: build a new snapshot from this checkout now. The next question from a checkout
that matches it exactly uses it (and pays its cache write); after that it is chosen like any other snapshot.
Provider and configuration errors come back as readable tool errors. They never contain the API key: messages are
scrubbed of the configured keys and of anything shaped like `sk-...`.
## Skills
Two skills, one copy of each, in `skills/`:
- `init`: create `.cag-mcp.toml` for a project: propose masks, show the estimated token count, explain the limits.
- `ask`: when to ask cag-mcp instead of searching files, how to phrase a question, how to treat an unverified
citation.
**They are served as ordinary Claude Code plugin skills, not over MCP.** The installed `mcp` SDK (2.3.0) does not
ship the MCP Skills extension (`io.modelcontextprotocol/skills`, SEP-2640), so cag-mcp uses the fallback: Claude
Code picks the skills up from the plugin's `skills/` directory. For other MCP clients, the server also lists the
same two files as plain resources (`skill://init/SKILL.md`, `skill://ask/SKILL.md`); it does not declare the
Skills extension and does not implement `skills/list` or `skills/get`.
## Snapshots, the overlay and worktrees
State lives in `<state_dir>/<repo-id>/<corpus>/<snapshot-id>/`: `prefix.txt` (the rendered prefix, sent byte for
byte), `manifest.json` (paths, content hashes and byte ranges in the prefix, the model) and `ledger.json`.
- `repo-id` is derived from the git common directory, so **all worktrees of a repository share snapshots**.
Outside git it is derived from the project root.
- `snapshot-id` is a hash of the prefix bytes, the model and the instructions: identical content always means the
same snapshot, whichever checkout built it.
- **Selection.** Inside git with `respect_gitignore = true`: tracked files that match `include` and not `exclude`,
read from the working tree (a tracked file deleted from disk is treated as deleted). With
`respect_gitignore = false`, or outside git: files on disk by the same masks, skipping `.git` (a directory, or
the `.git` pointer file of a worktree). The server's own state (`<state_dir>/<repo-id>/` for the resolved
`state_dir` of every corpus in the project file) is never selected by any corpus, even when a `state_dir` lies
inside the project and a mask such as `**/*` would match it. A file that is a
symlink, or that lies under a symlinked directory, is skipped: it could lead outside the project. Files that are not valid UTF-8 are skipped and listed in `status`, also when nothing else is selected.
- **The overlay** is one cumulative difference between a snapshot and the files of the asking checkout, recomputed
on every question from the manifest; there is no watcher. Per changed file a unified diff, or the whole new file
when the diff is larger than `overlay.whole_file_percent` of it; new files whole; deleted files named as deleted.
It is sent after the cached prefix, so the prefix stays cacheable. A diff keeps line boundaries: an unterminated
last line is followed by GNU diff's `\ No newline at end of file` marker.
- **The cache boundary.** Requests use explicit caching (`prompt_cache_options.mode = "explicit"`) with one
`prompt_cache_breakpoint` on the content block that holds the instructions and the snapshot. The overlay and the
question are later messages, after the breakpoint, so every question on a snapshot reads the same cache entry.
The implicit breakpoint is not used: it would sit after the question.
- **Which snapshot answers a question.** Among the snapshots of the configured model whose cache the ledger
predicts alive, each is held to both limits measured against its own prefix, and the one with the smallest overlay
among those within them is used, so a larger snapshot whose overlay fits wins over a smaller one whose overlay
does not. Otherwise (no live snapshot, every overlay over a limit of its snapshot, or the overlay disabled and anything changed) a new
snapshot is built from this checkout and used with an empty overlay. When no cache is predicted alive but a
stored snapshot has exactly this checkout's files, its stored prefix is used instead of rendering the same one
again.
- The base branch moving does not rebuild anything by itself; several snapshots may coexist for branches on
different bases; a snapshot is never replaced, its provider cache simply expires. Snapshot directories unused for
7 days are removed; every `ask` and `rebuild` runs this cleanup first. Publishing a snapshot, cleanup, and each
question's whole choice (listing the snapshots, reading their prefixes for the overlay, marking the chosen one as
used) share a lock per corpus directory, so cleanup never removes a candidate while it is read or a snapshot a
question has chosen. `status` lists and chooses under the same lock.
- A snapshot built from a checkout with unfinished edits becomes a base that other checkouts diff against. That
stays correct, at the price of a slightly larger overlay.
- **Token counts** have no tokenizer dependency: bytes divided by 4, replaced by the measured ratio (bytes sent /
`usage.input_tokens`) after the first request of a snapshot.
## The cache ledger
Per snapshot: creation time, last cache write, last cache read, TTL, prefix size, cumulative tokens by kind
(uncached, cached read, cache write by TTL, output; the part above 272,000 input tokens kept apart for its price
tier) and the last request's tokens and time, updated from `usage` after every request. When `usage` gives cache
writes without the per-TTL split (`cache_write_tokens_details` is optional in the SDK), they are counted at that
request's TTL before they are summed, so later requests at another TTL do not reprice them. `status` shows the last
completed request across the corpus's snapshots, also right after `rebuild` made a new, unused one.
- Predicted alive: `now < last_write + ttl`, or from the later of the last write and the last read when
`cache_read_extends_ttl` is true. A snapshot never written is predicted cold.
- Every request records whether the prediction matched `usage` (predicted alive but nothing read; predicted dead
but read); `status` shows the counts. This is the only "is the cache dead" detection in this version.
- A response without `usage` (the SDK allows it) is counted as a completed request and nothing else: it changes
neither the last write or read nor the tokens nor the mismatch counts. `status` then shows the last request's usage
as unknown and marks the cumulative tokens and cost as a known subtotal with the number of such requests.
- A cold write is serialized with a file lock in the snapshot directory, so parallel questions wait for one write
and then read it instead of each paying for a write.
## What is sent to the provider, and for how long it is kept
Every `ask` sends the full text of the selected files (the snapshot), the overlay of local changes and the
question to the configured `url` (by default OpenAI), with `store: false`. Nothing else from the machine is sent,
and the API key is sent only as the request's credential.
From OpenAI's [data controls](https://developers.openai.com/api/docs/guides/your-data) (checked 2026-11-28): API
data is not used for training unless you opt in; abuse-monitoring logs are kept for up to 30 days by default;
prompt caching may keep encrypted key/value tensors in GPU-local storage as application state, not retained after
a 24-hour expiration, and `prompt_cache_options.ttl` sets the minimum cache lifetime, not that maximum. Caches are
not shared across organizations. Organizations with Zero Data Retention get `store` treated as `false` anyway.
## Cache behaviour
The server lives by the provider's TTL: the first question on a snapshot writes the cache (billed at the write
price), later questions within the TTL read it at the cached-input price. A cache entry shorter than 1,024 tokens
is not cached by the provider at all.
**Warm-up and keepalive are under research.** The server contains no warm-up or keepalive code; `rebuild` builds a
snapshot locally and does not contact the provider. Whether a keepalive is worth it depends on how the cache
really behaves, which the research harness measures.
## Provider facts: what is confirmed and what is not
All OpenAI specifics are in [`src/cag_mcp/provider.py`](src/cag_mcp/provider.py), including the embeddings call,
its usage and its price that the benchmark's naive baseline uses. Checked against the installed
`openai` SDK (3.60.0) types and the OpenAI documentation on 2026-11-28:
- Confirmed in the SDK types: `prompt_cache_options.ttl` accepts `"30m"` and `"12h"`; `prompt_cache_options.prewarm`
exists; `prompt_cache_options.mode` is `implicit` (the default, one implicit breakpoint after the latest message)
or `explicit` (only the `prompt_cache_breakpoint`s on `input_text` blocks, up to four per request; none disables
caching, which the benchmark's no-cache system uses); `usage.input_tokens_details.cached_tokens`,
`.cache_write_tokens` and `.cache_write_tokens_details.ttl_30m_tokens` / `.ttl_12h_tokens` exist.
- Confirmed in the docs: write prices 1.25x (30m) and 2.5x (12h) instead of input, minimum cacheable prompt 1,024
tokens, uncached input = `input_tokens - cached_tokens - cache_write_tokens`, the prices above, the long-prompt
rate above 272,000 input tokens (2x input and cache, 1.5x output, on both model pages), and reasoning efforts
`none, low, medium, high, xhigh, max` for both models.
Not confirmed, to be checked by `research/cache_ttl/run.py --smoke` and the research run:
- that `gpt-6-luna` itself accepts `ttl` and `prewarm`: the SDK and the guide say "GPT-5.6 and later"; the model
page does not mention them;
- whether a read extends a 12h entry: the guide documents only that a 30m read on a 12h entry keeps the later of
the existing expiry and 30 minutes after the read;
- that `none` is accepted at request time (the model page lists it; `--smoke` tries `none`, `minimal`, `low`,
`medium` and reports the first accepted);
- how the provider matches a request against entries written at other breakpoints (the S3 and S4 canaries of the
research measure it); the offline fake reads only an entry that ends exactly at one of the request's breakpoints;
- that `responses.input_tokens.count` (in the SDK types) counts a request as its billed `input_tokens` do and bills
nothing, and whether its count of a request cut after its last breakpoint (the input items up to that breakpoint,
with the request's `text` answer schema, `reasoning`, `instructions` and `tools` kept, since the prompt-caching
guide places schemas before the breakpoint and says reasoning settings can rewrite the prefix instructions) equals
the tokens up to the breakpoint or adds framing after it. The research and the benchmark's overlay table use that count as the size of
a cached prefix (a request covered its whole prefix only when its cached plus written tokens equal it; usage above
it contradicts the count and decides nothing); if the provider adds framing, no request reaches it and every
whole-prefix conclusion stays undecided (`--smoke` checks that its write reaches the count). The fake counts exactly the tokens up to the breakpoint.
## Cache research harness
`research/cache_ttl/run.py` runs the experiment of PRD section 11 over about 26 hours and writes `records.jsonl`
plus a generated `REPORT.md` into a run directory (default `research/cache_ttl/runs/<UTC timestamp>/`).
```sh
uv run research/cache_ttl/run.py --smoke # small writes and reads; checks ttl, prewarm, usage fields
uv run research/cache_ttl/run.py --run-dir research/cache_ttl/runs/main # the schedule; rerun to resume
uv run research/cache_ttl/run.py --dry-run # the whole schedule against the fake client, in seconds
```
Every time point uses its own prefix, made unique by a salt at its very start. Every request sets its cache
boundaries with explicit breakpoints: S3 writes the short prefix, then the long one with breakpoints at both ends;
S4 writes the long prefix in one piece and never the short one on its own; each canary read carries one breakpoint
at the end of its own prefix. S3 and S4 each have two arms: A asks the short and the long prefix at the same time T,
B asks the short prefix at 11 h and the long one at 13 h or 23 h. Arm A counts the canary as agreeing only when
both reads read their whole entry, or neither did (see "whole entry" below); each line shows both cached and input
token counts. A pair counts only when both reads
succeeded, every original write of the probe was recorded as billed (in S4 the long one), in S3 the entries were
prepared as planned (the separate short write wrote its whole prefix, and the long write read that whole entry and
wrote the rest up to its own breakpoint: a long write that found no short entry and wrote both boundaries at once
leaves entries written together, not the ones the plan pairs; the same check holds for both S3 B arms), no request of the probe
was sent again after an interrupted attempt, neither read fell short of a whole-entry read without being a miss, and the two reads ran at most
300 s apart, measured as the widest distance their unrounded dispatch and return times allow (a pause, a budget stop
or a slow request can part them), and the read sent first wrote nothing. The pair is sequential: a write by the first
read (the short read missing and writing its prefix again) may displace the long entry before the long read, so the
second read shows what it saw, not the state of the long entry before the pair; such a pair stays an observation.
The one exception is a whole long read after a short write, which still shows a live long entry (a short write cannot
create it). The plan has no long-only read at a canary's age, so a gone long entry after a short read that wrote is
never counted, and with a real provider (which writes on a miss) the stand-in recommendation below is not reached
from arm A alone. Each line shows both actual read
times, and a pair that fails this keeps its line, marked "not counted". Each agreeing pair says whether the long
entry was live or gone. The report gives the number of counted pairs out of the four scheduled and recommends the
short request as a stand-in only when all four were counted and agreed, with the long entry live at some pairs and
gone at others: agreement on one state alone (four double misses, say) does not show that the short request detects
the other; with no counted pair it reports insufficient data. The extension questions (S2 and the B arms) run
one trial per end point (13 h, 23 h), each on its own salt: the write(s), the read at 11 h, one terminal read. Each
trial has a control on its own salt with the same writes and the terminal read alone, so no other request touches
either entry before its terminal read. In S3 an end point counts only when, in each arm it uses, the separate short
write wrote its whole prefix and the long write read that whole entry and wrote the rest up to its own breakpoint: a
long write that wrote both boundaries after the short write failed leaves entries of another history, so the arms
would no longer differ only by the early read. S4 writes no short prefix on its own by design.
The schedule is persisted in `schedule.json`. Before a step's requests go out, a `pending` line with the guard's
worst-case estimate is appended to `records.jsonl`; after them, one record per copy (S7 sends five). On restart the
journal is reconciled: a last line that a crash cut off is moved to `records.torn` before anything is appended; a
step is done only when the records of all its copies are there, so a step whose records were written is never sent
again, while a step with copies missing is sent again (its earlier records stay in the journal and the spend, and
the report uses the complete attempt). The spend is the cost of every record plus, for each copy whose record was
lost, its share of the worst-case estimate. A run directory refuses to resume with another `--model` or with live
and dry mode swapped. A dry run also keeps the fake client's simulated cache in `fake_cache.json` beside the
journal, saved after every request of the schedule (a `--smoke --dry-run` in the same directory leaves it alone),
so a resumed process continues the virtual clock and reads the entries the
stopped one wrote, without sending or charging its requests again. Late steps run as soon as the process is back; every
record carries the planned and the actual UTC time and the hours since the actual write of the cache entry it
reads (a read that missed and wrote the entry again counts as a write, unless it wrote fewer tokens than an earlier
write of the prefix reached, which leaves the entry at the breakpoint as it was; a write or prewarm step whose usage shows
that it only read a live entry and wrote nothing is dated from the earlier write it read). That age is unavailable (`n/a` in the
table) when no write of the probe was observed, for example when the write failed or its response carried no
`usage`. Every record also carries its call boundaries, `sent_ts` and `done_ts`, read from the run
clock right before and after its client call, and those of the write of the entry it reads (`write_ts`,
`write_done_ts`). The provider wrote or read somewhere within those boundaries, so an age is a range: from the write's
return to the read's dispatch at the least, from the write's dispatch to the read's return at the most. The report
compares unrounded ranges, and every inference from an age or an interval (lifetime, extension, prewarm, S6) must hold
across the whole range; it rounds only for display, where the age shows as `a to b` when the range is wider than
0.01 h (`hours_after_write` stays the dispatch-to-dispatch value). A lifetime read that hit or missed at an age range
that spans the minimum counts neither as within it nor past it, and a miss that may lie within the minimum is
reported as such, not as an early death.
Before a step's requests, the harness asks the provider to count the input tokens of the step's request cut after its
last breakpoint (`responses.input_tokens.count` with the input items up to that breakpoint, no tail, and the request's
settings that render before it or rewrite it: `text`, `reasoning`, `instructions`, `tools`; the endpoint bills nothing)
and records the count as `breakpoint_tokens`. The prefix is rendered alike in both, so the count is at least the
number of tokens up to the last breakpoint; a failed count leaves it unknown. A request reached its breakpoint only when its cached plus written tokens equal that
count (`provider.whole_prefix`). A request without a count of its own (its count failed, say on a resumed run) is
checked against the count recorded for the same rendered prefix (its probe and prefix). Usage above the count
contradicts it: such a request reached nothing and shows no state of its entry, so a read that cached nothing and
wrote more than the count is no miss and one that cached more than it is no hit; both are left out of every
conclusion as not shown to have read their whole entry. While any request of the prefix, up to and including a read,
covered more than its count, the read's coverage is undecided and its line says so (a write above its count is
reported as contradicting the count, not as a partial write); any framing the provider counts after the breakpoint only makes the count unreachable, and every conclusion that
needs a whole entry then stays undecided. Usage alone never shows it: the same counters come from a whole prefix and
a tail or from a shorter cached span and more uncached input, so neither the uncached input nor a comparison among
requests (which can all stop equally short) certifies a breakpoint. A read counts as having read its whole entry only
when some observed request of its probe and prefix, up to and including the read itself, reached the count, none of
them covered more than its count, and the read's cached tokens equal it. Otherwise its coverage is undecided, and its line gives the raw counters and the
bounds that were observed: at least the most any request of the prefix read or wrote (a later request that covers
fewer tokens does not shrink it) and at most the count. An S4 short read, whose prefix is never written on its own,
is thus shown whole only by its own usage against its own count. An original write counts (for the
lifetime, the canary, the extension controls, the prewarm comparison and the S6 billing statement) only when it is
the write that dates the read (the latest write of the prefix that the read's age counts from, so a later rewrite
replaces the planned write), it reached its breakpoint, and the usage's per-TTL split
(`cache_write_tokens_details`) bills all of it in the tier the conclusion claims: 12h for S1, S2, S3, S4, S5 and S6,
30m for the S8 lifetime. A write that stopped short leaves an entry of another size than the one tested, and a write
billed in another tier, or with no split, one whose lifetime the conclusion does not describe: neither is comparable
with the other arm's, and the conclusion stays undecided with the raw usage in the table. A read whose entry was not read
has no cached tokens, or exactly what an earlier request of a shorter prefix of the probe left (the 5k start of an S3
long read). Any other read is "not shown to have read its whole entry": some cached tokens, or most of the input, are
no evidence that the whole entry was read. Such a read keeps its raw usage in the table and its
line, shows neither a live nor a gone entry, and is left out of the lifetime, the canary, the extension (also as the
early read), the prewarm comparison and the S6 billing statement, with the tokens it read against what the write
left. A row whose step was sent again after an interrupted attempt is marked "replayed" in the table. The age of
every read of a probe that, at or before it, had such a replay or a failed request that may have reached the provider
is marked, in the table and wherever the report lists it, as counted from the last observed write while a lost
attempt may have written the entry later. A
lifetime conclusion (S1, S8) leaves out reads of unknown age, reads whose original write did not reach its
breakpoint or was not billed in the tier of the lifetime, and the reads of a probe that was sent again after an interrupted attempt, and says which reads it left out; their rows and cost stay in the table. It says
that no warm-up is needed within the minimum TTL only when a counted read inside the minimum hit and none missed,
and gives the oldest such hit; with no counted read inside the minimum it says so and draws no conclusion.
`--max-usd` (default 10; it must be a finite amount of 0 or more) stops the run, and `--smoke`, before the next
request could take the estimated spend over
the limit. The estimate is a worst case: the whole request (prefix, overlay, question) estimated at 3 bytes per
token (a cautious choice of the harness, not a provider fact) and billed as a cache write at its TTL, the full
output cap (`max_output_tokens = 16` on every research request), every parallel copy, and the long-prompt tier
when the estimate is above 272,000 input tokens. A model without built-in prices is refused. Every research
request is one transport attempt (the client is built with `max_retries = 0`, so the SDK never resends a request
the guard did not reserve). A failed request that may have reached the provider, such as a timeout or a 5xx, is
charged at its worst-case estimate, in the running spend and in its record, so a resume keeps the charge; only a
4xx refusal counts as unbilled. A response without `usage` (the SDK allows it) is charged the same way and recorded
as an error: it is no cache observation. `--scenarios S1,S7` runs a subset; `--model` picks the model.
The report has a table per scenario (breakpoints, planned and actual time, hours after the write, result, input,
cached, written and output tokens, estimated cost with its price tier) and states what was measured and what it
implies for warm-up, derived from the records. A conclusion needs its controls: that a read extends an entry (S2,
and the B arms of S3 and S4) is stated only when, at an end point, both arms have a recorded, billed original write
of the tested prefix that reached its breakpoint, no request of either arm was sent again after an interrupted attempt (a lost request may have
read or rewritten an entry), the trial's read at 11 h read its whole entry (without writing the entry again) less than one minimum TTL after the
tested entry's observed write (a read that ran later may have found the entry alive unread at the age its control
was gone, so the end point names it and cannot tell), its terminal read
read its whole entry at an age range entirely past the minimum TTL, and its control's terminal read missed at an
actual age at or up to 0.25 h before the trial's hit across both age ranges (a control that missed later fits one
natural lifetime between the two ages); and no end point contradicts it. Such a contrast "supports extension" and
gives the observed survival interval: the trial's age at its hit after its write and after the read at 11 h, and the
control's age at its miss. That bounds survival after the read from below (the 13 h end point shows 2 h, not a full
TTL); one trial per end point cannot exclude entries that simply live different lengths, and the report says so. No
end point decides `cache_read_extends_ttl = true` (the ledger's model: a read restarts the full TTL): a hit at the
23 h end point fits an entry that lives longer by itself or a refresh shorter than the TTL as well, so the report
says only that the end points give no ground to change the setting from its default `false`, and it makes no claim
that regular questions keep the cache alive without warm-up.
A control that lived as long, within 0.25 h, gives "does not show"; a trial whose terminal read missed less than
one minimum TTL after the read at 11 h (measured between the two reads' call boundaries, since in S3 the short and
the long entry are written one after the other) gives "did not restart a full TTL" with the time after the read the
entry was gone by (it may still have outlived its original write; in the B arms of S3 and S4 the summary says only that the
short read did not keep the tested entry alive a full TTL and draws nothing about `cache_read_extends_ttl`, since the
short read is no read of the whole entry), except in S3 and S4 when the short
read may have run a full minimum TTL or more after the long entry's observed write: then the long entry may already have been
gone when the short one was touched, and the end point names the delayed read and stays inconclusive; anything else (a missing write, a replayed
request, a missing or failed control, ages too far apart, a miss a full TTL after the read) is reported as observed
and the extension as inconclusive, since an entry that simply lives longer than the minimum
gives the same hits. S5 pairs each prewarm read with the S1 55k read of the same planned delay (1, 11, 12.5 and
14 h) and shows both actual delays. A pair counts only when both reads succeeded, both original writes (the prewarm
and the S1 write) were recorded as billed and reached their breakpoints, and neither probe was sent again after an interrupted attempt. A hit of the
whole entry and a miss count as a difference only when the entry that hit was at least as old as the one that missed
across both age ranges; when the entry
that hit was younger, one shared lifetime between the two ages explains both and the pair is inconclusive. Two
reads with the same outcome count as agreeing only when their actual ages are within 0.25 h of each other across both
ranges; further
apart, the pair keeps its line and is not counted (an entry may have lived past the younger age and not the older).
"Did not match" needs a counted difference, "matched" needs all four pairs counted and agreeing, and anything else
is reported as inconclusive. For the S5-live prewarm the report reads what it met from its own usage and the observed
write before it (the latest one, which must have reached its breakpoint and been billed in the 12h tier): on a live entry (a read of the whole entry, no write), part of the entry, which says nothing about a whole
live entry, a write that stopped short of its breakpoint, which does not show that it wrote the entry again, or (possibly) past the documented minimum a new write that says nothing about a live entry, or within the
minimum an entry that was gone. S6 gives each tail's usage and cost, says when a tail neither read nor wrote the cache,
and makes no claim about the prefix being billed again when the write that dates the entry a tail met (the latest of
the prefix, a tail's own rewrite included) was not observed, did not reach its breakpoint or was not billed in the 12h
tier, or when a request of
the probe was replayed after an interrupted attempt or failed after it may have reached the provider at or before
that tail (the entry it read may come from the lost write); a tail that missed and wrote the prefix past the
documented 12 h minimum is reported as a possibly expired prefix, not as a write caused by the tail, and one that
wrote without reaching the count of its prefix is reported as a partial write, which does not
show that a tail bills the whole prefix again. S7 reports only
what the usage and the clock show: how many copies succeeded, failed, billed a write and read from the cache, and how
many copies overlapped every other copy in time, how many did not overlap at least one other, and for how many this
is unknown. Two copies overlapped only when their spans share an interval of positive duration and were apart only
when one returned strictly before the other went out; equal, touching or zero-length spans (a zero-length span inside
another one too), and records without the times, leave it unknown. Each copy's actual time is its own dispatch time,
and the table shows every request's send and return time to the millisecond. When the parallel step was sent again after an interrupted attempt it says
so (then it need not be a cold start). It draws no conclusion about how the provider handled the concurrent requests. S8 lists the usage of the request above 272,000 input tokens and the
documented tier it was estimated at. The header gives the run's date and time in UTC, the mode, and the versions
of cag-mcp, `openai`, `mcp`, Python, uv and Claude Code. A dry-run report is marked as such; its numbers come from
the fake client and are not provider data.
## Benchmark harness
`benchmarks/run.py` compares, on a corpus directory and a questions file:
1. cag-mcp on `gpt-6-luna` and on `gpt-6.1-terra`;
2. a deliberately **naive** vector baseline (fixed-size chunks, OpenAI `text-embedding-3-small` embeddings,
brute-force cosine, top-k chunks to the same answering model), labelled naive in every table and living only
under `benchmarks/`;
3. the answering model with the full corpus and caching disabled (no cache breakpoint in the request);
4. a grep agent: `claude -p` in the corpus copy, on Haiku 5.5 and Sonnet 5.5.
```sh
uv run --group charts benchmarks/run.py --corpus ~/proj/work/loop-manager \
--questions questions.jsonl --edits edits.jsonl [--include '**/*.md'] [--systems cag:gpt-6-luna,grep:haiku]
uv run benchmarks/run.py --corpus tests/fixtures/bench/corpus \
--questions tests/fixtures/bench/questions.jsonl --edits tests/fixtures/bench/edits.jsonl --dry-run
```
The questions file is JSONL: `id`, `type` (`direct`, `paraphrased`, `multi`, `unanswered`), `question`, and
`expected` as a list of `{path, anchor}` where the anchor is verbatim text of the file. The edits file is JSONL:
`id`, `path`, `old`, `new`, `question`, `anchor` (verbatim text of the new fact), and `old_fact` and `new_fact`: the
fact the question asks about as the `old` and the `new` text state it (`3.12` and `3.13`, say). The question should
ask for a short answer (`Give just the number.`): only an answer that is, as a whole, the level's fact or one of the
optional `old_answers` / `new_answers` (other accepted short answers, each stating its own fact and not the other)
counts as stating it. Question ids must be unique:
a duplicate id stops the run before any system is asked. The fixtures in
`tests/fixtures/bench/` show both formats.
The corpus is never modified in place. Every system works on a temporary copy that holds only the selected regular
files: no symlinks, no `.git` directory or worktree pointer file, no `.claude/` directory at any depth and no
`.cag-mcp.toml`, even under a mask such as `**/*`. The harness writes its own `.cag-mcp.toml` into the copy cag-mcp
answers from and excludes it from the corpus, so it never becomes measured input. The Claude callers get a second
clean copy of the same selected files, so they never see that generated file either. Every system's citations are
resolved against the selected files with the same path rules: the naive baseline's excerpts carry their paths in the
escaped prompt form of cag-mcp (`&`, `"`), which is read back as such, while the grep agent's relative
paths are taken literally. Edits and padding are refused for any path that is not a selected regular file of that copy.
Both Claude callers (the grep agent and the judge) run read-only:
`claude -p --model <id> --output-format json --json-schema <schema> --restricted --safe-mode --tools Read,Grep,Glob
--permission-mode dontAsk --strict-mcp-config --disallowedTools 'mcp__*' --no-session-persistence`, with the prompt
on stdin and the clean copy as the working directory. `--restricted` (Claude Code v2.1.248 or later) confines the built-in
file tools to the working directory and loads only managed settings, so no user, project or local settings (and no
pre-approved permission rules from them) apply. `--safe-mode` disables hooks, CLAUDE.md, skills, plugins, MCP
servers, custom commands and agents, while authentication works as usual, with one exception: hooks configured by
managed (organization) policy still run. `--tools` leaves only those three
built-in tools, `dontAsk` denies every call that would ask for permission, and no MCP server or tool is available.
Managed (organization) policy still applies, as Claude Code documents for both modes. The reply is read from the
`structured_output` field of the JSON envelope and checked against its schema (the answer needs a string `answer`,
a boolean `answered` and citations that are objects with string `path` and `quote`; the verdict a boolean `correct`
and a string `reasoning`). A failed run, an error envelope or a missing or malformed structured output is recorded
as an error, never as an answer or a verdict.
Per system and question the harness records whether an expected file was cited, whether the cited lines overlap the
expected ones (both count only an answer: a reply with `answered` false scores neither on an answerable question,
whatever it quotes, and on a question the golden set calls unanswered both mean a correct abstention), the time to answer (the summary gives the median over the successful rows), tokens by kind and the cost, priced per request (including the long-prompt rate
above 272,000 input tokens). The naive baseline's cost includes its embeddings, priced at the rate of the
`text-embedding-3-small` model page; the index is embedded once, within its first question, and kept only when every batch succeeded (after a failed batch the next question builds it again). A failed row counts as
wrong and is left out of time; its tokens and cost count only what it is known to have billed: the usage of a
request whose answer was unusable (a malformed or empty structured answer on every OpenAI system, and on the grep
agent a reply without valid structured output or an error envelope that carries `usage`, also when `claude -p` exits
non-zero) and the embeddings a naive-baseline row billed before it failed (the index it built is reused by the next
question, so its cost stays in the comparison). An answer that is valid JSON but breaks the answer schema (for example
`citations` that is not a list, or a missing `answered` or `citations` field, which is never filled in with a
default) is such an unusable answer, and an overlay row that failed this way keeps its usage
too. Token counts and dollar amounts are read and summed separately (`tokens_complete` and `cost_complete` on each
row): a `claude -p` envelope with a price but no usage keeps its price, and one with usage but no price keeps its
tokens. Only the token counts a reply reports are recorded: its usage counts as complete only when it gives both
`input_tokens` and `output_tokens` (absent cache counts are then zero); an empty or partial `usage` keeps the counts
it has and marks the row's tokens incomplete. When some row's dollar amount is unknown (a connection error, a server error, a failed `claude -p` run
without an envelope, a response without usage, a reply or model without a price) the cost column shows the sum of
the known amounts marked `known subtotal`; when some row's usage is unknown the `token counts` column says `known
subtotal` (otherwise `complete`). Missing usage is never recorded as zero; a provider refusal (4xx) counts as
unbilled. A live run builds its OpenAI client with `max_retries = 0`: every request is one transport attempt, so a
failed row's billing covers the only request it sent (a 5xx whose retry the SDK would have answered with a 4xx
would otherwise be marked complete). A system with no known dollar amount shows `tokens only`, so a broken system never looks fast or cheap.
The grep agent's cost is the one `claude -p` reports. The benchmark has no spend guard of its own.
Every mismatch goes to a judge (`claude -p` on Opus 5.5): a row with no overlap, or whose `answered` disagrees with
the golden set (failed rows are never judged). The judge reads the cited lines and decides whether the answer
is right. All verdicts are collected first; then each question of one shared adjudicated golden set is settled from
every answer the judge accepted for it, so the order of the systems does not matter. An accepted answer adds its
verified citations that resolve to lines of the corpus as expected sources; a question the golden set called
unanswered becomes answerable only when such a citation exists. An accepted abstention turns a question the golden
set called answerable into an unanswered one (its expected sources are kept). When the judge accepted both an answer
and an abstention for one question, the original answerability stays and the verdicts that contradict it are
declined. Every accepted answer is logged with its reasoning and its outcome (`changed` when it changed the
answerability or added a source, `already` when the golden set already said so, or `declined` with the reason) in `adjudication.jsonl`; every row of every system is then
scored again, so each metric is reported twice, against the original and the adjudicated golden set. The report
gives the number of mismatches judged, of judge runs that gave no verdict (a failed judge corrects nothing) and of
accepted answers by outcome.
The overlay degradation run uses cag-mcp on `gpt-6-luna` with both overlay limits off. It applies the scripted
edits plus whole-line rewrites until 0 / 5 / 10 / 25 / 50% of the selected bytes changed (the report shows the
measured share), asks about the changed facts and reports accuracy and citation verification per level (verified
citations as the mean of the per-answer ratios). Each edit replaces the first occurrence of its `old` text, and the
harness tracks the lines of that replacement: padding never touches them, also when the fact spans several lines.
Every expected fact (the `old` text at level 0, `anchor` above it) must resolve, as a citation of it would, to the
lines the edit replaced. Above level 0 the `anchor` must also be part of the edit's `new` text (whitespace
normalized), so text that merely shares a line with the replacement is refused. An edit whose `new` text is its
`old` text (whitespace normalized: padding alone would make every level look edited) or keeps all of it (the
original fact would stay in place beside added text), or whose `anchor` is also part of its `old` text (a quote of
the original fact would then match it), is refused too, and so is an edit without `old_fact` and `new_fact` or whose
facts do not tell the versions apart: `old_fact` must be part of `old` and not of `new`, `new_fact` part of the anchor
(and so of `new`) and not of `old`, each as a whole value (whitespace normalized, case folded; `3.13` is not part
of `3.130`). An edit that keeps the old fact and only
changes punctuation or adds an aside is refused this way when its facts name what the question asks; the harness
cannot tell a mislabeled fact. When an expected fact is missing, or its first match in the file (whitespace normalized, as citations resolve)
is not the very text the edit put there, such as an earlier copy of the same text, even on the same line, the run
stops with the edit's id. All levels are checked before the first request. There is no
warm-up call: the snapshot and cache written by the measured questions (or by level 0's own questions) are the base,
and every later level should answer from that snapshot with the edits in the overlay. The harness checks it: level 0
must succeed on one snapshot that wrote or read the provider cache, without an overlay (an overlay at level 0
means the corpus changed after the base snapshot was taken), and a later row counts as measured only when it
answered from that snapshot, sent an overlay and read the whole cached base (a read of part of the prefix is no
answer from the base; a response without usage proves neither). The size of the base is the provider's count of a
level-0 request itself cut after its cache breakpoint, with its answer schema and reasoning settings (`base_tokens` on
each level-0 row, from `responses.input_tokens.count` as in the research rule above; the largest when they differ), and
it counts only when some level-0 request read or wrote exactly that many tokens (cached plus written): the usage alone
cannot tell a whole base from a shorter cached span. A level-0 row whose own count failed is checked against the
count of the others (one snapshot renders one base). Usage above the count contradicts it: when a level-0 request
covered more than its count the base is unknown, and a later row whose cached plus written tokens exceed the
base's count is not measured: its one cache breakpoint closes the base, so it can neither read nor write past it, and
a row that read the whole base and wrote beside it contradicts the count as well. A measured row read exactly the
count and wrote nothing. Otherwise the run reports that it could not measure cached overlays and
every edited level shows `n/a`; the rows keep their raw usage. The report gives the count per level and computes every
metric of an edited level from its measured rows only (`n/a` when there are none; `overlay.jsonl` keeps every row).
File hit, lines overlap and verified citations show where an answer looked, not which version of the fact it gives: a
quote of text both versions share, or of an aside added beside the edit, verifies and overlaps the edited lines. So
two more columns score the fact the question asks about, `old_fact` at level 0 and `new_fact` above it:
`states_fact`, an answer that is the fact (the whole answer, whitespace normalized, case folded, stripped of quotes
and a final period, equals the fact or one of the edit's accepted short answers, normalized the same way; a
sentence that mentions the fact,
rejects it or gives a longer value such as `3.130` does not count), and `quotes_fact`, a verified citation of the
edited file whose quote, at the place in that file where the citation verifier resolved it (its first
whitespace-normalized match, case kept), spans an occurrence of the fact that is a whole value in the
file text and lies within the expected anchor (`old` at level 0). The boundaries are checked in the file, not in the
quote: `Avoid Python 3.13` verifies against a line `Avoid Python 3.130.` but quotes part of a longer value, and a
quote of the fact outside the anchor does not count, nor does `Python 3.13` when its first match in the file is
that aside, even if a later match is the edited fact. A correct citation counts in `quotes_fact` whatever the
answer says. The report says plainly when the run could not measure cached overlays, for example when level 0 failed or the corpus is below the
provider's cache minimum.
Results go to `benchmarks/results/<UTC date>/` or `--out`, which must lie outside the corpus (the harness refuses it
before it writes anything). A `--questions` or `--edits` file at one of the artifact paths below is refused the same
way, before anything is deleted or asked. A run first deletes the files an earlier run left in that directory under the names
below, so it never holds a mix of two runs: `results.jsonl`, `adjudication.jsonl`, `overlay.jsonl`, a generated
`REPORT.md` (header: date and time in UTC, the commits of cag-mcp and of the corpus, model ids, versions of
`openai`, `mcp`, Python, uv and Claude Code) and `accuracy.png` when matplotlib is installed (`--group charts`).
## Benchmarks
Results are pending: the benchmark has not been run against a real corpus yet.
## Development
```sh
uv sync
uv run --frozen ruff check . && uv run --frozen ruff format --check . && uv run --frozen pytest -q
```
That is the `ci` script in `t3.json`. Tests use no network and no API key: everything that talks to the provider
runs against `cag_mcp.fake.FakeClient`, which simulates the prompt cache. `mise.toml` pins the Python and uv versions; ruff and pytest come from the `dev` dependency group.
## License
MIT, see [LICENSE](LICENSE).
TDQS
Scored across 3 tools
ask queries the corpus, status reports state, and rebuild regenerates the snapshot — three clearly distinct operations with no overlap. An agent can pick the right tool without inference from descriptions.
All names are single lowercase words with no separators, which is internally consistent and readable. Minor deviation: 'ask' and 'rebuild' are verbs while 'status' is a noun, breaking a strict verb pattern.
Three tools map cleanly onto the query / inspect / maintain lifecycle of a snapshot-backed doc server, with each earning its place. The surface is minimal but not artificially thin given the narrow domain.
The query-and-cite loop has a notable dead end: ask returns `path:start-end` citations telling the agent to read the lines itself, but no tool exposes file reads, so unverified citations cannot be resolved. No tool exists to refresh or clear a stale overlay/cache beyond a full rebuild.