context7-cli 0.2.7

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

[![Crates.io](https://img.shields.io/crates/v/context7-cli)](https://crates.io/crates/context7-cli)
[![docs.rs](https://img.shields.io/docsrs/context7-cli)](https://docs.rs/context7-cli)
[![CI](https://github.com/daniloaguiarbr/context7-cli/actions/workflows/ci.yml/badge.svg)](https://github.com/daniloaguiarbr/context7-cli/actions/workflows/ci.yml)
[![License](https://img.shields.io/badge/license-MIT%20OR%20Apache--2.0-blue)](https://github.com/daniloaguiarbr/context7-cli#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):**

```bash
cargo install context7-cli
context7 --help
```

**Windows (via Cargo + rustup):**

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

**Build from source:**

```bash
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]https://github.com/daniloaguiarbr/context7-cli/releases/latest (Linux gnu/musl tar.gz, Windows zip, macOS Universal Binary).

### First run

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

```bash
# 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+)

```bash
# 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.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](CHANGELOG.md) for full details.

### Release notes

- **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]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]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]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]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]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`](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`](docs/context7-skill.md) and [`docs/context7-llm-rules.md`](docs/context7-llm-rules.md).

---

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

```bash
cargo install context7-cli
context7 --help
```

**Windows (via Cargo + rustup):**

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

**Build a partir do fonte:**

```bash
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]https://github.com/daniloaguiarbr/context7-cli/releases/latest (Linux gnu/musl tar.gz, Windows zip, Universal Binary macOS).

### Primeira execução

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

```bash
# 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+)

```bash
# 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.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](CHANGELOG.md) para detalhes completos.

### Notas de release

- **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]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]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]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]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]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`](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`](docs/context7-skill.md) e [`docs/context7-llm-rules.md`](docs/context7-llm-rules.md).

---

## License

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

- [LICENSE-MIT]LICENSE-MIT
- [LICENSE-APACHE]LICENSE-APACHE

Copyright 2026 Danilo Aguiar <daniloaguiarbr@pm.me>