King Context is a CLI-first retrieval layer for AI agents. Use it to keep documentation, research, code-adjacent knowledge, and architectural decisions searchable without loading large files into the model context.
The CLI is the primary interface for agent workflows. MCP support can still be useful as an integration layer, but new capabilities expose reliable CLI primitives first.
King Context installs three command-line tools:
kctx: search, read, index, and validate local retrieval stores.king-scrape: scrape a documentation site and export indexed sections. Also exposesking-scrape audit <name>to check an indexed corpus for broken, moved, or drifted URLs, andking-scrape update <name>to incrementally refresh an existing corpus, paying LLM cost only for new or changed chunks.king-research: build and index a research corpus for a topic.
The kctx command searches two content stores by default:
docs: product or API documentation under.king-context/docs/.research: open-web research corpora under.king-context/research/.
Architectural decisions use a separate ADR workflow:
- Human-readable ADR files live under
.king-context/adr/. - Derived decision indexes live under
.king-context/decisions/project/.
Use progressive disclosure. Start with cheap metadata, then read only the smallest section that answers the question.
-
List available stores:
kctx list
-
Search metadata:
kctx search "authentication api key" --top 5 -
Preview the most likely section:
kctx read exa authentication --preview -
Read the full section only when the preview is relevant:
kctx read exa authentication
For most agent tasks, stop after one preview or one full read. Use kctx grep
for exact strings, and use kctx adr for architectural decisions.
Use kctx list to see indexed documentation and research corpora.
kctx list
kctx list docs
kctx list research
kctx list --jsonArguments and flags:
source: optional. Useall,docs, orresearch. The default isall.--json: return machine-readable output.
When you list all stores with --json, the command returns an object with
docs and research arrays. When you filter to one source, it returns a flat
array.
Use kctx search to search titles, keywords, use cases, tags, and priorities.
The command returns metadata only, not full content.
kctx search "websocket streaming audio"
kctx search "authentication" --doc exa --top 3
kctx search "chain of thought" --source research
kctx search "rate limits" --source docs --jsonFlags:
--doc <name>: restrict results to one indexed corpus.--top N: limit results. The default is5.--source all|docs|research: choose which store to search. The default isall.--json: return machine-readable output.
Use technical terms, API names, and short concepts. The searcher tokenizes the query and scores exact keyword matches, use-case substring matches, tag matches, and section priority.
Use kctx read after search returns a section path.
kctx read exa authentication --preview
kctx read exa authentication
kctx read prompt-engineering-techniques ai-prompt-engineering-patterns --source research
kctx read exa authentication --jsonArguments and flags:
doc: indexed corpus name.section: section path without.json.--preview: return the first approximately 150 words and the full token estimate.--source all|docs|research: disambiguate a corpus that exists in both stores. The default isall.--json: return machine-readable output.
If the section path doesn't exist, kctx read suggests up to five similar
paths.
Use kctx topics to inspect tags inside one corpus.
kctx topics exa
kctx topics exa --tag authentication
kctx topics prompt-engineering-techniques --source research --jsonFlags:
--tag <tag>: show one tag group.--source all|docs|research: choose the store. The default isall.--json: return machine-readable output.
Use kctx grep when you know the exact method, parameter, error code, or text
pattern.
kctx grep "Authorization" --doc exa
kctx grep "WebSocket" --source docs --context 3
kctx grep "Error 429" --jsonFlags:
--doc <name>: restrict results to one corpus.--context N: include surrounding lines.--source all|docs|research: choose the store. The default isall.--json: return machine-readable output.
Use kctx index to build the file-based retrieval store from exported JSON.
kctx index .king-context/data/stripe.json
kctx index .king-context/data/research/prompt-engineering-techniques.json
kctx index .king-context/data/research/prompt-engineering-techniques.json --source research
kctx index --allFlags:
--all: index.king-context/data/*.jsonand.king-context/data/research/*.json.--source all|docs|research: force the target store. The default isall, which auto-detects research JSON when a section has"source_type": "research".
The indexer writes one directory per corpus and builds reverse indexes for keywords, use cases, and tags.
Use kctx adr to record and retrieve architectural decision records. ADRs are
human-readable Markdown files, and the JSON decision index is a derived cache.
Don't edit .king-context/decisions/ directly.
Allowed ADR statuses are:
proposedaccepteddeprecatedsupersededrejected
Accepted and proposed ADRs are active unless another ADR supersedes them. ADR-specific search commands show active decisions by default.
kctx adr list
kctx adr list --all
kctx adr list --jsonFlags:
--active: show active decisions. This is the default behavior.--all: include superseded, deprecated, rejected, and proposed decisions.--json: return machine-readable output.
kctx adr search "cli first retrieval" --top 5
kctx adr search "mcp context budget" --all
kctx adr search "agent retrieval" --jsonFlags:
--active: show active decisions. This is the default behavior.--all: include inactive historical decisions.--top N: limit results. The default is5.--json: return machine-readable output.
Search results include the ADR ID, status, active state, path, score, and supersession metadata.
kctx adr read ADR-0001 --preview
kctx adr read 0001-adopt-cli-first-architecture-for-agent-retrieval
kctx adr read ADR-0001 --jsonArguments and flags:
target: ADR ID or indexed path.--preview: return the first approximately 150 words.--json: return machine-readable output.
Use kctx adr timeline when current guidance and history both matter.
kctx adr timeline "cli first agent retrieval"
kctx adr timeline "job coordination" --jsonThe timeline groups results into active, superseded, deprecated or rejected, and related decisions. It also shows supersession reasons when they exist.
Use kctx adr new after searching for related decisions. The CLI enforces the
ADR structure; the agent or author decides which decisions are related or
superseded.
kctx adr new \
--title "Adopt CLI-first architecture for agent retrieval" \
--status accepted \
--date 2026-05-02 \
--areas "cli,retrieval,agents,mcp,product-strategy" \
--keywords "cli-first,agent-retrieval,context-budget,mcp" \
--tags "architecture,product,retrieval,agents" \
--context "The CLI gives agents fast, explicit retrieval primitives." \
--decision "Design future King Context capabilities CLI-first." \
--alternatives "MCP-first and strict CLI/MCP parity were considered." \
--consequences "Expose CLI primitives first and add MCP support later when needed."You can also create an ADR from a complete Markdown draft:
kctx adr new --from-file draft.mdWhen --supersedes is present, include --supersession-reason. The command
updates the superseded ADR and rebuilds the decision index.
Use kctx adr supersede when both ADRs already exist.
kctx adr supersede ADR-0001 ADR-0002 \
--reason "The old approach created unsafe deploy behavior."The command updates the old ADR with status: superseded and
superseded_by, updates the new ADR with supersedes and
supersession_reason, and rebuilds the index.
Use kctx adr link for a non-supersession relationship.
kctx adr link ADR-0001 ADR-0004
kctx adr link ADR-0001 ADR-0004 --type relatedThe MVP supports only related links. Links are reciprocal.
Use these commands after manual edits, merges, or conflict resolution:
kctx adr index
kctx adr status
kctx adr validatekctx adr indexrebuilds.king-context/decisions/projectfrom.king-context/adr.kctx adr statuschecks whether Markdown sources and indexed JSON are in sync.kctx adr validatechecks required fields, body sections, links, reciprocal supersession state, related links, and stale status metadata.
Use king-scrape to turn a documentation site into a King Context JSON export.
king-scrape https://docs.example.com --name example --yesThe scraper pipeline runs these steps:
- Discover URLs.
- Filter relevant URLs.
- Fetch pages.
- Chunk content.
- Enrich chunks with metadata.
- Export JSON.
Useful flags:
--name <name>: set the corpus name.--display-name <name>: set the display name.--step discover|filter|fetch|chunk|enrich|export: resume from a step.--stop-after discover|filter|fetch|chunk|enrich|export: stop after a step.--model <model>: choose the enrichment model.--chunk-max-tokens N: set the maximum chunk size. The default is800.--chunk-min-tokens N: set the minimum chunk size before merging. The default is50.--concurrency N: set concurrent fetch requests. The default is5.--no-llm-filter: disable LLM fallback in URL filtering.--no-auto-seed: skip database seeding after export.--include-maybe: fetch URLs classified asmaybe.--yes: skip interactive confirmation prompts.--provider <name>: choose the scraper backend for this run. SetsSCRAPE_PROVIDERfor the process. Stage-specific environment variables take precedence over the flag. See Scraper providers for the full table.--no-fetch-cache: bypass the scraper provider's local cache for this run. SetsSCRAPE_CACHE_MODE=bypass. Useful when upstream content has changed and you need a fresh fetch without wiping the cache directory by hand (Crawl4AI keeps a local cache under~/.crawl4ai/). Honoured by the crawl4ai provider; firecrawl's API defaults to fresh-fetch and ignores this flag. SetSCRAPE_CACHE_MODEdirectly tobypass,disabled,read_only, orwrite_onlyfor finer-grained control.
king-scrape writes exported documentation JSON to .king-context/data/.
Use kctx index to build or rebuild the file-based CLI store from that JSON.
king-scrape supports pluggable scraper backends. The default is Firecrawl
(cloud, zero-config, pay per page). Crawl4AI is available as a local opt-in
backend (free, requires a one-time ~300MB Playwright install).
Resolution rules:
SCRAPE_DISCOVER_PROVIDERandSCRAPE_FETCH_PROVIDERset the backend for their respective stages.SCRAPE_PROVIDERsets the backend for both stages when the stage-specific variables are not set.--provider <name>is shorthand for settingSCRAPE_PROVIDERfor one run.- When nothing is set, both stages use
firecrawl.
Stage-specific environment variables always win over the flag and over
SCRAPE_PROVIDER.
Environment variables:
| Variable | Effect |
|---|---|
SCRAPE_PROVIDER |
Sets provider for both stages. Default firecrawl. |
SCRAPE_DISCOVER_PROVIDER |
Overrides SCRAPE_PROVIDER for the discover stage only. |
SCRAPE_FETCH_PROVIDER |
Overrides SCRAPE_PROVIDER for the fetch stage only. |
king-scrape https://docs.example.comRequires FIRECRAWL_API_KEY in .env. No additional install beyond
npx @king-context/cli init.
If you installed via npx @king-context/cli init, the Crawl4AI Python
package is already in the project venv (bundled by the [all] extra).
You only need to download the Playwright browser once:
.king-context/core/venv/bin/crawl4ai-setupThen pick the backend per run:
king-scrape https://docs.example.com --provider=crawl4aiOr set it as the default for the project:
SCRAPE_PROVIDER=crawl4ai king-scrape https://docs.example.comCloned the repo for development? Run from the repo root:
pip install -e ".[crawl4ai]" && crawl4ai-setupA standalone PyPI distribution (pip install king-context) is on the
roadmap.
Crawl4AI for SPA-style discovery plus Firecrawl for stable fetch:
SCRAPE_DISCOVER_PROVIDER=crawl4ai SCRAPE_FETCH_PROVIDER=firecrawl king-scrape https://docs.example.comStage-specific variables take precedence over SCRAPE_PROVIDER and over
--provider.
The pipeline checkpoint is keyed by URL slug, not by provider. Resuming a partial run with a different backend works:
SCRAPE_PROVIDER=firecrawl king-scrape https://docs.example.com --stop-after fetch
SCRAPE_PROVIDER=crawl4ai king-scrape https://docs.example.com --step chunkURLs already fetched with one backend are not re-fetched when you switch.
Unknown discovery provider 'X'. Registered: ['crawl4ai', 'firecrawl']
The provider name is misspelled or not installed. Check the spelling of
--provider, SCRAPE_PROVIDER, SCRAPE_DISCOVER_PROVIDER, and
SCRAPE_FETCH_PROVIDER. The error message lists the registered providers.
ProviderUnavailableError: crawl4ai not installed in the active Python environment...
The Crawl4AI package is not in the active venv. For npx-installed
projects, run npx @king-context/cli update. For dev clones, run
pip install -e ".[crawl4ai]" && crawl4ai-setup from the repo root.
ProviderUnavailableError: Crawl4AI installed but Playwright browser missing. Run: crawl4ai-setup
The Python package is installed but the chromium binary is not. Run
crawl4ai-setup once. The setup downloads about 300MB on first run.
FIRECRAWL_API_KEY missing (or equivalent SDK error)
Firecrawl is selected (default) but no API key is set. Add
FIRECRAWL_API_KEY=... to .env, or switch to Crawl4AI with
--provider=crawl4ai.
Use king-scrape audit <name> to check whether an indexed corpus is still
aligned with its upstream source. The audit is read only: it never mutates
data/<name>.json or the database, and the URL health pass needs no
provider key, so it is safe to run on a CI cron.
king-scrape audit elevenlabs-apiEach section URL is classified by its final HTTP status:
| Status | Meaning |
|---|---|
fresh |
2xx |
moved |
redirect chain ending in 2xx; the final URL is captured |
broken |
404 / 410, including chains that redirect into a dead page |
throttled |
429; respects Retry-After (capped 30s), retries once |
auth_required |
401 / 403 |
unreachable |
timeout / network error / other 5xx |
URLs are canonicalised (fragment, trailing slash, host case stripped) before dedupe and before the discovery diff so cosmetic variations do not inflate the report.
A Markdown report lands at .king-context/audit/<name>-<timestamp>.md
(timestamp is UTC, microsecond precision, suffixed Z).
Exit code is 0 when no broken URLs are found, 2 when at least one is, so
the audit can gate a CI job. The URL health pass needs no provider key, so
the keyless form is the right shape for CI:
# CI friendly: no provider key required, no upstream discovery diff
king-scrape audit my-corpus --no-discover || echo "drift detected, see report"| Flag | Default | Description |
|---|---|---|
--no-discover |
off | Skip the upstream discovery diff (faster, no provider key required). |
--concurrency N |
10 | Max concurrent URL probes. |
--report-dir DIR |
.king-context/audit/ |
Where to write the report. |
The optional discovery diff calls the configured DiscoveryProvider
(Firecrawl or Crawl4AI) to remap the upstream and lists URLs added or
removed since the corpus was indexed. Use --no-discover to skip the
provider step entirely.
Use king-scrape update <name> to bring an indexed corpus back in line with
its upstream source. The command refetches every page, rechunks, and reuses
every section whose chunked content is byte identical to the previous scrape.
Only new or changed chunks are sent to the LLM, so a typical refresh costs
cents instead of dollars even on a corpus with hundreds of pages.
king-scrape update elevenlabs-apiThe flow:
- Locate
data/<name>.json(or.king-context/data/<name>.json). - Resolve the source URL from
_meta.source_url, falling back tobase_url. - Run discover, filter, and fetch with
force_refresh=Trueso changed pages are actually re-downloaded instead of being skipped by the resume logic. Note:force_refresh=Trueonly disables king-scrape's own slug-skip; the underlying scraper provider (e.g. crawl4ai) may still serve from its own on-disk cache. Pass--no-fetch-cache(or setSCRAPE_CACHE_MODE=bypass) when you suspect provider cache is masking upstream changes. - Rechunk all fetched pages.
- For each fresh chunk, look up
content_hashin the existing corpus. Hit: carry forward the enrichment values. Miss: enqueue for the LLM. - Show a cost preview (reused / new / removed / added URL counts plus the
OpenRouter dollar estimate) and prompt for confirmation.
--yesskips the prompt for scripted runs. - Enrich only the new chunks. Reused sections take fresh
title,path,urlso a page reorganisation upstream is reflected. - Write the merged corpus back to the same JSON path.
git diffthen shows exactly what changed.
| Flag | Default | Description |
|---|---|---|
--yes |
off | Skip the cost confirmation prompt before enrichment. |
--corpus-path <path> |
inferred | Explicit corpus JSON path; bypasses the default lookup in data/<name>.json and .king-context/data/<name>.json. |
--provider <name> |
env / inferred | Override the scraper provider for this run (always wins over SCRAPE_PROVIDER). |
--model <id> |
env / default | Override the OpenRouter model for enrichment. |
The work directory at .king-context/_temp/<host>/ is reset at the start of
every update so stale state from a prior run cannot leak into the new corpus.
The corpus JSON is written atomically (tempfile plus rename) so an interrupted
update never leaves a partial file. If discover or filter produces zero
URLs, the update aborts before writing and the original corpus is preserved.
auto_seed is intentionally off: update writes to the corpus committed in
the repo, not to the local indexed store. After a successful update, refresh
the local index with kctx index .king-context/data/<name>.json (or
kctx index --all).
king-scrape and king-research use OpenRouter by default:
Ollama provider support is beta. If you find bugs, or if you validate local models that chunk and enrich content with quality close to Gemini through OpenRouter, open an issue with the model name, command, and a short quality note: King Context issues.
OPENROUTER_API_KEY=...
ENRICH_PROVIDER=openrouter
FILTER_PROVIDER=openrouter
RESEARCH_PROVIDER=openrouterEach LLM stage can choose its own provider and model:
ENRICH_PROVIDER=ollama
ENRICH_MODEL=qwen2.5:7b
FILTER_PROVIDER=openrouter
FILTER_MODEL=google/gemini-3-flash-preview
RESEARCH_PROVIDER=ollama
RESEARCH_MODEL=qwen2.5:7bLocal Ollama uses the OpenAI-compatible API:
OLLAMA_API_MODE=openai
OLLAMA_BASE_URL=http://localhost:11434/v1
OLLAMA_API_KEY=Ollama Cloud or another native Ollama host uses the native API:
OLLAMA_API_MODE=native
OLLAMA_BASE_URL=https://ollama.com
OLLAMA_API_KEY=...Fallback is one-way from Ollama to OpenRouter:
ENABLE_FALLBACK=true
FALLBACK_MODEL=google/gemini-3-flash-preview
OPENROUTER_API_KEY=...Provider validation is stage-aware. For example, king-scrape --stop-after chunk
does not require LLM credentials, and URL filtering validates the filter provider
only if the LLM fallback path actually runs. Ollama-only enrichment reports local
runtime wording instead of a paid cost estimate; if fallback is enabled, the CLI
warns that OpenRouter fallback may incur cost.
Check configured Ollama stages with:
kctx llm-doctor --jsonFor installation, model download, and smoke test steps, see the Ollama guide.
Use king-research to research a topic from the open web and index the result
into the research store.
king-research "retrieval augmented generation for coding agents" --medium --yes
king-research "prompt engineering techniques" --basic --name prompt-engineering
king-research "agent memory systems" --high --no-auto-indexEffort flags:
--basic: fewer queries and no deepening iterations.--medium: default effort.--high: more queries and deepening iterations.--extrahigh: maximum query and deepening budget.
Workflow flags:
--name <slug>: override the output slug.--step <step>: start the research pipeline from a step.--stop-after <step>: stop after a step.--yes: skip the enrichment cost prompt.--no-auto-index: export JSON without indexing it into.king-context/research/.--no-filter: accepted as a no-op in the current P1 implementation.--force: accepted as a no-op in the current P3 implementation.
Research exports include "source_type": "research" in their sections, so
kctx index can route them to the research store automatically.
kctx search "authentication api key" --doc exa --top 3
kctx read exa authentication --preview
kctx read exa authenticationUse this pattern when you need current API behavior, setup steps, parameters, or examples from indexed documentation.
kctx search "tree of thoughts" --source research --top 5
kctx read prompt-engineering-techniques tree-of-thoughts --source research --previewUse this pattern when the answer depends on synthesized web research rather than one product's documentation.
kctx adr status
kctx adr search "cli first retrieval" --active --top 5
kctx adr read ADR-0001 --previewUse this pattern before changing architecture, adding new surfaces, or making a decision that could conflict with existing project guidance.
kctx grep "class Client" --source docs
kctx grep "Error 429" --context 3Use this pattern when metadata search is too broad and you know the exact text.
Use --json when another script or agent needs structured output.
kctx list --json
kctx search "authentication" --json
kctx read exa authentication --json
kctx adr search "cli first" --jsonThe exact JSON shape depends on the command:
- Search commands return ranked result objects.
- Read commands return the selected content and metadata.
- List commands return indexed corpus or ADR metadata.
- ADR timeline returns grouped decision history.
If .king-context/bin/kctx isn't present in a development checkout, run the
Python module directly:
python -m context_cli.cli --help
python -m context_cli.cli adr statusInstalled projects use the wrapper commands in .king-context/bin/.
If a corpus name exists in both docs and research, add --source docs or
--source research to kctx read and kctx topics.
Try shorter, keyword-based queries. Use technical nouns, API names, tags, and error codes instead of full natural-language questions.
Run:
kctx adr index
kctx adr validateIf validation fails, fix the Markdown source under .king-context/adr/, then
rebuild the index. Don't edit .king-context/decisions/ directly.