context7-cli 0.2.0

CLI client for the Context7 API — search libraries and documentation from the terminal
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
# How to use context7-cli / Como usar context7-cli

---

## English

`context7-cli` is a native Rust CLI that queries the [Context7](https://context7.com) REST API to search library documentation from your terminal. This guide covers installation on Linux, macOS, and Windows, plus complete usage examples and LLM integration patterns.

---

### Step 1 — Download & Install

#### Linux

**Option A — Recommended: via `cargo install`**

```bash
# Requires Rust toolchain (https://rustup.rs)
cargo install context7-cli
```

**Option B — Build from source**

```bash
git clone https://github.com/daniloaguiarbr/context7-cli
cd context7-cli
cargo build --release
sudo cp target/release/context7 /usr/local/bin/context7
# or without sudo:
cp target/release/context7 ~/.local/bin/context7
```

**Verify installation:**

```bash
context7 --help
```

#### macOS

**Option A — Recommended: via `cargo install`**

```bash
# Install Rust from https://rustup.rs if needed
cargo install context7-cli
```

The binary is placed in `~/.cargo/bin/context7`. Ensure `~/.cargo/bin` is in your `PATH` (added automatically by rustup).

**Option B — Build from source**

```bash
git clone https://github.com/daniloaguiarbr/context7-cli
cd context7-cli
cargo build --release
cp target/release/context7 /usr/local/bin/context7
```

**Verify installation:**

```bash
context7 --help
```

#### Windows

**Option A — Recommended: via `cargo install` (PowerShell)**

```powershell
# 1. Install Rust from https://rustup.rs (64-bit installer)
# 2. Open a new PowerShell window, then:
cargo install context7-cli
```

The binary is placed at `%USERPROFILE%\.cargo\bin\context7.exe`. Rustup adds this to `PATH` automatically.

**Verify installation (PowerShell):**

```powershell
context7 --help
```

**Option B — Build from source (PowerShell)**

```powershell
git clone https://github.com/daniloaguiarbr/context7-cli
cd context7-cli
cargo build --release
# Binary at: target\release\context7.exe
# Copy to a directory in your PATH:
copy target\release\context7.exe $env:USERPROFILE\.cargo\bin\
```

---

### Step 2 — Get your Context7 API key

1. Go to [https://context7.com]https://context7.com
2. Sign up or log in
3. Navigate to your account settings or API section
4. Generate a new API key — it starts with `ctx7sk-`
5. Copy the full key (you will only see it once)

---

### Step 3 — Add the API key

```bash
context7 keys add ctx7sk-YOUR-KEY-HERE
```

**Verify it was stored:**

```bash
context7 keys list
# Output: 1. ctx7sk-YOUR...HERE (added on 2026-04-08)

context7 keys path
# Output: /home/you/.config/context7/config.toml
```

**Storage location by OS:**

| OS | Path |
|----|------|
| Linux | `~/.config/context7/config.toml` |
| macOS | `~/Library/Application Support/context7/config.toml` |
| Windows | `%APPDATA%\context7\config\config.toml` |

Permissions: `600` on Unix (owner read/write only) — set automatically.

**Alternative — environment variable (CI/CD, no file needed):**

```bash
export CONTEXT7_API_KEYS="ctx7sk-key-01,ctx7sk-key-02"
context7 library react
```

**Supported environment variables:**

| Variable | Purpose |
|----------|---------|
| `CONTEXT7_API_KEYS` | Comma-separated API keys (overrides config file) |
| `CONTEXT7_LANG` | UI language: `en` or `pt` |
| `CONTEXT7_HOME` | Alternative XDG config directory (mainly for tests) |
| `RUST_LOG` | Log level: `error`, `warn`, `info`, `debug`, `trace` |

**Full key discovery hierarchy (precedence order):**

| Priority | Source | Format |
|----------|--------|--------|
| 1 (highest) | `CONTEXT7_API_KEYS` env var | Comma-separated keys |
| 2 | XDG config (`~/.config/context7/config.toml`) | TOML |
| 3 | `.env` file in current directory | `CONTEXT7_API=ctx7sk-...` |
| 4 (lowest) | Compile-time embed | `CONTEXT7_API_KEYS` at build time |

---

### Step 4 — Your first search

```bash
context7 library react
```

Example output:

```
Libraries found:
────────────────────────────────────────────────────────────
1. /facebook/react  React
   A JavaScript library for building user interfaces
   Trust: 9.8

2. /preactjs/preact  Preact
   Fast 3kB React alternative with the same modern API
   Trust: 8.1
```

**With semantic context for better ranking:**

```bash
context7 library react "effect hooks and state"
context7 library axum "middleware and routing"
context7 library tokio "async mpsc channel"
```

**Available aliases:** `lib`, `search`

```bash
context7 lib react
context7 search tokio
```

---

### Step 5 — Fetch documentation

Use the `id` from Step 4 (e.g. `/facebook/react`):

```bash
context7 docs /facebook/react --query "useEffect cleanup"
```

**Available aliases:** `doc`, `context`

```bash
context7 doc /rust-lang/rust --query "lifetimes and borrowing"
context7 context /tokio-rs/tokio --query "spawn_blocking"
```

**Flags for `docs`:**

| Flag | Description |
|------|-------------|
| `--query <TEXT>`, `-q <TEXT>` | Semantic search within the library docs |
| `--text` | Return plain text (no color, ideal for LLMs and pipes) |
| `--json` | Return structured JSON |

> `--text` and `--json` are mutually exclusive.

**Examples:**

```bash
# Human-readable (default)
context7 docs /facebook/react --query "useState"

# Plain text for LLM context
context7 docs /tokio-rs/tokio --query "spawn_blocking" --text

# JSON for scripting
context7 docs /axum-rs/axum --json
```

---

### Step 6 — Language override (v0.2.0+)

By default, `context7-cli` auto-detects your system language. You can override it at runtime:

```bash
# Force English output
context7 --lang en library react

# Force Portuguese output
context7 --lang pt docs /facebook/react --query "hooks"
```

**Permanent override via environment variable:**

```bash
# Set once in your shell profile (~/.bashrc, ~/.zshrc, etc.)
export CONTEXT7_LANG=en    # always English
export CONTEXT7_LANG=pt    # always Portuguese
```

**Auto-detect order:**

| Priority | Source | Example |
|----------|--------|---------|
| 1 (highest) | `--lang` CLI flag | `context7 --lang en library react` |
| 2 | `CONTEXT7_LANG` env var | `CONTEXT7_LANG=pt context7 ...` |
| 3 | System locale | `LANG=pt_BR.UTF-8` → Portuguese |
| 4 (default) | English fallback | (when locale is unrecognized) |

Any locale starting with `pt` (e.g., `pt_BR`, `pt_PT`) triggers Portuguese output automatically.

---

### Step 7 — Output formats

**Colored output (default):**

```
Documentation:
────────────────────────────────────────────────────────────
## useEffect

The useEffect hook lets you synchronize a component with an external system...

Sources:
  https://react.dev/reference/react/useEffect
```

**JSON output (`--json`):**

```json
{
  "id": "/facebook/react",
  "snippets": [
    {
      "content": "## useEffect\n\nThe useEffect hook...",
      "type": "markdown",
      "source_urls": ["https://react.dev/reference/react/useEffect"]
    }
  ]
}
```

**Library JSON output:**

```json
[
  {
    "id": "/facebook/react",
    "title": "React",
    "description": "A JavaScript library for building user interfaces",
    "trust_score": 9.8
  }
]
```

---

### Step 8 — Advanced: multi-key rotation

When you have multiple API keys, `context7-cli` rotates between them automatically to avoid rate limiting:

```bash
# Add multiple keys (one per command)
context7 keys add ctx7sk-primary-key
context7 keys add ctx7sk-secondary-key
context7 keys add ctx7sk-tertiary-key

context7 keys list
# Output:
# 1. ctx7sk-prim...key (added on 2026-04-08)
# 2. ctx7sk-seco...key (added on 2026-04-08)
# 3. ctx7sk-tert...key (added on 2026-04-08)
```

**How rotation works:**

- Each request randomly picks a key from the pool (shuffle without replacement)
- If a request fails (401/403/429/5xx/network error), the next attempt uses a different key
- Up to 3 attempts total with exponential backoff: 500ms → 1s → 2s
- With 3+ keys, rate limiting is practically eliminated

**Remove a specific key:**

```bash
context7 keys remove 2    # removes key at index 2 (1-based)
```

**Rotate to next key manually:**

```bash
context7 keys rotate      # advances the active key pointer to the next one
```

---

### Step 9 — Backup & restore

```bash
# Export all keys to .env format (plain text — protect this file!)
context7 keys export > ~/backup-context7.env

# Verify the export
cat ~/backup-context7.env
# Output: CONTEXT7_API=ctx7sk-full-value-here

# Wipe all stored keys
context7 keys clear --yes

# Restore from backup
context7 keys import ~/backup-context7.env
# Output: 3/3 key(s) imported successfully.

# Migrate from a legacy project .env file
context7 keys import /path/to/project/.env
```

---

### Troubleshooting

| Symptom | Cause | Solution |
|---------|-------|----------|
| `No API key found` | No key configured | Run `context7 keys add ctx7sk-...` |
| `401 Unauthorized` | Invalid or expired key | Check with `context7 keys list`, remove bad key, add a new one |
| `429 Too Many Requests` | Rate limit | The CLI retries automatically; add more keys for sustained workloads |
| `Network error / timeout` | No internet or slow connection | Check connectivity; CLI retries with backoff (30s timeout per attempt) |
| `command not found: context7` | Binary not in PATH | Ensure `~/.cargo/bin` (Linux/macOS) or `%USERPROFILE%\.cargo\bin` (Windows) is in PATH |
| `All API keys failed` | All keys are invalid | Run `context7 keys list`, remove invalid keys, add new ones from context7.com |

**View logs for detailed diagnostics:**

```bash
# Linux
bat -P ~/.local/state/context7/context7.log

# macOS
bat -P ~/Library/Application\ Support/context7/context7.log

# Dev mode (any OS)
bat -P logs/context7.log
```

**Increase log verbosity:**

```bash
RUST_LOG=context7=debug context7 library react
RUST_LOG=trace context7 docs /facebook/react --query "hooks"
```

---

### Integration examples

**With `jaq` (JSON parsing):**

```bash
# Get only library IDs
context7 library react --json | jaq '.[].id'

# Filter by trust score > 8
context7 library vue --json | jaq '[.[] | select(.trust_score > 8.0)]'

# Get the top result's ID
context7 library axum --json | jaq -r '.[0].id'
```

**With `rg` (search in documentation):**

```bash
# Search for a pattern in plain text docs
context7 docs /facebook/react --text | rg "useEffect"

# With 3-line context
context7 docs /rust-lang/rust --query "ownership" --text | rg -C 3 "borrow"
```

**Loop over results:**

```bash
for id in $(context7 library react --json | jaq -r '.[].id'); do
  echo "=== $id ==="
  context7 docs "$id" --query "getting started" --text
done
```

---

### System prompt for LLMs (English)

Copy-paste this into your LLM's system prompt to enable automatic documentation fetching:

```
You have access to the `context7` CLI to fetch up-to-date technical documentation for libraries and frameworks.

## Available tool: `context7`

### When to use
- When you need documentation for any library (React, Vue, Axum, Tokio, etc.)
- When the user asks about APIs, configuration, or usage of a specific library
- When your training data may be outdated for a particular library
- Before suggesting code that depends on external APIs

### How to use: three subcommands

#### Subcommand `library` — Discover a library's ID
```bash
context7 library <NAME> [OPTIONAL_CONTEXT]
```
- `NAME`: library name (e.g., `react`, `axum`, `tokio`, `vue`)
- `OPTIONAL_CONTEXT`: text to refine ranking (e.g., `"effect hooks"`)
- Returns: list of libraries with IDs, titles, and trust scores
- **Always use this subcommand first to get the correct ID**

Examples:
```bash
context7 library react "hooks and state"
context7 library axum "middleware and routing"
context7 library tokio "async channels"
```

#### Subcommand `docs` — Fetch documentation by ID
```bash
context7 docs <LIBRARY_ID> [--query <TEXT>] [--text]
```
- `LIBRARY_ID`: ID in `/org/repo` format obtained via `library` (e.g., `/facebook/react`)
- `--query <TEXT>`: specific topic to search (optional but recommended)
- `--text`: returns plain text (recommended for inserting into context)
- `--json`: returns structured JSON (incompatible with `--text`)

Examples:
```bash
context7 docs /facebook/react --query "useEffect and cleanup" --text
context7 docs /tokio-rs/tokio --query "spawn_blocking" --text
context7 docs /rust-lang/rust --query "lifetimes and borrowing" --text
```

### Correct 2-step workflow

**Step 1:** Discover the ID
```bash
context7 library react "effect hooks"
# → Returns: /facebook/react, /preactjs/preact, ...
```

**Step 2:** Fetch documentation with the correct ID
```bash
context7 docs /facebook/react --query "useEffect dependencies" --text
```

### Important rules
- **NEVER guess a LIBRARY_ID** — always use `library` first to obtain it
- `--text` and `--json` are mutually exclusive: use only one
- The `--json` flag is global and works with any subcommand
- If `library` returns no results, try name variations (e.g., `react` vs `reactjs`)
- 401/403 errors indicate a problem with the API key (check with `context7 keys list`)
- 429 errors indicate rate limiting: the CLI retries automatically

### Prerequisites
- API key configured via `context7 keys add <KEY>` (recommended)
- `context7` binary available in PATH
```

---

### System prompt for LLMs (Portuguese)

See [Section 9 below (Português)](#step-9--workflow-recomendado-para-llms) for the Portuguese version.

---

## Português

A CLI `context7-cli` é um binário Rust nativo que consulta a API REST pública do [Context7](https://context7.com) (`https://context7.com/api/v1`) para buscar documentação de bibliotecas diretamente no terminal. Este guia cobre instalação no Linux, macOS e Windows, além de exemplos completos de uso e padrões de integração com LLMs.

---

### Passo 1 — Download e Instalação

#### Linux

**Opção A — Recomendada: via `cargo install`**

```bash
# Requer Rust toolchain (https://rustup.rs)
cargo install context7-cli
```

**Opção B — Build a partir do fonte**

```bash
git clone https://github.com/daniloaguiarbr/context7-cli
cd context7-cli
cargo build --release
sudo cp target/release/context7 /usr/local/bin/context7
# ou sem sudo:
cp target/release/context7 ~/.local/bin/context7
```

**Verificar instalação:**

```bash
context7 --help
```

#### macOS

**Opção A — Recomendada: via `cargo install`**

```bash
# Instale o Rust em https://rustup.rs se necessário
cargo install context7-cli
```

O binário é colocado em `~/.cargo/bin/context7`. O rustup adiciona esse diretório ao `PATH` automaticamente.

**Opção B — Build a partir do fonte**

```bash
git clone https://github.com/daniloaguiarbr/context7-cli
cd context7-cli
cargo build --release
cp target/release/context7 /usr/local/bin/context7
```

**Verificar instalação:**

```bash
context7 --help
```

#### Windows

**Opção A — Recomendada: via `cargo install` (PowerShell)**

```powershell
# 1. Instale o Rust em https://rustup.rs (instalador 64-bit)
# 2. Abra um novo PowerShell e execute:
cargo install context7-cli
```

O binário é colocado em `%USERPROFILE%\.cargo\bin\context7.exe`. O rustup adiciona esse diretório ao `PATH` automaticamente.

**Verificar instalação (PowerShell):**

```powershell
context7 --help
```

**Opção B — Build a partir do fonte (PowerShell)**

```powershell
git clone https://github.com/daniloaguiarbr/context7-cli
cd context7-cli
cargo build --release
# Binário em: target\release\context7.exe
copy target\release\context7.exe $env:USERPROFILE\.cargo\bin\
```

---

### Passo 2 — Obter sua chave de API do Context7

1. Acesse [https://context7.com]https://context7.com
2. Cadastre-se ou faça login
3. Navegue até as configurações da conta ou seção de API
4. Gere uma nova chave de API — ela começa com `ctx7sk-`
5. Copie a chave completa (você só a verá uma vez)

---

### Passo 3 — Adicionar a chave de API

```bash
context7 keys add ctx7sk-SUA-CHAVE-AQUI
```

**Verificar se foi salva:**

```bash
context7 keys list
# Saída: 1. ctx7sk-SUA...QUI (adicionada em 2026-04-08)

context7 keys path
# Saída: /home/usuario/.config/context7/config.toml
```

**Localização do arquivo de configuração por OS:**

| OS | Caminho |
|----|---------|
| Linux | `~/.config/context7/config.toml` |
| macOS | `~/Library/Application Support/context7/config.toml` |
| Windows | `%APPDATA%\context7\config\config.toml` |

Permissões: `600` no Unix (leitura/escrita apenas do proprietário) — configuradas automaticamente.

**Alternativa — variável de ambiente (CI/CD, sem arquivo):**

```bash
export CONTEXT7_API_KEYS="ctx7sk-chave-01,ctx7sk-chave-02"
context7 library react
```

**Variáveis de ambiente suportadas:**

| Variável | Finalidade |
|----------|-----------|
| `CONTEXT7_API_KEYS` | Chaves de API separadas por vírgula (sobrepõe o arquivo de config) |
| `CONTEXT7_LANG` | Idioma da interface: `en` ou `pt` |
| `CONTEXT7_HOME` | Diretório XDG alternativo (principalmente para testes) |
| `RUST_LOG` | Nível de log: `error`, `warn`, `info`, `debug`, `trace` |

**Hierarquia completa de descoberta de chaves (ordem de precedência):**

| Prioridade | Fonte | Formato |
|------------|-------|---------|
| 1 (maior) | Variável de ambiente `CONTEXT7_API_KEYS` | Chaves separadas por vírgula |
| 2 | Config XDG (`~/.config/context7/config.toml`) | TOML |
| 3 | Arquivo `.env` no diretório atual | `CONTEXT7_API=ctx7sk-...` |
| 4 (menor) | Embutida em compile-time | `CONTEXT7_API_KEYS` no build |

---

### Passo 4 — Primeira busca

```bash
context7 library react
```

Exemplo de saída:

```
Bibliotecas encontradas:
────────────────────────────────────────────────────────────
1. /facebook/react  React
   A JavaScript library for building user interfaces
   Confiança: 9.8

2. /preactjs/preact  Preact
   Fast 3kB React alternative with the same modern API
   Confiança: 8.1
```

**Com contexto semântico para ranking mais preciso:**

```bash
context7 library react "hooks de efeito e estado"
context7 library axum "middleware e rotas"
context7 library tokio "canal mpsc assíncrono"
```

**Aliases disponíveis:** `lib`, `search`

```bash
context7 lib react
context7 search tokio
```

---

### Passo 5 — Buscar documentação

Use o `id` do Passo 4 (ex: `/facebook/react`):

```bash
context7 docs /facebook/react --query "useEffect e cleanup"
```

**Aliases disponíveis:** `doc`, `context`

```bash
context7 doc /rust-lang/rust --query "lifetimes e borrowing"
context7 context /tokio-rs/tokio --query "spawn_blocking"
```

**Flags para `docs`:**

| Flag | Descrição |
|------|-----------|
| `--query <TEXTO>`, `-q <TEXTO>` | Busca semântica dentro da documentação da biblioteca |
| `--text` | Retorna texto plano (sem cor, ideal para LLMs e pipes) |
| `--json` | Retorna JSON estruturado |

> `--text` e `--json` são mutuamente exclusivos.

**Exemplos:**

```bash
# Saída legível para humanos (padrão)
context7 docs /facebook/react --query "useState"

# Texto plano para contexto de LLM
context7 docs /tokio-rs/tokio --query "spawn_blocking" --text

# JSON para scripting
context7 docs /axum-rs/axum --json
```

---

### Passo 6 — Override de idioma (v0.2.0+)

Por padrão, o `context7-cli` detecta automaticamente o idioma do sistema. Você pode sobrescrever em runtime:

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

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

**Override permanente via variável de ambiente:**

```bash
# Configure uma vez no seu shell profile (~/.bashrc, ~/.zshrc, etc.)
export CONTEXT7_LANG=pt    # sempre português
export CONTEXT7_LANG=en    # sempre inglês
```

**Ordem de detecção automática:**

| Prioridade | Fonte | Exemplo |
|------------|-------|---------|
| 1 (maior) | Flag `--lang` na CLI | `context7 --lang pt library react` |
| 2 | Variável de ambiente `CONTEXT7_LANG` | `CONTEXT7_LANG=pt context7 ...` |
| 3 | Locale do sistema | `LANG=pt_BR.UTF-8` → português |
| 4 (padrão) | Fallback inglês | (quando locale não reconhecido) |

Qualquer locale começando com `pt` (ex: `pt_BR`, `pt_PT`) ativa o português automaticamente.

---

### Passo 7 — Formatos de saída

**Saída colorida (padrão):**

```
Documentação:
────────────────────────────────────────────────────────────
## useEffect

O hook useEffect permite sincronizar um componente com um sistema externo...

Fontes:
  https://react.dev/reference/react/useEffect
```

**Saída JSON (`--json`):**

```json
{
  "id": "/facebook/react",
  "snippets": [
    {
      "content": "## useEffect\n\nO hook useEffect...",
      "type": "markdown",
      "source_urls": ["https://react.dev/reference/react/useEffect"]
    }
  ]
}
```

**JSON de library:**

```json
[
  {
    "id": "/facebook/react",
    "title": "React",
    "description": "A JavaScript library for building user interfaces",
    "trust_score": 9.8
  }
]
```

---

### Passo 8 — Avançado: rotação de múltiplas chaves

Com múltiplas chaves, a `context7-cli` alterna entre elas automaticamente para evitar rate limiting:

```bash
# Adicionar múltiplas chaves (uma por comando)
context7 keys add ctx7sk-chave-principal
context7 keys add ctx7sk-chave-secundaria
context7 keys add ctx7sk-chave-terciaria

context7 keys list
# Saída:
# 1. ctx7sk-chav...pal (adicionada em 2026-04-08)
# 2. ctx7sk-chav...ria (adicionada em 2026-04-08)
# 3. ctx7sk-chav...ria (adicionada em 2026-04-08)
```

**Como funciona a rotação:**

- Cada requisição escolhe aleatoriamente uma chave do pool (shuffle sem reposição)
- Se uma requisição falhar (401/403/429/5xx/erro de rede), a próxima tentativa usa uma chave diferente
- Até 3 tentativas com backoff exponencial: 500ms → 1s → 2s
- Com 3+ chaves, o rate limiting é praticamente eliminado

**Remover chave específica:**

```bash
context7 keys remove 2    # remove a chave no índice 2 (1-based)
```

**Rotar para a próxima chave manualmente:**

```bash
context7 keys rotate      # avança o ponteiro da chave ativa para a próxima
```

---

### Passo 9 — Backup e restauração

```bash
# Exportar todas as chaves em formato .env (texto claro — proteja este arquivo!)
context7 keys export > ~/backup-context7.env

# Verificar o export
cat ~/backup-context7.env
# Saída: CONTEXT7_API=ctx7sk-valor-completo-aqui

# Apagar todas as chaves armazenadas
context7 keys clear --yes

# Restaurar a partir do backup
context7 keys import ~/backup-context7.env
# Saída: 3/3 chave(s) importada(s) com sucesso.

# Migrar a partir de arquivo .env legado de um projeto
context7 keys import /caminho/do/projeto/.env
```

---

### Solução de problemas

| Sintoma | Causa | Solução |
|---------|-------|---------|
| `Nenhuma chave de API encontrada` | Nenhuma chave configurada | Execute `context7 keys add ctx7sk-...` |
| `401 Unauthorized` | Chave inválida ou expirada | Verifique com `context7 keys list`, remova a chave inválida e adicione uma nova |
| `429 Too Many Requests` | Rate limit atingido | A CLI faz retry automaticamente; adicione mais chaves para cargas contínuas |
| Erro de rede / timeout | Sem internet ou conexão lenta | Verifique conectividade; CLI faz retry com backoff (timeout de 30s por tentativa) |
| `command not found: context7` | Binário não está no PATH | Certifique-se de que `~/.cargo/bin` (Linux/macOS) ou `%USERPROFILE%\.cargo\bin` (Windows) está no PATH |
| `Todas as chaves de API falharam` | Todas as chaves são inválidas | Execute `context7 keys list`, remova as inválidas e adicione novas em context7.com |

**Ver logs para diagnóstico detalhado:**

```bash
# Linux
bat -P ~/.local/state/context7/context7.log

# macOS
bat -P ~/Library/Application\ Support/context7/context7.log

# Modo dev (qualquer OS)
bat -P logs/context7.log
```

**Aumentar verbosidade dos logs:**

```bash
RUST_LOG=context7=debug context7 library react
RUST_LOG=trace context7 docs /facebook/react --query "hooks"
```

---

### Exemplos de integração

**Com `jaq` (parsing JSON):**

```bash
# Obter apenas os IDs das bibliotecas
context7 library react --json | jaq '.[].id'

# Filtrar por trust score > 8
context7 library vue --json | jaq '[.[] | select(.trust_score > 8.0)]'

# Obter o ID do primeiro resultado
context7 library axum --json | jaq -r '.[0].id'
```

**Com `rg` (busca na documentação):**

```bash
# Buscar padrão em documentação de texto plano
context7 docs /facebook/react --text | rg "useEffect"

# Com contexto de 3 linhas
context7 docs /rust-lang/rust --query "ownership" --text | rg -C 3 "borrow"
```

**Loop sobre resultados:**

```bash
for id in $(context7 library react --json | jaq -r '.[].id'); do
  echo "=== $id ==="
  context7 docs "$id" --query "getting started" --text
done
```

---

### System prompt para LLMs (Português)

Copie e cole isto no system prompt do seu LLM para habilitar busca automática de documentação:

```
Você tem acesso à CLI `context7` para buscar documentação técnica atualizada de bibliotecas e frameworks.

## Ferramenta disponível: `context7`

### Quando usar
- Quando precisar de documentação de qualquer biblioteca (React, Vue, Axum, Tokio, etc.)
- Quando o usuário perguntar sobre APIs, configurações ou uso de uma biblioteca específica
- Quando sua base de conhecimento puder estar desatualizada sobre uma biblioteca
- Antes de sugerir código que dependa de APIs externas

### Como usar: três subcomandos

#### Subcomando `library` — Descobrir o ID de uma biblioteca
```bash
context7 library <NOME> [CONTEXTO_OPCIONAL]
```
- `NOME`: nome da biblioteca (ex: `react`, `axum`, `tokio`, `vue`)
- `CONTEXTO_OPCIONAL`: texto para refinar o ranking (ex: `"hooks de efeito"`)
- Retorna: lista de bibliotecas com IDs, títulos e pontuação de confiança
- **Sempre use este subcomando primeiro para obter o ID correto**

Exemplos:
```bash
context7 library react "hooks e estado"
context7 library axum "middleware e rotas"
context7 library tokio "canal assíncrono"
```

#### Subcomando `docs` — Buscar documentação por ID
```bash
context7 docs <LIBRARY_ID> [--query <TEXTO>] [--text]
```
- `LIBRARY_ID`: ID no formato `/org/repo` obtido via `library` (ex: `/facebook/react`)
- `--query <TEXTO>`: tópico específico a buscar (opcional mas recomendado)
- `--text`: retorna texto plano (recomendado para inserir no contexto)
- `--json`: retorna JSON estruturado (incompatível com `--text`)

Exemplos:
```bash
context7 docs /facebook/react --query "useEffect e cleanup" --text
context7 docs /tokio-rs/tokio --query "spawn_blocking" --text
context7 docs /rust-lang/rust --query "lifetimes e borrowing" --text
```

### Fluxo correto em 2 passos

**Passo 1:** Descubra o ID
```bash
context7 library react "hooks de efeito"
# → Retorna: /facebook/react, /preactjs/preact, ...
```

**Passo 2:** Busque documentação com o ID correto
```bash
context7 docs /facebook/react --query "useEffect dependências" --text
```

### Regras importantes
- **NUNCA invente um LIBRARY_ID** — sempre use `library` primeiro para obtê-lo
- `--text` e `--json` são incompatíveis: use apenas um
- A flag `--json` é global e funciona em qualquer subcomando
- Se `library` não retornar resultados, tente variações do nome (ex: `react` vs `reactjs`)
- Erros 401/403 indicam problema com a chave de API (verifique via `context7 keys list`)
- Erros 429 indicam rate limit: a CLI faz retry automaticamente

### Pré-requisito
- Chave de API configurada via `context7 keys add <CHAVE>` (recomendado)
- Binário `context7` disponível no PATH
```