context7-cli
English
Search any library's docs from your terminal — one binary, zero runtime, instant results.
What is context7-cli?
context7-cli queries the Context7 REST API directly from your shell. No Node, no Python, no daemon. One static binary that installs in seconds and works identically on Linux, macOS, and Windows.
Key properties:
- Single binary — zero runtime dependencies, ships as a static executable
- XDG-compliant storage — API keys stored in
~/.config/context7/config.tomlwithchmod 600 - Multi-key rotation — automatic shuffle with exponential backoff retry (500ms → 1s → 2s, up to 5 attempts)
- Bilingual UI — English and Brazilian Portuguese output, auto-detected from system locale
- Privacy-first — no telemetry, no analytics; keys are masked in all logs and list output
- Structured output — colored terminal,
--jsonfor pipes,--textfor LLM context windows
Why context7-cli?
- Zero context switching — stay in your terminal, no browser tabs needed
- Pipe-friendly —
--textoutput feeds directly into LLMs, scripts, and pipelines - Works over SSH — full functionality on headless servers and remote machines
- CI/CD native — set
CONTEXT7_API_KEYSand use it in any automation workflow
Quick Start (30 seconds)
# 1 — Install
# 2 — Add your API key (get one at https://context7.com)
# 3 — Search a library
Expected output:
Libraries found:
────────────────────────────────────────────────────────────
1. React (trust 10.0/10)
/reactjs/react.dev
React.dev is the official documentation website for React...
# 4 — Fetch documentation
No Rust toolchain? Download a prebuilt binary from the GitHub Releases page (Linux gnu/musl, Windows zip, macOS Universal Binary).
Commands
Search Libraries
Aliases: library, lib, search are equivalent.
Fetch Documentation
Use --text to pipe clean prose directly into an LLM context window. Use --json to process with jaq or scripts.
Key Management
| Command | Description |
|---|---|
context7 keys add ctx7sk-... |
Add an API key |
context7 keys list |
List saved keys (masked) |
context7 keys list --json |
List keys as JSON array |
context7 keys remove 2 |
Remove key 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, no markup (docs only) | LLM context windows |
--lang en|pt |
Force UI language | Multilingual workflows |
Environment Variables
| Variable | Description | Example |
|---|---|---|
CONTEXT7_API_KEYS |
Comma-separated keys (overrides config file) | ctx7sk-key1,ctx7sk-key2 |
CONTEXT7_HOME |
Override XDG config directory | $HOME/.dotfiles/context7 |
CONTEXT7_LANG |
Force UI language | en or pt |
RUST_LOG |
Log verbosity | warn, info, debug, trace |
Language auto-detect order: --lang flag → CONTEXT7_LANG → system locale → English.
Integration Patterns
# Pipe documentation into an LLM prompt
|
# Extract library IDs for scripting
|
# Search documentation with ripgrep
|
# Loop over multiple libraries
for; do
|
done
# CI/CD — no config file needed
CONTEXT7_API_KEYS="ctx7sk-key-01"
Quick Reference
| Operation | Command |
|---|---|
| Search library | context7 library NAME [CONTEXT] |
| Fetch docs | context7 docs ID [-q TEXT] [--text|--json] |
| Add key | context7 keys add ctx7sk-... |
| List keys | context7 keys list [--json] |
| Remove key | context7 keys remove N |
| Clear all keys | context7 keys clear --yes |
| Config path | context7 keys path |
| Export keys | context7 keys export |
| Import keys | context7 keys import FILE |
| Force language | context7 --lang en|pt COMMAND |
| Shell completions | context7 completions bash|zsh|fish|powershell|elvish |
Shell Completions
# Bash
# Zsh (add ~/.zfunc to fpath in .zshrc first)
# Fish
# PowerShell (add to $PROFILE)
# Elvish
Exit Codes
| Code | Meaning | Example |
|---|---|---|
0 |
Success | Successful search, key added, completions generated |
1 |
Operation error | No API keys configured, empty key, invalid index, API 404 |
2 |
Usage error (clap) | Unknown subcommand, conflicting flags (--text + --json) |
Troubleshooting
command not found: context7
Add ~/.cargo/bin to your PATH: export PATH="$HOME/.cargo/bin:$PATH"
"No API key configured"
Run context7 keys add ctx7sk-YOUR-KEY or set CONTEXT7_API_KEYS env var.
"Library not found" (404)
The library ID must come from context7 library NAME. Copy the /org/repo path from the search results, not from GitHub.
Rate limited (429)
The CLI retries automatically with exponential backoff (up to 5 attempts). Add a second key with context7 keys add to increase throughput.
macOS Gatekeeper blocks the binary
Run: xattr -d com.apple.quarantine context7 && chmod +x context7
Or install via cargo install context7-cli to bypass Gatekeeper entirely.
No colors in terminal
Use --text for plain output, or verify your terminal supports ANSI escape sequences.
--text and --json together give an error
These flags are mutually exclusive. Use one or the other: context7 docs /org/repo --text or context7 docs /org/repo --json.
keys remove 0 gives "Invalid index"
Indices are 1-based. Run context7 keys list first to see the current indices, then use context7 keys remove <N> with N ≥ 1.
context7 library without arguments gives an error
The library name is required. Provide a search term: context7 library react
What's New in v0.4.3
- 70/70 empirical QA tests passed — every command, alias, flag, env var, and edge case from HOW_TO_USE.md validated end-to-end on a live system with real API keys and isolated temp directories.
- Snap & Flatpak CI fixes —
snapcraft.yamlbuild-attributes format corrected (snapcraft 8.x requires list of strings),flatpak-builderremoved non-existent--allow-networkflag. - Resilient release pipeline — Snap/Flatpak failures no longer block binary releases for all platforms.
- Shell completions —
context7 completions bash|zsh|fish|powershell|elvishgenerates shell-specific completion scripts. Install once, tab-complete forever. - Dynamic user-agent — HTTP requests include the exact version from
Cargo.tomlautomatically.
See CHANGELOG.md for the complete history.
Full Documentation
- HOW_TO_USE.md — step-by-step guide for Linux, macOS, and Windows
- CROSS_PLATFORM.md — Windows UTF-8, macOS Gatekeeper, Linux musl/Flatpak/Snap, NixOS, GNU Guix
- context7-skill.md — LLM integration patterns
- context7-llm-rules.md — system prompt rules for AI assistants
Português
Pesquise a documentação de qualquer biblioteca no terminal — um binário, sem runtime, resultados instantâneos.
O que é o context7-cli?
O context7-cli consulta a API REST do Context7 diretamente do seu shell. Sem Node, sem Python, sem daemon. Um único binário estático que instala em segundos e funciona de forma idêntica no Linux, macOS e Windows.
Propriedades principais:
- Binário único — zero dependências de runtime, distribuído como executável estático
- Armazenamento XDG — chaves de API salvas em
~/.config/context7/config.tomlcomchmod 600 - Rotação multi-chave — shuffle automático com retry e backoff exponencial (500ms → 1s → 2s, até 5 tentativas)
- Interface bilíngue — saída em inglês e português brasileiro, detectado automaticamente pelo locale do sistema
- Privacidade em primeiro lugar — sem telemetria, sem analytics; chaves mascaradas em todos os logs e no output de listagem
- Saída estruturada — colorido para terminal,
--jsonpara pipes,--textpara janelas de contexto de LLM
Por que o context7-cli?
- Zero troca de contexto — fique no terminal, sem abas de browser
- Amigável para pipes — saída
--textalimenta LLMs, scripts e pipelines diretamente - Funciona via SSH — funcionalidade completa em servidores headless e máquinas remotas
- Nativo para CI/CD — configure
CONTEXT7_API_KEYSe use em qualquer workflow de automação
Início Rápido (30 segundos)
# 1 — Instalar
# 2 — Adicionar sua chave de API (obtenha em https://context7.com)
# 3 — Buscar uma biblioteca
Saída esperada:
Bibliotecas encontradas:
────────────────────────────────────────────────────────────
1. React (confiança 10.0/10)
/reactjs/react.dev
React.dev é o site oficial de documentação do React...
# 4 — Buscar documentação
Sem toolchain Rust? Baixe um binário pré-compilado na página de Releases do GitHub (Linux gnu/musl, Windows zip, Universal Binary macOS).
Comandos
Buscar Bibliotecas
Aliases: library, lib, search são equivalentes.
Buscar Documentação
Use --text para enviar prosa limpa diretamente para a janela de contexto de um LLM. Use --json para processar com jaq ou scripts.
Gerenciamento de Chaves
| Comando | Descrição |
|---|---|
context7 keys add ctx7sk-... |
Adicionar uma chave de API |
context7 keys list |
Listar chaves salvas (mascaradas) |
context7 keys list --json |
Listar chaves como array JSON |
context7 keys remove 2 |
Remover chave por índice 1-based |
context7 keys clear --yes |
Remover todas as chaves |
context7 keys path |
Exibir caminho do arquivo de configuração |
context7 keys export |
Exportar no 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, sem marcação (apenas docs) |
Janelas de contexto de LLM |
--lang en|pt |
Forçar idioma da interface | Fluxos multilíngues |
Variáveis de Ambiente
| Variável | Descrição | Exemplo |
|---|---|---|
CONTEXT7_API_KEYS |
Chaves separadas por vírgula (substitui o arquivo de configuração) | ctx7sk-chave1,ctx7sk-chave2 |
CONTEXT7_HOME |
Override do diretório de configuração XDG | $HOME/.dotfiles/context7 |
CONTEXT7_LANG |
Forçar idioma da interface | en ou pt |
RUST_LOG |
Verbosidade de log | warn, info, debug, trace |
Ordem de detecção de idioma: flag --lang → CONTEXT7_LANG → locale do sistema → inglês.
Padrões de Integração
# Enviar documentação para um LLM
|
# Extrair IDs de biblioteca para scripts
|
# Buscar na documentação com ripgrep
|
# Iterar sobre múltiplas bibliotecas
for; do
|
done
# CI/CD — sem arquivo de configuração necessário
CONTEXT7_API_KEYS="ctx7sk-chave-01"
Referência Rápida
| Operação | Comando |
|---|---|
| Buscar biblioteca | context7 library NOME [CONTEXTO] |
| Buscar docs | context7 docs ID [-q TEXTO] [--text|--json] |
| Adicionar chave | context7 keys add ctx7sk-... |
| Listar chaves | context7 keys list [--json] |
| Remover chave | context7 keys remove N |
| Limpar todas as chaves | context7 keys clear --yes |
| Caminho da configuração | context7 keys path |
| Exportar chaves | context7 keys export |
| Importar chaves | context7 keys import ARQUIVO |
| Forçar idioma | context7 --lang en|pt COMANDO |
| Autocompletar | context7 completions bash|zsh|fish|powershell|elvish |
Autocompletar no Shell
# Bash
# Zsh (adicione ~/.zfunc ao fpath no .zshrc primeiro)
# Fish
# PowerShell (adicione ao $PROFILE)
# Elvish
Códigos de Saída
| Código | Significado | Exemplo |
|---|---|---|
0 |
Sucesso | Busca realizada, chave adicionada, completions geradas |
1 |
Erro de operação | Sem chaves configuradas, chave vazia, índice inválido, API 404 |
2 |
Erro de uso (clap) | Subcomando desconhecido, flags conflitantes (--text + --json) |
Resolução de Problemas
command not found: context7
Adicione ~/.cargo/bin ao seu PATH: export PATH="$HOME/.cargo/bin:$PATH"
"Nenhuma chave de API configurada"
Execute context7 keys add ctx7sk-SUA-CHAVE ou defina a variável CONTEXT7_API_KEYS.
"Biblioteca não encontrada" (404)
O ID da biblioteca deve vir de context7 library NOME. Copie o caminho /org/repo dos resultados da busca, não do GitHub.
Rate limit (429)
A CLI faz retry automaticamente com backoff exponencial (até 5 tentativas). Adicione uma segunda chave com context7 keys add para aumentar o throughput.
macOS Gatekeeper bloqueia o binário
Execute: xattr -d com.apple.quarantine context7 && chmod +x context7
Ou instale via cargo install context7-cli para contornar o Gatekeeper completamente.
Sem cores no terminal
Use --text para saída sem marcação, ou verifique se o terminal suporta escape sequences ANSI.
--text e --json juntos causam erro
Essas flags são mutuamente exclusivas. Use uma ou outra: context7 docs /org/repo --text ou context7 docs /org/repo --json.
keys remove 0 retorna "Índice inválido"
Os índices são 1-based. Execute context7 keys list primeiro para ver os índices atuais, depois use context7 keys remove <N> com N ≥ 1.
context7 library sem argumentos retorna erro
O nome da biblioteca é obrigatório. Forneça um termo de busca: context7 library react
Novidades na v0.4.3
- 70/70 testes empíricos QA aprovados — cada comando, alias, flag, variável de ambiente e edge case do HOW_TO_USE.md validado end-to-end em sistema real com chaves de API reais e diretórios temporários isolados.
- Correções Snap & Flatpak CI — formato
build-attributesdosnapcraft.yamlcorrigido (snapcraft 8.x exige lista de strings), flag--allow-networkinexistente removida doflatpak-builder. - Pipeline de release resiliente — falhas do Snap/Flatpak não bloqueiam mais releases de binários para todas as plataformas.
- Shell completions —
context7 completions bash|zsh|fish|powershell|elvishgera scripts de autocompletar para cada shell. Instale uma vez, use tab para sempre. - User-agent dinâmico — requisições HTTP incluem a versão exata do
Cargo.tomlautomaticamente.
Veja CHANGELOG.md para o histórico completo.
Documentação Completa
- HOW_TO_USE.md — guia passo a passo para Linux, macOS e Windows
- CROSS_PLATFORM.md — Windows UTF-8, Gatekeeper macOS, Linux musl/Flatpak/Snap, NixOS, GNU Guix
- context7-skill.md — padrões de integração com LLM
- context7-llm-rules.md — regras de system prompt para assistentes de IA
License
Dual-licensed under MIT OR Apache-2.0, at your choice.
Copyright 2026 Danilo Aguiar <daniloaguiarbr@pm.me>