context7-cli 0.2.9

Search library documentation from your terminal — zero runtime, bilingual (EN/PT), multi-key rotation
Documentation

context7-cli

Crates.io docs.rs CI License


English

What is context7-cli?

Search any library's docs from your terminal — zero runtime, instant results.

Why use it?

  1. Single binary — one file, zero runtime dependencies (no Node/Python required)
  2. Cross-platform — Linux, macOS, and Windows with identical behavior
  3. XDG-compliant storage — API keys stored securely in ~/.config/context7/config.toml with chmod 600 (or OS equivalent)
  4. Multi-key rotation — multiple API keys with automatic shuffle and exponential backoff retry (500ms → 1s → 2s, up to 5 attempts)
  5. Bilingual UI — English and Brazilian Portuguese output (v0.2.0+)
  6. Privacy-first — no telemetry, no analytics, no data collection; keys are masked in all logs and list output
  7. Structured error handling — zero unwrap() in production; every error path returns a user-friendly message
  8. Multiple output formats — colored human-readable, --json for pipes/scripts, --text for LLM context

Quick install

Linux / macOS (via Cargo):

cargo install context7-cli
context7 --help

Windows (via Cargo + rustup):

# Install Rust from https://rustup.rs first, then:
cargo install context7-cli
context7 --help

Build from source:

git clone https://github.com/daniloaguiarbr/context7-cli
cd context7-cli
cargo build --release
./target/release/context7 --help

The crate is published as context7-cli on crates.io. The installed binary is context7 (no -cli suffix).

No Rust toolchain? Download a prebuilt binary for your OS from the GitHub Releases page (Linux gnu/musl tar.gz, Windows zip, macOS Universal Binary).

First run

# Step 1 — Add your API key (get yours at https://context7.com)
context7 keys add ctx7sk-YOUR-KEY-HERE

# Step 2 — Verify it was stored
context7 keys list

# Step 3 — Search a library
context7 library react

# Step 4 — Fetch documentation
context7 docs /reactjs/react.dev --query "useEffect cleanup"

Core commands

# Search libraries by name
context7 library react
context7 lib axum "middleware"          # alias + semantic context
context7 search tokio "mpsc channel"   # alias + semantic context

# Fetch documentation
context7 docs /reactjs/react.dev
context7 docs /tokio-rs/tokio --query "spawn_blocking" --text
context7 docs /tokio-rs/tokio -q "spawn_blocking" --text   # -q is short for --query
context7 doc  /rust-lang/rust --query "lifetimes" --json

# Manage API keys
context7 keys add ctx7sk-...           # add a key
context7 keys list                     # list saved keys (masked)
context7 keys remove 2                 # remove by 1-based index
context7 keys clear --yes              # remove all keys
context7 keys path                     # show config file path
context7 keys export                   # export to .env format
context7 keys import .env              # import from .env file
# Key rotation is automatic — every request shuffles keys randomly.

Output formats

Flag Description Best for
(none) Colored, human-readable Terminal reading
--json Pretty-printed JSON Scripts, pipes, jaq
--text Plain text (docs only) LLM context, rg pipelines
--lang en|pt Force UI language Multilingual workflows

Language selection (v0.2.0+)

# Force English output
context7 --lang en library react

# Force Portuguese output
context7 --lang pt docs /reactjs/react.dev --query "hooks"

# Permanent override via environment variable
export CONTEXT7_LANG=en
context7 library react    # always English from now on

Auto-detect order: --lang flag → CONTEXT7_LANG env var → system locale → English (default).

What's new in v0.2.9

  • CI fix: removed a redundant import that was causing CI failure on all platforms
  • Docs: documented keys list --json output in HOW_TO_USE.md
  • Deps: merged Dependabot updates for GitHub Actions artifacts (upload v7, download v8)

What's new in v0.2.8

A release pipeline overhaul plus input validation improvements.

Input validation (runtime changes):

  • Empty key rejectionkeys add now rejects empty strings with exit code 1 instead of silently storing them
  • Format warning — keys missing the ctx7sk- prefix emit a non-blocking stderr warning
  • keys list --json — the keys list subcommand now supports --json for scripting (e.g., context7 keys list --json | jaq 'length')
  • Path traversal logging — invalid CONTEXT7_HOME values (containing ..) now emit a tracing::warn diagnostic

CI + Packaging:

  • Automatic release builds — tags like v0.2.8 now trigger the full release pipeline automatically (previously required manual workflow_dispatch for every release)
  • Flatpak bundles.flatpak artifacts shipped with every GitHub Release (install via flatpak install --user)
  • Snap packages.snap artifacts shipped with every GitHub Release
  • macOS ARM runner migration — removed deprecated macos-13 from CI/release workflows; Intel x86_64 binary produced via cross-compile (rustup target add x86_64-apple-darwin) on the ARM runner; Universal Binary via lipo as before
  • Cross-platform documentation — new docs/CROSS_PLATFORM.md with per-platform installation, behavior differences, and troubleshooting (Windows UTF-8, macOS Gatekeeper, Linux FHS + musl + Flatpak + Snap)

See CHANGELOG.md for full details.

What's new in v0.2.7 (CI/Build Patch)

A CI-only patch that restores the green build pipeline after v0.2.6. Zero functional changes — the binary behavior is identical to v0.2.6.

  • Fixed MSRV job by pinning assert_cmd = "=2.1.2" (last edition2021-compatible version)
  • Fixed coverage gate to ignore structural dispatcher files (src/cli.rs, src/lib.rs, src/main.rs)
  • Fixed release workflow startup failure by unifying Apple codesign steps (GitHub Actions secrets context is not available in step.if)

If you're already on v0.2.6, upgrading is optional — purely a housekeeping release.

What's new in v0.2.6

  • keys remove exit code fixed — now returns exit code 1 on invalid index or empty storage (was 0)
  • --lang respected on "no API key" error — message is no longer hardcoded in Portuguese
  • keys list timestamps — now displayed as YYYY-MM-DD HH:MM:SS instead of full RFC3339 nanosecond strings
  • Path traversal regression test — explicit test confirms CONTEXT7_HOME=../../../etc is rejected

See CHANGELOG.md for full details.

Release notes

  • v0.2.8 — Input validation + CI/Packaging: empty key rejection (exit code 1), ctx7sk- format warning, keys list --json, path traversal logging. Plus: automatic release builds on tag push, Flatpak + Snap artifacts, macOS ARM runner migration, docs/CROSS_PLATFORM.md. See CHANGELOG.md for full details.
  • v0.2.7 — CI/Build patch: MSRV job restored by pinning assert_cmd = "=2.1.2", coverage gate excludes structural dispatchers, release workflow startup failure fixed (GitHub Actions secrets context not available in step.if). Zero runtime changes — binary identical to v0.2.6. See CHANGELOG.md for full details.
  • v0.2.6 — Backlog cleanup: keys remove exit code fix (B3), --lang respected on key-missing error (B2), compact timestamp display in keys list (B4), path traversal regression test (LOW-01). See CHANGELOG.md for full details.
  • v0.2.5 — Cross-platform total: CONTEXT7_HOME env var, Alpine musl CI, Universal Binary macOS, Flatpak/Snap manifests, prebuilt artifacts, CI coverage gate (80%), 18 storage tests isolated, MSRV lockfile fix. See CHANGELOG.md for full details.
  • v0.2.4 — Cross-platform perfection: Windows UTF-8/ANSI fixes, keys clear accepts yes, CI matrix (Linux/macOS/Windows), cargo-deny config, docs polish (5 attempts, /reactjs/react.dev, TOC, Step 4 format). See CHANGELOG.md for full details.
  • v0.2.3 — UX polish: library-not-found hint, bilingual --help parameter names (EN), improved library list format (title bold + trust inline), tagline updated. See CHANGELOG.md for full details.
  • v0.2.2 — Documentation polish + HTTP 404 handling: dedicated error for missing libraries (no more misleading "No valid API key" message), cleaned up legacy trust_score/source_urls/keys rotate references across all docs.
  • v0.2.1 — Bugfix release: fixed docs endpoint schema, fixed --text output, fixed trustScore parsing, improved retry logic.
  • v0.2.0 — Bilingual UI (EN/PT), public library API, modular architecture, docs/ directory.
  • v0.1.0 — Initial release.

Full documentation

See docs/HOW_TO_USE.md for a complete step-by-step guide covering Linux, macOS, and Windows.

For LLM integration patterns, see docs/context7-skill.md and docs/context7-llm-rules.md.

  • Cross-platform guide — Windows, macOS, Linux compatibility details (UTF-8, ANSI colors, Gatekeeper, musl, Flatpak, Snap)

Português

O que é o context7-cli?

Pesquise a documentação de qualquer biblioteca no terminal — sem runtime, resultados instantâneos.

Por que usar?

  1. Binário único — um arquivo só, zero dependências de runtime (sem Node/Python)
  2. Cross-platform — Linux, macOS e Windows com comportamento idêntico
  3. Armazenamento XDG — chaves de API salvas com segurança em ~/.config/context7/config.toml com chmod 600 (ou equivalente do OS)
  4. Rotação multi-chave — múltiplas chaves de API com shuffle automático e retry com backoff exponencial (500ms → 1s → 2s, até 5 tentativas)
  5. Interface bilíngue — saída em inglês e português brasileiro (v0.2.0+)
  6. Privacidade em primeiro lugar — sem telemetria, sem analytics, sem coleta de dados; chaves mascaradas em todos os logs e no output de list
  7. Tratamento estruturado de erros — zero unwrap() em produção; todo caminho de erro retorna mensagem amigável ao usuário
  8. Múltiplos formatos de saída — colorido legível para humanos, --json para pipes/scripts, --text para contexto de LLM

Instalação rápida

Linux / macOS (via Cargo):

cargo install context7-cli
context7 --help

Windows (via Cargo + rustup):

# Instale o Rust em https://rustup.rs primeiro, depois:
cargo install context7-cli
context7 --help

Build a partir do fonte:

git clone https://github.com/daniloaguiarbr/context7-cli
cd context7-cli
cargo build --release
./target/release/context7 --help

O crate está publicado no crates.io como context7-cli. O binário instalado é context7 (sem o sufixo -cli).

Sem toolchain Rust? Baixe um binário pré-compilado para o seu OS na página de Releases do GitHub (Linux gnu/musl tar.gz, Windows zip, Universal Binary macOS).

Primeira execução

# Passo 1 — Adicione sua chave de API (obtenha em https://context7.com)
context7 keys add ctx7sk-SUA-CHAVE-AQUI

# Passo 2 — Verifique se foi salva
context7 keys list

# Passo 3 — Busque uma biblioteca
context7 library react

# Passo 4 — Busque documentação
context7 docs /reactjs/react.dev --query "useEffect e cleanup"

Comandos principais

# Buscar bibliotecas por nome
context7 library react
context7 lib axum "middleware"          # alias + contexto semântico
context7 search tokio "canal mpsc"     # alias + contexto semântico

# Buscar documentação
context7 docs /reactjs/react.dev
context7 docs /tokio-rs/tokio --query "spawn_blocking" --text
context7 docs /tokio-rs/tokio -q "spawn_blocking" --text   # -q é alias de --query
context7 doc  /rust-lang/rust --query "lifetimes" --json

# Gerenciar chaves de API
context7 keys add ctx7sk-...           # adicionar chave
context7 keys list                     # listar chaves salvas (mascaradas)
context7 keys remove 2                 # remover por índice 1-based
context7 keys clear --yes              # remover todas as chaves
context7 keys path                     # exibir caminho do arquivo config
context7 keys export                   # exportar em formato .env
context7 keys import .env              # importar de arquivo .env
# A rotação de chaves é automática — cada requisição embaralha as chaves aleatoriamente.

Formatos de saída

Flag Descrição Melhor para
(nenhuma) Colorido, legível por humanos Leitura no terminal
--json JSON pretty-printed Scripts, pipes, jaq
--text Texto plano (apenas docs) Contexto de LLM, pipelines com rg
--lang en|pt Forçar idioma da interface Fluxos multilíngues

Seleção de idioma (v0.2.0+)

# Forçar saída em inglês
context7 --lang en library react

# Forçar saída em português
context7 --lang pt docs /reactjs/react.dev --query "hooks"

# Override permanente via variável de ambiente
export CONTEXT7_LANG=pt
context7 library react    # sempre em português a partir de agora

Ordem de detecção: flag --lang → variável CONTEXT7_LANG → locale do sistema → inglês (padrão).

Novidades v0.2.9

  • Fix CI: removido import redundante que causava falha de CI em todas as plataformas
  • Docs: documentado saída keys list --json no HOW_TO_USE.md
  • Deps: merge de atualizações Dependabot para artifacts do GitHub Actions (upload v7, download v8)

Novidades v0.2.8

Uma reformulação da pipeline de release mais melhorias de validação de entrada.

Validação de entrada (mudanças em runtime):

  • Rejeição de chave vaziakeys add agora rejeita strings vazias com exit code 1 em vez de armazená-las silenciosamente
  • Aviso de formato — chaves sem o prefixo ctx7sk- emitem um aviso não-bloqueante no stderr
  • keys list --json — o subcomando keys list agora suporta --json para automação (ex.: context7 keys list --json | jaq 'length')
  • Log de path traversal — valores inválidos de CONTEXT7_HOME (contendo ..) agora emitem um diagnóstico tracing::warn

CI + Packaging:

  • Builds automáticos de release — tags como v0.2.8 agora disparam a pipeline completa automaticamente (antes era necessário workflow_dispatch manual para cada release)
  • Bundles Flatpak — artefatos .flatpak incluídos em cada GitHub Release (instale via flatpak install --user)
  • Pacotes Snap — artefatos .snap incluídos em cada GitHub Release
  • Migração para runner ARM no macOS — runner macos-13 deprecado removido; binário Intel x86_64 produzido por cross-compilação (rustup target add x86_64-apple-darwin) no runner ARM; Universal Binary via lipo como antes
  • Documentação cross-platform — novo docs/CROSS_PLATFORM.md com instalação, diferenças de comportamento e troubleshooting por plataforma (Windows UTF-8, Gatekeeper macOS, Linux FHS + musl + Flatpak + Snap)

Veja CHANGELOG.md para detalhes completos.

Novidades v0.2.7 (Patch CI/Build)

Um patch apenas de CI que restaura a esteira de build verde após v0.2.6. Zero mudanças funcionais — o comportamento do binário é idêntico a v0.2.6.

  • Corrigido o job MSRV pinando assert_cmd = "=2.1.2" (última versão compatível com edition2021)
  • Corrigido o gate de cobertura para ignorar arquivos de dispatcher estrutural (src/cli.rs, src/lib.rs, src/main.rs)
  • Corrigido o startup failure do workflow de release unificando os steps de codesign da Apple (contexto secrets do GitHub Actions não está disponível em step.if)

Se você já está na v0.2.6, o upgrade é opcional — é puramente um release de limpeza.

Novidades na v0.2.6

  • Exit code de keys remove corrigido — agora retorna exit code 1 em índice inválido ou storage vazio (antes era 0)
  • --lang respeitado no erro "nenhuma chave de API" — mensagem não é mais hardcoded em português
  • Timestamps em keys list — agora exibidos como AAAA-MM-DD HH:MM:SS em vez de strings RFC3339 com nanosegundos
  • Teste de regressão para path traversal — teste explícito confirma que CONTEXT7_HOME=../../../etc é rejeitado

Veja CHANGELOG.md para detalhes completos.

Notas de release

  • v0.2.8 — Validação de entrada + CI/Packaging: rejeição de chave vazia (exit code 1), aviso de formato ctx7sk-, keys list --json, log de path traversal. Mais: builds automáticos em push de tag, artefatos Flatpak + Snap, migração para runner ARM no macOS, docs/CROSS_PLATFORM.md. Veja CHANGELOG.md para detalhes completos.
  • v0.2.7 — Patch CI/Build: job MSRV restaurado pinando assert_cmd = "=2.1.2", gate de cobertura exclui dispatchers estruturais, startup failure do workflow de release corrigido (contexto secrets do GitHub Actions não está disponível em step.if). Zero mudanças em runtime — binário idêntico a v0.2.6. Veja CHANGELOG.md para detalhes completos.
  • v0.2.6 — Limpeza de backlog: correção de exit code em keys remove (B3), --lang respeitado no erro de chave ausente (B2), exibição compacta de timestamp em keys list (B4), teste de regressão para path traversal (LOW-01). Veja CHANGELOG.md para detalhes completos.
  • v0.2.5 — Cross-platform total: variável CONTEXT7_HOME, CI musl Alpine, Universal Binary macOS, manifestos Flatpak/Snap, artefatos pré-compilados, gate de cobertura CI (80%), 18 testes de storage isolados, correção do lockfile MSRV. Veja CHANGELOG.md para detalhes completos.
  • v0.2.4 — Perfeição cross-platform: correções UTF-8/ANSI no Windows, keys clear aceita yes, pipeline CI (Linux/macOS/Windows), configuração cargo-deny, polish de docs (5 tentativas, /reactjs/react.dev, sumário, formato do Passo 4). Veja CHANGELOG.md para detalhes completos.
  • v0.2.3 — Polish de UX: dica para biblioteca não encontrada, nomes de parâmetros no --help em inglês, novo formato de lista de bibliotecas (título em destaque + confiança inline), tagline atualizada. Veja CHANGELOG.md para detalhes completos.
  • v0.2.2 — Polish de documentação + handling de HTTP 404: erro dedicado para bibliotecas inexistentes (sem a mensagem enganosa "Nenhuma chave válida"), limpeza de referências legadas a trust_score/source_urls/keys rotate em todos os docs.
  • v0.2.1 — Release de correção: corrigido schema do endpoint docs, corrigido output --text, corrigido parsing de trustScore, melhorada lógica de retry.
  • v0.2.0 — Interface bilíngue (EN/PT), API pública de biblioteca, arquitetura modular, diretório docs/.
  • v0.1.0 — Lançamento inicial.

Documentação completa

Veja docs/HOW_TO_USE.md para um guia passo a passo completo cobrindo Linux, macOS e Windows.

Para padrões de integração com LLM, veja docs/context7-skill.md e docs/context7-llm-rules.md.

  • Guia cross-platform — detalhes de compatibilidade Windows, macOS, Linux (UTF-8, cores ANSI, Gatekeeper, musl, Flatpak, Snap)

License

Dual-licensed under MIT OR Apache-2.0, at your choice.

Copyright 2026 Danilo Aguiar <daniloaguiarbr@pm.me>