From 1533e69b3a1bc778a244ea312eeb7a57d67ffce6 Mon Sep 17 00:00:00 2001 From: Alex Samson Date: Sun, 22 Nov 2026 22:14:05 +0700 Subject: [PATCH 1/3] Handle Context7's submission queue and upload size limit add: - accept several URLs; validate all of them before sending any - stop on a full queue (exit 9), a 429 (exit 6) or a 401 (exit 3) and list the inputs still to send in notSubmitted; other refusals go to failed - --queue waits for a free slot (30 s polls, --queue-timeout per URL) - one progress line per URL; Ctrl-C or SIGTERM prints the partial summary and exits 130 - send a git token with repositories only upload: - refuse files over 4.4 MB before sending (Context7 answers 413 FUNCTION_PAYLOAD_TOO_LARGE above ~4.5 MB), with a split hint per file type; --skip-size-check overrides - say the library id comes from the file name Also: network failures come back as JSON instead of a traceback, every command has --help text, log keeps stdout JSON, and the skill and plugin are at version 1.2. Docs: new Upload a file page, an "Add many sources" section, new gotchas and exit codes; examples use this repo where a real source fits. Co-Authored-By: Claude Opus 5.5 --- .claude-plugin/plugin.json | 2 +- README.md | 18 +- docs/commands.mdx | 57 ++++- docs/docs.json | 2 +- docs/gotchas.mdx | 14 +- docs/upload.mdx | 157 ++++++++++++++ docs/usage.mdx | 4 +- skills/context7-add/SKILL.md | 38 +++- skills/context7-add/scripts/c7.py | 345 ++++++++++++++++++++++++------ 9 files changed, 537 insertions(+), 100 deletions(-) create mode 100644 docs/upload.mdx diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 22bc51f..853711f 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "context7-add", - "version": "1.1.0", + "version": "1.2.0", "description": "Index repos, docs sites, llms.txt, OpenAPI specs and files in Context7 when missing, and allow them in your teamspace policy so the Context7 MCP serves them.", "author": { "name": "Alex Samson", diff --git a/README.md b/README.md index a81d61f..046182a 100644 --- a/README.md +++ b/README.md @@ -54,8 +54,8 @@ or your agent's skills folder. Ask your agent, for example: -- "Add https://github.com/acme/widgets to Context7 and allow it." -- "Context7 says /acme/widgets isn't in my allowed libraries, fix it." +- "Add https://github.com/saalse/context7-add to Context7 and allow it." +- "Context7 says /saalse/context7-add isn't in my allowed libraries, fix it." - "Make the docs at https://docs.acme.dev available in context7." Or run the helper yourself: @@ -63,16 +63,16 @@ Or run the helper yourself: ```bash C7=skills/context7-add/scripts/c7.py python3 $C7 whoami -python3 $C7 check https://github.com/acme/widgets -python3 $C7 allow /acme/widgets # dry run -python3 $C7 allow /acme/widgets --apply -python3 $C7 add https://github.com/acme/widgets --apply -python3 $C7 wait /acme/widgets +python3 $C7 check https://github.com/saalse/context7-add +python3 $C7 allow /saalse/context7-add # dry run +python3 $C7 allow /saalse/context7-add --apply +python3 $C7 add https://github.com/saalse/context7-add --apply # already indexed: reports its id, creates nothing +python3 $C7 wait /saalse/context7-add ``` Results are JSON on stdout; errors go to stderr with a distinct exit code (bad input, -auth, not found, refused by policy, rate limited, unprocessable, timed out). See -`python3 $C7 --help`. +auth, not found, refused by policy, rate limited, unprocessable, timed out, submission +queue full, file too large). See `python3 $C7 --help`. The skill follows the [Agent Skills specification](https://agentskills.io/specification). diff --git a/docs/commands.mdx b/docs/commands.mdx index 8fdcee9..70be9a6 100644 --- a/docs/commands.mdx +++ b/docs/commands.mdx @@ -11,8 +11,8 @@ pass `--apply`. python3 scripts/c7.py whoami python3 scripts/c7.py check ... python3 scripts/c7.py allow ... [--remove] [--apply] -python3 scripts/c7.py add [--type T] [--base-url URL] [--private] [--git-token-env VAR] [--apply] -python3 scripts/c7.py upload [--title T] [--apply] +python3 scripts/c7.py add ... [--type T] [--base-url URL] [--private] [--git-token-env VAR] [--queue [--queue-timeout SEC]] [--apply] +python3 scripts/c7.py upload [--title T] [--description D] [--skip-size-check] [--apply] python3 scripts/c7.py refresh [--apply] python3 scripts/c7.py wait [--changed] [--timeout SEC] python3 scripts/c7.py log @@ -23,22 +23,67 @@ python3 scripts/c7.py log | `whoami` | plan, role, policy mode, which list admits libraries | | `check` | state, freshness and coverage per input; guessed website ids; the site's llms.txt files; a GitHub owner's repos | | `allow` | add or remove allowlist / wild-card entries, with a dry-run library count | -| `add` | submit a repo, website, llms.txt or OpenAPI URL; reports the existing id if Context7 already has it | -| `upload` | upload a PDF, DOCX or OpenAPI file (private to the teamspace) | +| `add` | submit one or more repo, website, llms.txt or OpenAPI URLs; reports the existing id if Context7 already has it. See [Add many sources](#add-many-sources) | +| `upload` | upload a PDF, DOCX or OpenAPI file up to ~4.5 MB (private to the teamspace). See [Upload a file](/upload) | | `refresh` | re-crawl or re-parse a stale library (daily limit) | | `wait` | poll until indexed; `--changed` waits until a refresh lands | | `log` | the audit trail of applied changes | +## Add many sources + +Context7 lets each user have at most **5 libraries processing or queued** at a time. A sixth +submission is refused with `400 user-has-active-task`. Pass every URL to one `add` call. In +select mode, allow public repos first: their submission is gated by the policy. + +```bash +python3 scripts/c7.py allow /acme/a /acme/b --apply +python3 scripts/c7.py add https://github.com/acme/a https://github.com/acme/b https://docs.acme.dev/ --apply +``` + +All inputs are validated before anything is sent, and stderr gets one progress line per URL. +When the queue fills up, Context7 answers 429 (rate limited), or the key is refused (401), +`add` stops: the remaining URLs would be refused too. With several URLs, the output lists what +was not submitted, starting with the URL that hit the limit: + +```json +{ + "results": [ + {"input": "https://github.com/acme/a", "status": 200, "libraryId": "/acme/a", "...": "..."}, + {"input": "https://github.com/acme/b", "status": 400, + "response": {"error": "user-has-active-task", "message": "You already have 5 libraries being processed or queued. ..."}, + "meaning": "not submitted: Context7 allows 5 libraries processing or queued per user. ..."} + ], + "notSubmitted": ["https://github.com/acme/b", "https://docs.acme.dev/"], + "next": "Context7's queue holds 5 libraries per user. Resubmit notSubmitted once some finish ..." +} +``` + +URLs refused for another reason (policy, not a documentation site, and so on) are listed in +`failed`; they aren't retried, and the exit code is the first such refusal. Only when nothing +failed for real is the exit code 3 (key refused), 9 (queue full) or 6 (rate limited). + +To submit everything in one go, add `--queue`. When the queue is full, `add` then waits 30 s +and retries the same URL, for up to `--queue-timeout` seconds per URL (default 1800). Indexing +takes minutes, so run it in the background. If the run is stopped (Ctrl-C or SIGTERM), it still +prints the summary so far, with `"interrupted": true` and `notSubmitted`, and exits 130, +whatever else happened before. The URL that was being sent may already have been accepted; +resubmitting it is safe, because Context7 answers `library-already-exists`. + +`--type` and `--base-url` apply to one URL, so they can't be combined with several URLs; the +type is detected per URL otherwise. + ## Exit codes | Code | Meaning | |---|---| | 0 | success (`check`: report produced; `wait`: ready) | | 1 | API or network error | -| 2 | bad input | +| 2 | bad input, or a file too large to upload (over ~4.5 MB, or a 413) | | 3 | missing or invalid key, or role/plan too low | | 4 | library not found | | 5 | refused by the teamspace policy | | 6 | rate limited | -| 7 | unprocessable (no or too few docs) | +| 7 | unprocessable (no or too few docs), or not a documentation website | | 8 | `wait` timed out | +| 9 | submission queue full (5 libraries already processing). `add`: resubmit `notSubmitted` or use `--queue`; `refresh`, `upload`: try again later | +| 130 | `add`: interrupted; the partial summary lists `notSubmitted` | diff --git a/docs/docs.json b/docs/docs.json index d22e447..c38e31a 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -20,7 +20,7 @@ "navigation": { "groups": [ { "group": "Get started", "pages": ["index", "install"] }, - { "group": "Guide", "pages": ["usage", "commands", "gotchas"] } + { "group": "Guide", "pages": ["usage", "commands", "upload", "gotchas"] } ] } } diff --git a/docs/gotchas.mdx b/docs/gotchas.mdx index 70955a6..a637426 100644 --- a/docs/gotchas.mdx +++ b/docs/gotchas.mdx @@ -10,12 +10,12 @@ description: Context7 behaviours that contradict reasonable assumptions, found i official source first; an RFC is `https://www.rfc-editor.org/rfc/rfcNNNN.html`, which lives in `/websites/rfc-editor_rfc`. - **Website ids drop parts of the URL.** `docs.` / `www.`, `.com` / `.org` / `.net` and a - `docs` path segment are removed: `nianticspatial.com/docs/scaniverse` → - `/websites/nianticspatial_scaniverse`. + `docs` path segment are removed: `docs.github.com/en` → `/websites/github_en`, + `example.com/docs/guide` → `/websites/example_guide`. - **A domain entry is about docs sites, not repo hosts.** A `github.com` entry does not admit GitHub repos. -- **"Already exists" is a 400, not a 409.** Submitting a site Context7 already has returns - `library-already-exists` with the id in the message, and creates nothing. +- **"Already exists" is a 400, not a 409.** Submitting a repo or site Context7 already has + returns `library-already-exists` with the id in the message, and creates nothing. - **Exists is not the same as covered.** A library can be months old and missing pages, or empty while a more specific sibling has the content. Refresh stale ones. - **Crawls only follow the site's menu.** Unlinked pages stay out even after a refresh; the @@ -25,5 +25,11 @@ description: Context7 behaviours that contradict reasonable assumptions, found i `unprocessable`, and the failed library remains in the index. - **The library count ignores empty libraries.** A policy dry run doesn't move for libraries that are empty or still processing. +- **Only 5 submissions at a time.** A sixth `add` while 5 libraries are processing gets + `400 user-has-active-task`. Pass all URLs to one `add --queue` call. +- **Uploads stop at about 4.5 MB.** Larger files get `413 FUNCTION_PAYLOAD_TOO_LARGE`. Split + PDFs by pages. The library id comes from the file name, not the title, so name the file well. +- **Some sites are refused as "not documentation".** `422 not_documentation_website` + ("Website score 1 below threshold 9") is final for that URL: marketing sites and blogs get it. - **Claiming needs a Write-access key.** The management API (`/v2/teamspaces/…`) answers `write_access_required` to a normal key; use the dashboard instead. diff --git a/docs/upload.mdx b/docs/upload.mdx new file mode 100644 index 0000000..567100b --- /dev/null +++ b/docs/upload.mdx @@ -0,0 +1,157 @@ +--- +title: Upload a file +description: Upload a PDF, DOCX or OpenAPI file to Context7 with c7.py upload, the endpoints and multipart fields it uses, the size limit, and what happens after. +--- + +Use `upload` when the docs exist only as a file: a PDF manual or paper, a Word document, or an +OpenAPI spec that isn't published at a URL. (For a spec that has a URL, use `add ` +instead, so Context7 can refresh it.) Like every command that changes something, it is a dry +run until you pass `--apply`. + +```bash +python3 scripts/c7.py upload [--title TITLE] [--description TEXT] [--skip-size-check] [--apply] +``` + +| Option | What it does | +|---|---| +| `` | path to a `.pdf`, `.docx`, or an OpenAPI `.json`, `.yaml` or `.yml` file | +| `--title` | the library's display name; sent as `projectTitle` (PDF, DOCX) or `libraryTitle` (OpenAPI). If you leave it out, no title field is sent and Context7 chooses the name | +| `--description` | a short summary of the document, sent as the `description` field | +| `--skip-size-check` | send a file over the ~4.5 MB limit anyway; only useful if Context7 has raised the limit | +| `--apply` | actually upload; without it the command only prints what it would send | + +## Example: upload a PDF + +Preview first: + +```bash +python3 scripts/c7.py upload acme-handbook.pdf --title "Acme Handbook" --description "Internal engineering handbook" +``` + +```json +{ + "dryRun": true, + "would": "POST https://context7.com/api/v2/add/pdf-upload", + "file": "acme-handbook.pdf", + "bytes": 1200000, + "fields": { + "projectTitle": "Acme Handbook", + "description": "Internal engineering handbook" + }, + "note": "Uploaded files are private to the teamspace (source type uploaded_files), not subject to the public allowlist. The library id is built from the file name (for a PDF: /pdf/--), not from --title: rename the file first if its name says nothing." +} +``` + +The dry run checks the file type, that the file exists, and its size. It sends nothing and +needs no API key. When the preview looks right, upload it. The response looks like this; the +id's prefix and hash differ for every upload: + +```bash +python3 scripts/c7.py upload acme-handbook.pdf --title "Acme Handbook" --description "Internal engineering handbook" --apply +``` + +```json +{ + "status": 200, + "response": { + "libraryName": "/pdf/1a2b3c4d-acme-handbook.pdf-9f8e7d6c", + "message": "PDF file uploaded successfully" + }, + "libraryId": "/pdf/1a2b3c4d-acme-handbook.pdf-9f8e7d6c" +} +``` + +`libraryId` is the new library. The upload is written to the audit log (`c7.py log`). Query +it with the Context7 MCP `query-docs` tool once indexing finishes, or follow it with +`python3 scripts/c7.py wait `. + +## Name the file before you upload + +The library id comes from the **file name**, not from `--title`: +`/pdf/--`. An upload of `scan_0042_final.pdf` gets an +id nobody can read later. Rename it first, to something like `acme-widget-manual-2024.pdf`. + +## Size limit + +Context7 doesn't document an upload limit, but in practice the request body is capped at about +**4.5 MB**. Files around 3 MB upload fine, while files around 5 MB and larger are refused with +`413 FUNCTION_PAYLOAD_TOO_LARGE`. So the script checks the size first: + +- the dry run adds a `sizeWarning` for a file over 4.4 MB; +- `--apply` refuses to send it (exit code 2) unless you pass `--skip-size-check`; +- if Context7 still answers 413, the result carries a `meaning` with the fix. + +Recompressing rarely helps, because figures in papers are already compressed. Split the file by +pages instead, for example with `qpdf`, and upload each part: + +```bash +qpdf --empty --pages paper.pdf 1-3 -- acme-paper-p1-3.pdf +qpdf --empty --pages paper.pdf 4-6 -- acme-paper-p4-6.pdf +python3 scripts/c7.py upload acme-paper-p1-3.pdf --title "Acme paper, pages 1-3" --apply +python3 scripts/c7.py upload acme-paper-p4-6.pdf --title "Acme paper, pages 4-6" --apply +``` + +Each part becomes its own library, so put the page range in both the file name and `--title`. +A single page that is still over the limit (one large figure) can't be uploaded as-is. For a +DOCX, split the document or remove large images; for an OpenAPI spec, split it (for example by +tag) or drop large embedded examples. + +## Example: upload an OpenAPI spec + +```bash +python3 scripts/c7.py upload acme-openapi.yaml --title "Acme API" --apply +``` + +OpenAPI files go to a different endpoint and use `libraryTitle` instead of `projectTitle`; +the script picks both from the file extension. + +## Endpoints and form fields + +Each upload is one `multipart/form-data` POST to the Context7 API, authenticated with your API +key as `Authorization: Bearer `. + +| File | Endpoint | File field | Title field | +|---|---|---|---| +| `.pdf` | `POST https://context7.com/api/v2/add/pdf-upload` | `pdfFile` | `projectTitle` | +| `.docx` | `POST https://context7.com/api/v2/add/docx-upload` | `docxFile` | `projectTitle` | +| `.json`, `.yaml`, `.yml` (OpenAPI) | `POST https://context7.com/api/v2/add/openapi-upload` | `openapiFile` | `libraryTitle` | + +All three also accept an optional `description` field. The file part carries the file name +and a content type guessed from the extension (`application/pdf`, for example). + +The same PDF upload with `curl`: + +```bash +curl -X POST https://context7.com/api/v2/add/pdf-upload \ + -H "Authorization: Bearer $CONTEXT7_API_KEY" \ + -F "pdfFile=@acme-handbook.pdf" \ + -F "projectTitle=Acme Handbook" \ + -F "description=Internal engineering handbook" +``` + +## Privacy and access + +- Uploaded files are private to your teamspace. They are not public libraries, so they need + no allowlist or wild-card entry (`allow` is not needed). +- Your teamspace must have the **Uploaded Files** source type turned on (`whoami` shows + `sourceTypes.uploaded_files`), or the Context7 MCP won't serve them. See Context7's + [data privacy settings](https://context7.com/docs/security/data-privacy). + +## Updating an uploaded file + +Context7 can't refresh uploaded files: `refresh` works only for sources it can fetch again, like +repos, websites, `llms.txt` and OpenAPI URLs. To update an uploaded file, upload the new version +again ([Context7: keeping libraries fresh](https://context7.com/docs/library-updates)). + +## Errors and exit codes + +| Code | When | +|---|---| +| 0 | dry run printed, or upload accepted | +| 1 | network error (on a file over 3 MB, the result adds that it may be a size refusal), or an unexpected API error | +| 2 | unsupported file type, missing file, file over 4.4 MB (nothing sent), a 413 from Context7, or another 400 | +| 3 | missing or invalid API key, or role/plan too low | +| 5 | refused by the teamspace policy | +| 6 | rate limited | +| 7 | Context7 could not process the file (422) | +| 9 | Context7's per-user submission queue is full; upload again later | diff --git a/docs/usage.mdx b/docs/usage.mdx index 0f27494..c3f1ee0 100644 --- a/docs/usage.mdx +++ b/docs/usage.mdx @@ -5,8 +5,8 @@ description: What to ask your agent, and the workflow it follows. ## Ask your agent -- "Add https://github.com/acme/widgets to Context7 and allow it." -- "Context7 says /acme/widgets isn't in my allowed libraries, fix it." +- "Add https://github.com/saalse/context7-add to Context7 and allow it." +- "Context7 says /saalse/context7-add isn't in my allowed libraries, fix it." - "Make the docs at https://docs.acme.dev available in context7." - "Is open3d indexed and allowed in my Context7?" diff --git a/skills/context7-add/SKILL.md b/skills/context7-add/SKILL.md index 2b71998..5d3dd91 100644 --- a/skills/context7-add/SKILL.md +++ b/skills/context7-add/SKILL.md @@ -7,7 +7,7 @@ metadata: author: Alex Samson homepage: https://saalse.com repository: https://github.com/saalse/context7-add - version: "1.1" + version: "1.2" --- # Context7: add and allow @@ -22,14 +22,18 @@ is usually two steps: **index** the source if Context7 lacks it, then **allow** **`scripts/c7.py`** does every call. Run it from this skill's folder. It reads the API key from `$CONTEXT7_API_KEY`, or else from the `context7` MCP server entry in `~/.claude.json`, and never prints it. Every command that changes something is a **dry run unless `--apply`**. -Results are JSON on stdout; progress and errors go to stderr. `--help` lists the exit codes. +Results are JSON on stdout; progress and errors go to stderr. + +Exit codes: 0 ok · 1 API/network error · 2 bad input or file too large · 3 key/role/plan · +4 not found · 5 refused by policy · 6 rate limited · 7 unprocessable or not a docs site · +8 `wait` timed out · 9 submission queue full · 130 `add` interrupted (partial summary printed). ```bash python3 scripts/c7.py whoami # plan, role, policy mode, which list admits libraries python3 scripts/c7.py check … # indexed? fresh? allowed? which entry covers it? python3 scripts/c7.py allow /org/repo [--remove] [--apply] # dry run shows library count before/after -python3 scripts/c7.py add [--type …] [--base-url URL] [--private] [--apply] -python3 scripts/c7.py upload [--title …] [--apply] +python3 scripts/c7.py add … [--type …] [--base-url URL] [--private] [--queue [--queue-timeout SEC]] [--apply] +python3 scripts/c7.py upload [--title …] [--description …] [--skip-size-check] [--apply] python3 scripts/c7.py refresh /org/repo [--apply] # re-crawl / re-parse a stale library python3 scripts/c7.py wait /org/repo [--changed] # until indexed; --changed: until a refresh lands python3 scripts/c7.py log # what this skill changed before (registry.jsonl) @@ -50,13 +54,13 @@ These come from real runs and contradict reasonable assumptions: its official source first (repo URL, or docs URL: an RFC is `https://www.rfc-editor.org/rfc/rfcNNNN.html`) and check that. - **Website ids drop parts of the URL.** `docs.` / `www.`, `.com` / `.org` / `.net` and a - `docs` path segment are removed: `nianticspatial.com/docs/scaniverse` → - `/websites/nianticspatial_scaniverse`. `check` guesses these shapes (`guessedIds`). + `docs` path segment are removed: `docs.github.com/en` → `/websites/github_en`, + `example.com/docs/guide` → `/websites/example_guide`. `check` guesses these shapes (`guessedIds`). - **A domain entry is about docs sites, not repo hosts.** A `github.com` entry does not admit GitHub repos; each repo needs its own entry or an owner entry. -- **"Already exists" is a 400, not a 409.** Submitting a site Context7 already has returns - `library-already-exists` with the id in the message; nothing is created. The script reports - that id, so `add` doubles as a safe lookup for a site you would add anyway. +- **"Already exists" is a 400, not a 409.** Submitting a repo or site Context7 already has + returns `library-already-exists` with the id in the message; nothing is created. The script + reports that id (exit 0), so `add` doubles as a safe lookup for a source you would add anyway. - **Exists is not the same as covered.** A library can be months old and missing pages, or empty (`unprocessable`) while a more specific sibling has the content. - **Crawls only follow the site's menu.** Pages the navigation never links stay out even after @@ -72,6 +76,19 @@ These come from real runs and contradict reasonable assumptions: but the management API (`/v2/teamspaces/…`: claim, owned-library settings, Docs7 sites) answers 403 `write_access_required` unless the key was created with **Write access** ticked. Otherwise send the user to the dashboard for those steps. +- **Only 5 submissions in flight per user.** More get `400 user-has-active-task` (exit 9). + Pass all URLs to one `add … --queue --apply` and run it in the background. It waits for free + slots, so don't write your own retry loop. Without `--queue`, resubmit the output's + `notSubmitted` list later. URLs refused for other reasons are in `failed`, and the exit code + is the first such refusal. `--type` and `--base-url` need one URL per call. +- **Uploads stop at about 4.5 MB** (`413 FUNCTION_PAYLOAD_TOO_LARGE`). `upload` refuses larger + files before sending. Split a PDF by pages (`qpdf --empty --pages in.pdf 1-3 -- in-p1-3.pdf`), + one upload per part, with the page range in the file name and `--title`. +- **An upload's id comes from the file name, not `--title`** (`/pdf/--`). + Rename an opaque file name before uploading. +- **"Not a documentation website" is final.** `422 not_documentation_website` (exit 7) means + Context7 scored the site too low (marketing pages, blogs). Look for a docs subdomain or + llms.txt; otherwise list it as "read on the web". - **A fresh submit looks missing.** Right after `add`, the id answers `no_snippets_found` (`processing_or_empty`) until parsing finishes. Use `wait`, not a single probe. @@ -119,7 +136,8 @@ upstream repo. | website / llms.txt / OpenAPI not found | `add `, then `allow ` | | add refused with `access_denied` | the submit is gated by the policy: allow the docs host, retry, allow the exact id, offer to remove the host entry | | private repo | `add --private` (paid plan; account connected in the dashboard, or `--git-token-env VAR`). Private sources aren't gated by the public allowlist | -| PDF / DOCX / OpenAPI file | `upload `; private to the teamspace, no `allow` needed | +| several missing sources | `allow` the exact ids of the public repos first (the add is gated by the policy), then one `add … --queue --apply` in the background, then `allow` each new `libraryId` from the results (websites, llms.txt, OpenAPI) | +| PDF / DOCX / OpenAPI file | `upload `; private to the teamspace, no `allow` needed; over ~4.5 MB, split it first (a PDF by pages) | | Notion, Confluence | needs connected accounts: send the user to https://context7.com/add-library | **Allow the narrowest entry that works.** The allowlist is a security control: `/owner/repo` diff --git a/skills/context7-add/scripts/c7.py b/skills/context7-add/scripts/c7.py index 3ecca51..5a0cc38 100755 --- a/skills/context7-add/scripts/c7.py +++ b/skills/context7-add/scripts/c7.py @@ -8,11 +8,15 @@ c7.py check ... is it in Context7? is it allowed by the policy? c7.py allow ... [--remove] [--apply] add/remove allowlist entries (/org, /org/repo, domain.com) - c7.py add [--type T] [--private] [--generate-docs] [--base-url URL] - [--git-token-env VAR] [--apply] - submit a repo / website / llms.txt / OpenAPI URL - c7.py upload [--title T] [--description D] [--apply] - upload a PDF, DOCX or OpenAPI file + c7.py add ... [--type T] [--private] [--generate-docs] [--base-url URL] + [--git-token-env VAR] [--queue [--queue-timeout SEC]] [--apply] + submit repos / websites / llms.txt / OpenAPI URLs; + --queue: wait for a free slot when Context7's + 5-submission queue is full, instead of stopping. + One progress line per URL on stderr; --type and + --base-url need a single URL + c7.py upload [--title T] [--description D] [--skip-size-check] [--apply] + upload a PDF, DOCX or OpenAPI file (max ~4.5 MB) c7.py refresh [--apply] re-crawl / re-parse a stale library (daily limit) c7.py wait [--changed] [--timeout SEC] poll until the library is indexed and served; @@ -20,9 +24,10 @@ c7.py log show what this skill has changed before Examples: - c7.py check https://github.com/acme/widgets https://docs.acme.dev/ - c7.py allow /acme/widgets --apply + c7.py check https://github.com/saalse/context7-add https://docs.acme.dev/ + c7.py allow /saalse/context7-add --apply c7.py add https://docs.acme.dev/guide/ --base-url https://docs.acme.dev/guide/ --apply + c7.py add https://github.com/acme/a https://github.com/acme/b https://docs.acme.dev/ --queue --apply API key: $CONTEXT7_API_KEY, else the context7 MCP entry in ~/.claude.json. The key is never printed. Results are JSON on stdout; progress and errors on stderr. @@ -30,19 +35,27 @@ Exit codes: 0 success (check: the report was produced, read its fields; wait: ready) 1 API or network error - 2 bad input (arguments, file type, unsupported llms.txt name) + 2 bad input (arguments, file type, unsupported llms.txt name, file too large / 413) 3 auth: missing/invalid API key, or role/plan too low 4 library not found 5 refused by the teamspace policy (access_denied) 6 rate limited (429) - 7 library unprocessable (no or too few docs) + 7 library unprocessable (no or too few docs, or not a documentation website) 8 wait timed out + 9 submission queue full (5 libraries already processing). add: `notSubmitted` lists + what to resubmit, or rerun with --queue; refresh / upload: try again later + 130 add: interrupted (Ctrl-C or SIGTERM); the partial summary lists `notSubmitted` +With several URLs, add exits 130 if interrupted, else with the first real refusal (listed in +`failed`), else 3, 9 or 6. A 401, 429 or full queue stops the run; that URL and the rest are +listed in `notSubmitted`. """ import argparse +import http.client import json import mimetypes import os import re +import signal import sys import time import urllib.error @@ -56,7 +69,17 @@ LOG_PATH = os.path.join(SKILL_DIR, "registry.jsonl") EXIT_API, EXIT_USAGE, EXIT_AUTH, EXIT_NOT_FOUND = 1, 2, 3, 4 -EXIT_POLICY, EXIT_RATE, EXIT_UNPROCESSABLE, EXIT_TIMEOUT = 5, 6, 7, 8 +EXIT_POLICY, EXIT_RATE, EXIT_UNPROCESSABLE, EXIT_TIMEOUT, EXIT_QUEUE = 5, 6, 7, 8, 9 +EXIT_INTERRUPTED = 130 + +QUEUE_FULL = "user-has-active-task" # 400: "You already have 5 libraries being processed or queued" +QUEUE_POLL_SEC = 30 +DEFAULT_QUEUE_TIMEOUT = 1800 +# Context7 doesn't document an upload limit; in practice the request body is capped at ~4.5 MB +# (413 FUNCTION_PAYLOAD_TOO_LARGE: ~3 MB goes through, ~5 MB does not). Leave room for the +# multipart envelope. +MAX_UPLOAD_BYTES = 4_400_000 +LARGE_UPLOAD_BYTES = 3_000_000 # above this, a dropped connection may be the size limit def fail(code, msg): @@ -68,9 +91,16 @@ def http_exit_code(status, data): err = data.get("error") if isinstance(data, dict) else None if status == 403: return EXIT_POLICY if err == "access_denied" else EXIT_AUTH - return {0: EXIT_API, 400: EXIT_USAGE, 401: EXIT_AUTH, 404: EXIT_NOT_FOUND, + if err == QUEUE_FULL: + return EXIT_QUEUE + return {0: EXIT_API, 400: EXIT_USAGE, 401: EXIT_AUTH, 404: EXIT_NOT_FOUND, 413: EXIT_USAGE, 422: EXIT_UNPROCESSABLE, 429: EXIT_RATE}.get(status, EXIT_API) + +def queue_full(data): + return isinstance(data, dict) and data.get("error") == QUEUE_FULL + + REPO_HOSTS = {"github.com": "github", "gitlab.com": "gitlab", "bitbucket.org": "bitbucket"} ADD_ENDPOINT = { "github": ("/v2/add/repo/github", "docsRepoUrl"), @@ -131,9 +161,17 @@ def call(method, path, body=None, params=None, form=None): with urllib.request.urlopen(req, timeout=120) as r: status, raw = r.status, r.read() except urllib.error.HTTPError as e: - status, raw = e.code, e.read() + status = e.code + try: # the server may send error headers and then drop the connection (seen with 413) + raw = e.read() + except (OSError, http.client.HTTPException): + raw = b"" except urllib.error.URLError as e: return 0, {"error": "network", "message": str(e.reason)} + except (OSError, http.client.HTTPException) as e: + # Connection reset, remote disconnect or timeout mid-request (seen on large uploads): + # report it as JSON like any other network error instead of a traceback. + return 0, {"error": "network", "message": f"{type(e).__name__}: {e}"} text = raw.decode("utf-8", "replace") try: return status, json.loads(text) @@ -147,8 +185,11 @@ def out(obj): def log(action, **fields): entry = {"at": datetime.now(timezone.utc).isoformat(timespec="seconds"), "action": action, **fields} - with open(LOG_PATH, "a") as f: - f.write(json.dumps(entry, ensure_ascii=False) + "\n") + try: + with open(LOG_PATH, "a") as f: + f.write(json.dumps(entry, ensure_ascii=False) + "\n") + except OSError as e: # the change itself went through; don't lose the result over the audit log + print(f"warning: could not write {LOG_PATH}: {e}", file=sys.stderr) def get_policies(): @@ -226,8 +267,8 @@ def probe(lib_id): def website_id_candidates(url): """Guess Context7 ids for a docs URL. Observed shapes: docs.github.com/en -> /websites/github_en, - nianticspatial.com/docs/scaniverse -> /websites/nianticspatial_scaniverse, docs.astral.sh -> - /websites/astral_sh, rfc-editor.org/rfc/ -> /websites/rfc-editor_rfc.""" + docs.astral.sh -> /websites/astral_sh, rfc-editor.org/rfc/ -> /websites/rfc-editor_rfc; a `docs` + path segment is dropped (example.com/docs/guide -> /websites/example_guide).""" u = urllib.parse.urlparse(url) host = (u.hostname or "").lower() for prefix in ("www.", "docs."): @@ -260,7 +301,7 @@ def site_llms_files(url): for i in range(1, len(segs) + 1): base = root + "/" + "/".join(segs[:i]) cands += [f"{base}/llms.txt", f"{base}/llms-full.txt"] - if i >= 2: # e.g. /docs/scaniverse -> /docs/llms-scaniverse.txt + if i >= 2: # e.g. /docs/guide -> /docs/llms-guide.txt cands.append(root + "/" + "/".join(segs[:i - 1]) + f"/llms-{segs[i - 1]}.txt") found = [] for c in dict.fromkeys(cands): @@ -433,62 +474,170 @@ def cmd_allow(args): out(result) -def cmd_add(args): - c = classify(args.url) +def prepare_add(url, args): + """Validate one input and build its request; exits with EXIT_USAGE on bad input.""" + c = classify(url) kind = args.type or c["kind"] if kind not in ADD_ENDPOINT: - fail(EXIT_USAGE, f"Cannot tell the source type of {args.url!r} (got {kind!r}); pass --type " + fail(EXIT_USAGE, f"Cannot tell the source type of {url!r} (got {kind!r}); pass --type " f"{'|'.join(ADD_ENDPOINT)}.") if kind == "llmstxt": - fname = urllib.parse.urlparse(args.url).path.rstrip("/").split("/")[-1].lower() + fname = urllib.parse.urlparse(url).path.rstrip("/").split("/")[-1].lower() if fname not in ("llms.txt", "llms-full.txt", "llms-small.txt"): fail(EXIT_USAGE, f"Context7 only accepts files named llms.txt, llms-full.txt or llms-small.txt (got {fname!r}). " "For a per-section file, cover the missing pages with a narrow website source instead: " "add
--base-url
.") path, field = ADD_ENDPOINT[kind] - body = {field: c.get("repoUrl") or args.url} + body = {field: c.get("repoUrl") or url} is_repo = field == "docsRepoUrl" if args.private: if not is_repo: - fail(EXIT_USAGE, "--private applies to repositories only.") + fail(EXIT_USAGE, f"--private applies to repositories only (got {url!r}).") body["private"] = True if args.generate_docs: if not (is_repo and args.private): - fail(EXIT_USAGE, "--generate-docs applies to private repositories only.") + fail(EXIT_USAGE, f"--generate-docs applies to private repositories only (got {url!r}).") body["generateDocs"] = True if args.base_url: if kind != "website": - fail(EXIT_USAGE, "--base-url applies to websites only.") + fail(EXIT_USAGE, f"--base-url applies to websites only (got {url!r}).") body["websiteBaseUrl"] = args.base_url token_note = None if args.git_token_env: tok = os.environ.get(args.git_token_env) if not tok: fail(EXIT_USAGE, f"${args.git_token_env} is empty.") - body["gitToken"] = tok - token_note = f"gitToken from ${args.git_token_env}" - shown = {k: ("" if k == "gitToken" else v) for k, v in body.items()} - if not args.apply: - out({"dryRun": True, "would": f"POST {API}{path}", "body": shown, - "expectedLibraryId": c["libraryId"], "note": token_note}) - return - status, data = call("POST", path, body=body) - result = {"status": status, "response": data, "expectedLibraryId": c["libraryId"]} - if status == 200 and isinstance(data, dict): - log("add", source=kind, url=body[field], libraryId=data.get("libraryName"), - version=data.get("version"), private=bool(args.private)) - result["libraryId"] = data.get("libraryName") - elif status == 409 or (isinstance(data, dict) and data.get("error") == "library-already-exists"): - m = re.search(r"(/[\w.@-]+(?:/[\w.@-]+)+)", (data or {}).get("message", "")) if isinstance(data, dict) else None + if is_repo: + body["gitToken"] = tok + token_note = f"gitToken from ${args.git_token_env}" + else: # never hand a git token to a website / llms.txt / OpenAPI submission + token_note = f"${args.git_token_env} not sent: a git token applies to repositories only" + return {"input": url, "kind": kind, "c": c, "path": path, "field": field, "body": body, + "tokenNote": token_note} + + +def submit_add(p, args): + """POST one prepared add. Returns (result, exit_code, stop) where stop is "queue", "rate" or + "auth" when the remaining inputs would be refused too.""" + deadline = time.time() + (args.queue_timeout if args.queue_timeout is not None else DEFAULT_QUEUE_TIMEOUT) + while True: + status, data = call("POST", p["path"], body=p["body"]) + if not (queue_full(data) and args.queue and time.time() < deadline): + break + wait = min(QUEUE_POLL_SEC, max(1, int(deadline - time.time()))) + print(f"queue full (5 libraries processing); retrying {p['input']} in {wait} s", file=sys.stderr) + time.sleep(wait) + c = p["c"] + result = {"input": p["input"], "status": status, "response": data, "expectedLibraryId": c["libraryId"]} + err = data.get("error") if isinstance(data, dict) else None + code = 0 + if status == 200: + d = data if isinstance(data, dict) else {} + log("add", source=p["kind"], url=p["body"][p["field"]], libraryId=d.get("libraryName"), + version=d.get("version"), private=bool(args.private)) + result["libraryId"] = d.get("libraryName") + elif status == 409 or err == "library-already-exists": + m = re.search(r"(/[\w.@-]+(?:/[\w.@-]+)+)", data.get("message") or "") if isinstance(data, dict) else None result["libraryId"] = m.group(1).lower() if m else c["libraryId"] result["meaning"] = "already exists in Context7: nothing was created; just make sure it is allowed" - status = 409 - elif status == 403: - result["meaning"] = ("refused: if error is access_denied the library id is outside the allowlist " - "(allow it first); otherwise role/plan") - out(result) - if status not in (200, 409): - sys.exit(http_exit_code(status, data)) + else: + code = http_exit_code(status, data) + if err == QUEUE_FULL: + result["meaning"] = ("not submitted: Context7 allows 5 libraries processing or queued per user. " + + ("--queue timed out; resubmit later, or rerun with a larger --queue-timeout" + if args.queue else + "resubmit later, or rerun with --queue to wait for a free slot")) + elif status == 403: + result["meaning"] = ("refused: if error is access_denied the library id is outside the allowlist " + "(allow it first); otherwise role/plan") + elif err == "not_documentation_website": + result["meaning"] = ("refused for good: Context7 doesn't score this as a documentation site. " + "Look for a docs subdomain or an llms.txt, or read it on the web") + elif status == 429: + result["meaning"] = "not submitted: rate limited; wait a few minutes, then resubmit" + stop = "queue" if err == QUEUE_FULL else "rate" if status == 429 else "auth" if status == 401 else None + return result, code, stop + + +def _sigterm(signum, frame): + raise KeyboardInterrupt # a background run that gets killed still prints its partial summary + + +def cmd_add(args): + many = len(args.urls) > 1 + if many and args.base_url: + fail(EXIT_USAGE, "--base-url applies to one website at a time; run add once per website.") + if many and args.type: + fail(EXIT_USAGE, "--type applies to one URL at a time; leave it out (the type is detected per URL) " + "or run add once per URL that needs it.") + if args.queue_timeout is not None and not args.queue: + fail(EXIT_USAGE, "--queue-timeout only makes sense with --queue.") + if args.queue_timeout is not None and args.queue_timeout < 0: + fail(EXIT_USAGE, "--queue-timeout must be 0 or more seconds.") + plans = [prepare_add(u, args) for u in args.urls] # validate everything before submitting anything + if not args.apply: + dry = [{"dryRun": True, "input": p["input"], "would": f"POST {API}{p['path']}", + "body": {k: ("" if k == "gitToken" else v) for k, v in p["body"].items()}, + "expectedLibraryId": p["c"]["libraryId"], "note": p["tokenNote"]} for p in plans] + out({"dryRun": True, "results": dry} if many else dry[0]) + return + previous = signal.signal(signal.SIGTERM, _sigterm) + results, failed, not_submitted, stopped, interrupted = [], [], [], None, False + first_failure, i = 0, 0 + try: + for i, p in enumerate(plans): + result, code, stop = submit_add(p, args) + results.append(result) + if stop: # recorded before anything else, so an interrupt during the print keeps it + not_submitted = [q["input"] for q in plans[i:]] # this URL too: it never got through + stopped = stop + resp = result["response"] + what = result.get("libraryId") or (resp.get("error") if isinstance(resp, dict) else "") or "" + print(f"[{i + 1}/{len(plans)}] {p['input']}: {result['status']} {what}", file=sys.stderr) + if stop: # the queue won't drain mid-loop, a rate limit won't lift, a bad key stays bad + break + if code: + failed.append(p["input"]) + first_failure = first_failure or code + except KeyboardInterrupt: + interrupted = True + if not stopped: # by position, so duplicates are kept; the URL in flight may have been accepted + not_submitted = [q["input"] for q in plans[len(results):]] + finally: + signal.signal(signal.SIGTERM, previous) # a second signal now stops the process as usual + if interrupted: # the run is incomplete: say so before anything else + exit_code = EXIT_INTERRUPTED + elif first_failure: # a real refusal matters more than "try again later" + exit_code = first_failure + elif stopped == "auth": + exit_code = EXIT_AUTH + elif stopped == "queue": + exit_code = EXIT_QUEUE + elif stopped == "rate": + exit_code = EXIT_RATE + else: + exit_code = 0 + if not many and not interrupted: + out(results[0]) + sys.exit(exit_code) + summary = {"results": results} + if failed: + summary["failed"] = failed + if not_submitted: + summary["notSubmitted"] = not_submitted + if interrupted: + summary["interrupted"] = True + summary["next"] = ("stopped before finishing: resubmit notSubmitted (safe even if the first one " + "was already accepted: Context7 answers library-already-exists)") + elif stopped == "queue": + summary["next"] = ("Context7's queue holds 5 libraries per user. Resubmit notSubmitted once some " + "finish (`wait `), or rerun add with --queue (run it in the background).") + elif stopped == "rate": + summary["next"] = "rate limited: wait a few minutes, then resubmit notSubmitted" + elif stopped == "auth": + summary["next"] = "the API key was refused (401): fix the key, then resubmit notSubmitted" + out(summary) + sys.exit(exit_code) def library_info(lib_id): @@ -532,6 +681,16 @@ def multipart(fields, file_field, file_path): return head + payload + f"\r\n--{boundary}--\r\n".encode(), f"multipart/form-data; boundary={boundary}" +def size_hint(ext, size): + how = {".pdf": "Split it by pages and upload each part, e.g. `qpdf --empty --pages in.pdf 1-3 -- in-p1-3.pdf`; " + "put the page range in the file name and --title.", + ".docx": "Split the document into smaller files (or remove large images) and upload each part."}.get( + ext, "Split the spec into smaller files (for example by tag) or remove large embedded examples.") + return (f"The file is {size:,} bytes ({size / 1e6:.2f} MB); Context7 refuses request bodies over about 4.5 MB in practice " + f"(413 FUNCTION_PAYLOAD_TOO_LARGE), and this script refuses files over {MAX_UPLOAD_BYTES:,} bytes to leave " + f"room for the form envelope. {how}") + + def cmd_upload(args): ext = os.path.splitext(args.file)[1].lower() if ext not in UPLOAD_ENDPOINT: @@ -545,15 +704,32 @@ def cmd_upload(args): if args.description: fields["description"] = args.description size = os.path.getsize(args.file) + too_big = size > MAX_UPLOAD_BYTES + split_hint = size_hint(ext, size) if not args.apply: - out({"dryRun": True, "would": f"POST {API}{path}", "file": args.file, "bytes": size, "fields": fields, - "note": "Uploaded files are private to the teamspace (source type uploaded_files), " - "not subject to the public allowlist."}) + dry = {"dryRun": True, "would": f"POST {API}{path}", "file": args.file, "bytes": size, "fields": fields, + "note": "Uploaded files are private to the teamspace (source type uploaded_files), " + "not subject to the public allowlist. The library id is built from the file name " + "(for a PDF: /pdf/--), not from --title: rename the file " + "first if its name says nothing."} + if too_big: + dry["sizeWarning"] = split_hint + out(dry) return + if too_big and not args.skip_size_check: + fail(EXIT_USAGE, split_hint + " Nothing was sent. If Context7 raised the limit, rerun with --skip-size-check.") status, data = call("POST", path, form=multipart(fields, file_field, args.file)) + result = {"status": status, "response": data} if status == 200 and isinstance(data, dict): log("upload", file=os.path.basename(args.file), libraryId=data.get("libraryName")) - out({"status": status, "response": data}) + result["libraryId"] = data.get("libraryName") + elif status == 413: + result["meaning"] = split_hint + elif status == 0: + result["meaning"] = "network error: check the connection and retry" + if size > LARGE_UPLOAD_BYTES: # a big body can also be cut off by the size limit + result["meaning"] += ". The file is large, so Context7 may have refused it for size: " + split_hint + out(result) if status != 200: sys.exit(http_exit_code(status, data)) @@ -593,7 +769,7 @@ def cmd_wait(args): def cmd_log(_): if not os.path.exists(LOG_PATH): - print("(nothing logged yet)") + print("nothing logged yet", file=sys.stderr) # stdout stays JSON lines (here: none) return with open(LOG_PATH) as f: sys.stdout.write(f.read()) @@ -602,25 +778,60 @@ def cmd_log(_): def main(): p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) sub = p.add_subparsers(dest="cmd", required=True) - sub.add_parser("whoami").set_defaults(fn=cmd_whoami) - s = sub.add_parser("check"); s.add_argument("inputs", nargs="+"); s.set_defaults(fn=cmd_check) - s = sub.add_parser("allow"); s.add_argument("entries", nargs="+") - s.add_argument("--remove", action="store_true"); s.add_argument("--apply", action="store_true") + apply_help = "make the change; without it the command is a dry run that only prints what it would do" + + def cmd(name, purpose): + return sub.add_parser(name, help=purpose, description=purpose + " Exit codes: see `c7.py --help`.") + + s = cmd("whoami", "Show plan, role, policy mode and which list admits libraries.") + s.set_defaults(fn=cmd_whoami) + s = cmd("check", "Report whether each input is indexed, fresh and allowed by the teamspace policy.") + s.add_argument("inputs", nargs="+", + help="repo URL, owner/repo, library id, context7.com URL, docs/llms.txt/OpenAPI URL, " + "GitHub user/org URL, or a name") + s.set_defaults(fn=cmd_check) + s = cmd("allow", "Add or remove allowlist / wild-card entries.") + s.add_argument("entries", nargs="+", help="/owner/repo (one library), /owner (all of it), or a docs domain") + s.add_argument("--remove", action="store_true", help="remove the entries instead of adding them") + s.add_argument("--apply", action="store_true", help=apply_help) s.set_defaults(fn=cmd_allow) - s = sub.add_parser("add"); s.add_argument("url") - s.add_argument("--type", choices=list(ADD_ENDPOINT)); s.add_argument("--private", action="store_true") - s.add_argument("--generate-docs", action="store_true"); s.add_argument("--base-url") - s.add_argument("--git-token-env", help="name of an env var holding a git token (never pass the token itself)") - s.add_argument("--apply", action="store_true"); s.set_defaults(fn=cmd_add) - s = sub.add_parser("upload"); s.add_argument("file"); s.add_argument("--title"); s.add_argument("--description") - s.add_argument("--apply", action="store_true"); s.set_defaults(fn=cmd_upload) - s = sub.add_parser("refresh"); s.add_argument("library_id"); s.add_argument("--apply", action="store_true") + s = cmd("add", "Submit repos, websites, llms.txt or OpenAPI URLs for indexing.") + s.add_argument("urls", nargs="+", metavar="url", help="one or more sources; all are validated before any is sent") + s.add_argument("--type", choices=list(ADD_ENDPOINT), + help="force the source type when it can't be detected (one URL only)") + s.add_argument("--private", action="store_true", help="index a private repository (paid plan)") + s.add_argument("--generate-docs", action="store_true", + help="private repositories only: let Context7 generate docs from the code") + s.add_argument("--base-url", help="websites only: crawl only pages under this URL (one URL only)") + s.add_argument("--git-token-env", metavar="VAR", + help="name of an env var holding a git token for repositories (never pass the token itself)") + s.add_argument("--queue", action="store_true", + help="when the 5-submission queue is full, wait and retry instead of stopping") + s.add_argument("--queue-timeout", type=int, default=None, metavar="SEC", + help=f"with --queue, per URL: give up waiting for a free slot after SEC seconds " + f"(default {DEFAULT_QUEUE_TIMEOUT})") + s.add_argument("--apply", action="store_true", help=apply_help) + s.set_defaults(fn=cmd_add) + s = cmd("upload", "Upload a PDF, DOCX or OpenAPI file (private to the teamspace, max ~4.5 MB).") + s.add_argument("file", help="a .pdf, .docx, or OpenAPI .json/.yaml/.yml file") + s.add_argument("--title", help="library display name (the id still comes from the file name)") + s.add_argument("--description", help="short summary of the document") + s.add_argument("--skip-size-check", action="store_true", + help="send a file over the ~4.5 MB limit anyway (only if Context7 raised the limit)") + s.add_argument("--apply", action="store_true", help=apply_help) + s.set_defaults(fn=cmd_upload) + s = cmd("refresh", "Re-crawl or re-parse a stale library (daily limit).") + s.add_argument("library_id", help="library id, e.g. /owner/repo") + s.add_argument("--apply", action="store_true", help=apply_help) s.set_defaults(fn=cmd_refresh) - s = sub.add_parser("wait"); s.add_argument("library_id") - s.add_argument("--timeout", type=int, default=900); s.add_argument("--interval", type=int, default=20) + s = cmd("wait", "Poll until a library is indexed and served.") + s.add_argument("library_id", help="library id, e.g. /owner/repo") + s.add_argument("--timeout", type=int, default=900, metavar="SEC", help="give up after SEC seconds (default 900)") + s.add_argument("--interval", type=int, default=20, metavar="SEC", help="seconds between polls (default 20)") s.add_argument("--changed", action="store_true", help="after a refresh: wait until lastUpdateDate moves") s.set_defaults(fn=cmd_wait) - sub.add_parser("log").set_defaults(fn=cmd_log) + s = cmd("log", "Print what this skill changed before (registry.jsonl, one JSON object per line).") + s.set_defaults(fn=cmd_log) args = p.parse_args() args.fn(args) From f0b1dbd7db4e8bd2b0e01d6ff82547563c13f390 Mon Sep 17 00:00:00 2001 From: Alex Samson Date: Sun, 22 Nov 2026 22:14:13 +0700 Subject: [PATCH 2/3] Add offline tests, CI and README badges - tests/test_c7.py: 46 unittest tests for c7.py with the Context7 API stubbed (no key, no network): input classification, website ids, add (single, several URLs, queue, refusals, validation, interrupts), upload (size limit, hints, 413, network errors), call() network failures, log and --help - CI on push to main and on pull requests: tests on Python 3.8 to 3.13, syntax check, skill validation against the Agent Skills specification (skills-ref 0.1.1) and a coverage report - README: CI, Python, license, last-commit, Agent Skills and Context7 badges, and how to run the tests Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 49 +++++ .gitignore | 1 + README.md | 18 ++ tests/test_c7.py | 396 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 464 insertions(+) create mode 100644 .github/workflows/ci.yml create mode 100644 tests/test_c7.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..f86e974 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,49 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +permissions: + contents: read + +jobs: + test: + name: Tests (Python ${{ matrix.python }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + python: ["3.9", "3.10", "3.11", "3.12", "3.13"] + os: [ubuntu-latest] + include: + - python: "3.8" # the oldest version SKILL.md promises; not built for ubuntu-24.04 + os: ubuntu-22.04 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python }} + - name: Syntax check + run: python -m py_compile skills/context7-add/scripts/c7.py + - name: Tests (offline, API stubbed) + run: python -m unittest discover -s tests -v + + skill: + name: Skill and coverage + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - name: Install tools + run: python -m pip install "skills-ref==0.1.1" "coverage==7.6.1" + - name: Validate the skill (Agent Skills specification) + run: agentskills validate skills/context7-add + - name: Coverage + run: | + python -m coverage run --source=skills/context7-add/scripts -m unittest discover -s tests + python -m coverage report -m diff --git a/.gitignore b/.gitignore index df8c3b3..1efc48c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ registry.jsonl __pycache__/ .DS_Store +.coverage diff --git a/README.md b/README.md index 046182a..ef4491b 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,12 @@ # context7-add +[![CI](https://github.com/saalse/context7-add/actions/workflows/ci.yml/badge.svg)](https://github.com/saalse/context7-add/actions/workflows/ci.yml) +[![Python 3.8+](https://img.shields.io/badge/python-3.8%2B-blue)](skills/context7-add/scripts/c7.py) +[![License: MIT](https://img.shields.io/github/license/saalse/context7-add)](LICENSE) +[![Last commit](https://img.shields.io/github/last-commit/saalse/context7-add)](https://github.com/saalse/context7-add/commits/main) +[![Agent Skills](https://img.shields.io/badge/Agent%20Skills-spec-8A2BE2)](https://agentskills.io/specification) +[![Context7](https://img.shields.io/badge/Context7-indexed-00A86B)](https://context7.com/saalse/context7-add) + An agent skill that makes documentation available through [Context7](https://context7.com) when it isn't yet: it **indexes** a repo, docs site, `llms.txt`, OpenAPI spec or PDF/DOCX file if Context7 doesn't have it, and **allows** it in your teamspace policy so your API key and the @@ -76,6 +83,17 @@ queue full, file too large). See `python3 $C7 --help`. The skill follows the [Agent Skills specification](https://agentskills.io/specification). +## Development + +The tests are offline: they stub the Context7 API, so they need no key or network. + +```bash +python3 -m unittest discover -s tests -v +``` + +CI runs them on Python 3.8 to 3.13, validates the skill against the Agent Skills +specification, and prints a coverage report. + ## Notes - Submitting a public source adds it to Context7's public index. Use `--private` for internal diff --git a/tests/test_c7.py b/tests/test_c7.py new file mode 100644 index 0000000..8118d80 --- /dev/null +++ b/tests/test_c7.py @@ -0,0 +1,396 @@ +"""Offline tests for skills/context7-add/scripts/c7.py. + +The Context7 API is stubbed: nothing is sent, and no API key is needed. +Run from the repo root: python3 -m unittest discover -s tests -v +""" +import contextlib +import importlib.util +import io +import json +import os +import signal +import tempfile +import unittest +import urllib.error +import urllib.request + +C7_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "skills", "context7-add", "scripts", "c7.py") + +A = "https://github.com/acme/a" +B = "https://github.com/acme/b" +C = "https://docs.acme.dev/" +QUEUE_FULL = (400, {"error": "user-has-active-task", + "message": "You already have 5 libraries being processed or queued."}) + + +def load_c7(): + spec = importlib.util.spec_from_file_location("c7", C7_PATH) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def ok(lib): + return 200, {"libraryName": lib, "message": "Repository submitted successfully"} + + +class C7TestCase(unittest.TestCase): + """Loads a fresh c7 module per test with call(), log() and sleep stubbed.""" + + def setUp(self): + self.c7 = load_c7() + self.sent, self.logged, self.sleeps = [], [], [] + self.c7.log = lambda action, **kw: self.logged.append((action, kw)) + self.c7.time.sleep = lambda s: self.sleeps.append(s) + self.c7.api_key = lambda: "test-key" + self.sigterm = signal.getsignal(signal.SIGTERM) + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.addCleanup(signal.signal, signal.SIGTERM, self.sigterm) + + def run_c7(self, argv, responses=()): + """Run main() with queued responses (or exceptions); return (exit_code, json_or_None, stderr).""" + queue = list(responses) + + def fake_call(method, path, body=None, params=None, form=None): + self.sent.append((method, path, body)) + item = queue.pop(0) + if isinstance(item, BaseException): + raise item + return item + + self.c7.call = fake_call + out, err, code = io.StringIO(), io.StringIO(), 0 + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + import sys + old_argv, sys.argv = sys.argv, ["c7.py"] + list(argv) + try: + self.c7.main() + except SystemExit as e: + code = e.code or 0 + finally: + sys.argv = old_argv + text = out.getvalue() + return code, (json.loads(text) if text.strip() else None), err.getvalue() + + def make_file(self, name, size=None, data=None): + path = os.path.join(self.tmp.name, name) + with open(path, "wb") as f: + if data is not None: + f.write(data) + else: + f.truncate(size) + return path + + +class TestClassify(C7TestCase): + def test_repo_url(self): + c = self.c7.classify("https://github.com/Acme/Widgets.git") + self.assertEqual((c["kind"], c["libraryId"]), ("github", "/acme/widgets")) + + def test_owner_repo_shorthand(self): + self.assertEqual(self.c7.classify("acme/widgets")["libraryId"], "/acme/widgets") + + def test_library_id_and_context7_url(self): + self.assertEqual(self.c7.classify("/acme/widgets")["kind"], "library_id") + self.assertEqual(self.c7.classify("https://context7.com/acme/widgets")["libraryId"], "/acme/widgets") + + def test_github_owner(self): + self.assertEqual(self.c7.classify("https://github.com/acme")["kind"], "repo_owner") + + def test_llms_openapi_website(self): + self.assertEqual(self.c7.classify("https://docs.acme.dev/llms.txt")["kind"], "llmstxt") + self.assertEqual(self.c7.classify("https://acme.dev/openapi.yaml")["kind"], "openapi") + self.assertEqual(self.c7.classify("https://docs.acme.dev/guide/")["kind"], "website") + + +class TestWebsiteIds(C7TestCase): + def test_documented_shapes(self): + self.assertEqual(self.c7.website_id_candidates("https://docs.github.com/en")[0], "/websites/github_en") + self.assertEqual(self.c7.website_id_candidates("https://example.com/docs/guide/")[0], + "/websites/example_guide") + self.assertEqual(self.c7.website_id_candidates("https://docs.astral.sh/")[0], "/websites/astral_sh") + + +class TestAddSingle(C7TestCase): + def test_success_keeps_old_shape(self): + code, o, err = self.run_c7(["add", A, "--apply"], [ok("/acme/a")]) + self.assertEqual(code, 0) + self.assertEqual(o["libraryId"], "/acme/a") + self.assertNotIn("results", o) + self.assertIn("[1/1] " + A + ": 200 /acme/a", err) + self.assertEqual(self.logged[0][1]["libraryId"], "/acme/a") + + def test_already_exists_is_success(self): + code, o, _ = self.run_c7(["add", A, "--apply"], + [(400, {"error": "library-already-exists", "message": "The library /acme/a already exists."})]) + self.assertEqual((code, o["libraryId"]), (0, "/acme/a")) + + def test_already_exists_with_null_message(self): + code, o, _ = self.run_c7(["add", A, "--apply"], [(400, {"error": "library-already-exists", "message": None})]) + self.assertEqual((code, o["libraryId"]), (0, "/acme/a")) + + def test_200_with_non_json_body_is_success(self): + code, _, _ = self.run_c7(["add", A, "--apply"], [(200, "OK")]) + self.assertEqual(code, 0) + + def test_queue_full_exits_9(self): + code, o, _ = self.run_c7(["add", A, "--apply"], [QUEUE_FULL]) + self.assertEqual(code, 9) + self.assertIn("--queue", o["meaning"]) + + def test_dry_run_sends_nothing(self): + code, o, _ = self.run_c7(["add", A]) + self.assertEqual(code, 0) + self.assertTrue(o["dryRun"]) + self.assertEqual(o["input"], A) + self.assertEqual(self.sent, []) + + +class TestAddMany(C7TestCase): + def test_queue_full_stops_and_lists_the_rest(self): + code, o, _ = self.run_c7(["add", A, B, C, "--apply"], [ok("/acme/a"), QUEUE_FULL]) + self.assertEqual(code, 9) + self.assertEqual(len(self.sent), 2) + self.assertEqual(o["notSubmitted"], [B, C]) + self.assertEqual(o["results"][0]["libraryId"], "/acme/a") + + def test_queue_waits_and_retries(self): + code, o, err = self.run_c7(["add", A, B, "--queue", "--apply"], + [ok("/acme/a"), QUEUE_FULL, QUEUE_FULL, ok("/acme/b")]) + self.assertEqual(code, 0) + self.assertEqual(self.sleeps, [30, 30]) + self.assertIn("retrying " + B, err) + self.assertNotIn("notSubmitted", o) + + def test_queue_timeout_gives_up(self): + code, o, _ = self.run_c7(["add", A, "--queue", "--queue-timeout", "0", "--apply"], [QUEUE_FULL]) + self.assertEqual(code, 9) + self.assertIn("larger --queue-timeout", o["meaning"]) + + def test_other_refusals_go_to_failed_and_keep_going(self): + code, o, _ = self.run_c7(["add", A, C, "--apply"], + [(400, {"error": "library-already-exists", "message": "The library /acme/a already exists."}), + (422, {"error": "not_documentation_website", "message": "Website score 1 below threshold 9"})]) + self.assertEqual(code, 7) + self.assertEqual(o["failed"], [C]) + self.assertIn("documentation site", o["results"][1]["meaning"]) + + def test_real_refusal_wins_over_queue_full(self): + code, o, _ = self.run_c7(["add", A, B, C, "--apply"], + [(403, {"error": "access_denied", "message": "not allowed"}), QUEUE_FULL]) + self.assertEqual(code, 5) + self.assertEqual((o["failed"], o["notSubmitted"]), ([A], [B, C])) + + def test_rate_limit_stops(self): + code, o, _ = self.run_c7(["add", A, B, C, "--apply"], + [ok("/acme/a"), (429, {"error": "rate_limited", "message": "slow down"})]) + self.assertEqual(code, 6) + self.assertEqual(o["notSubmitted"], [B, C]) + + def test_bad_key_stops_and_its_url_is_resubmittable(self): + code, o, _ = self.run_c7(["add", A, B, C, "--apply"], [(401, {"error": "unauthorized", "message": "bad key"})]) + self.assertEqual(code, 3) + self.assertEqual(len(self.sent), 1) + self.assertNotIn("failed", o) + self.assertEqual(o["notSubmitted"], [A, B, C]) + + def test_dry_run_lists_every_input(self): + code, o, _ = self.run_c7(["add", A, C]) + self.assertEqual([r["input"] for r in o["results"]], [A, C]) + self.assertEqual(self.sent, []) + + def test_git_token_goes_to_repositories_only(self): + os.environ["C7_TEST_TOKEN"] = "token-value" + self.addCleanup(os.environ.pop, "C7_TEST_TOKEN") + self.run_c7(["add", A, C, "--git-token-env", "C7_TEST_TOKEN", "--apply"], + [ok("/acme/a"), ok("/websites/acme_dev")]) + self.assertEqual(self.sent[0][2]["gitToken"], "token-value") + self.assertNotIn("gitToken", self.sent[1][2]) + + +class TestAddValidation(C7TestCase): + def assert_refused(self, argv): + code, _, _ = self.run_c7(argv) + self.assertEqual(code, 2) + self.assertEqual(self.sent, []) + + def test_base_url_needs_one_url(self): + self.assert_refused(["add", A, C, "--base-url", C, "--apply"]) + + def test_type_needs_one_url(self): + self.assert_refused(["add", A, C, "--type", "website", "--apply"]) + + def test_queue_timeout_needs_queue(self): + self.assert_refused(["add", A, "--queue-timeout", "10", "--apply"]) + + def test_negative_queue_timeout(self): + self.assert_refused(["add", A, "--queue", "--queue-timeout", "-5", "--apply"]) + + def test_one_bad_input_stops_the_batch(self): + self.assert_refused(["add", A, "https://acme.dev/llms-api.txt", "--apply"]) + + +class TestAddInterrupted(C7TestCase): + def test_partial_summary_exit_130(self): + code, o, err = self.run_c7(["add", A, B, C, "--apply"], [ok("/acme/a"), KeyboardInterrupt()]) + self.assertEqual(code, 130) + self.assertTrue(o["interrupted"]) + self.assertEqual(o["results"][0]["libraryId"], "/acme/a") + self.assertEqual(o["notSubmitted"], [B, C]) + + def test_single_url(self): + code, o, _ = self.run_c7(["add", A, "--apply"], [KeyboardInterrupt()]) + self.assertEqual((code, o["notSubmitted"]), (130, [A])) + + def test_130_wins_over_earlier_refusal(self): + code, o, _ = self.run_c7(["add", A, B, "--apply"], + [(403, {"error": "access_denied", "message": "x"}), KeyboardInterrupt()]) + self.assertEqual(code, 130) + self.assertEqual((o["failed"], o["notSubmitted"]), ([A], [B])) + + def test_duplicates_kept_by_position(self): + _, o, _ = self.run_c7(["add", A, A, "--apply"], [ok("/acme/a"), KeyboardInterrupt()]) + self.assertEqual(o["notSubmitted"], [A]) + + def test_sigterm_handler_restored(self): + self.run_c7(["add", A, "--apply"], [ok("/acme/a")]) + self.assertIs(signal.getsignal(signal.SIGTERM), self.sigterm) + + +class TestUpload(C7TestCase): + def test_small_file_dry_run(self): + path = self.make_file("small.pdf", data=b"%PDF-1.4\n" + b"0" * 1000) + code, o, _ = self.run_c7(["upload", path, "--title", "T"]) + self.assertEqual(code, 0) + self.assertNotIn("sizeWarning", o) + self.assertEqual(o["fields"], {"projectTitle": "T"}) + self.assertIn("file name", o["note"]) + self.assertEqual(self.sent, []) + + def test_upload_ok(self): + path = self.make_file("small.pdf", data=b"%PDF-1.4\n") + code, o, _ = self.run_c7(["upload", path, "--apply"], [(200, {"libraryName": "/pdf/x-small.pdf-y"})]) + self.assertEqual((code, o["libraryId"]), (0, "/pdf/x-small.pdf-y")) + self.assertEqual(self.logged[0][0], "upload") + + def test_openapi_uses_library_title(self): + path = self.make_file("spec.yaml", data=b"openapi: 3.0.0\n") + _, o, _ = self.run_c7(["upload", path, "--title", "API"]) + self.assertIn("openapi-upload", o["would"]) + self.assertEqual(o["fields"], {"libraryTitle": "API"}) + + def test_big_file_warns_and_refuses(self): + path = self.make_file("big.pdf", size=5_000_000) + _, o, _ = self.run_c7(["upload", path]) + self.assertIn("qpdf", o["sizeWarning"]) + code, _, err = self.run_c7(["upload", path, "--apply"]) + self.assertEqual(code, 2) + self.assertEqual(self.sent, []) + self.assertIn("--skip-size-check", err) + + def test_size_shown_in_bytes_just_over_the_limit(self): + path = self.make_file("just.pdf", size=4_400_001) + _, o, _ = self.run_c7(["upload", path]) + self.assertIn("4,400,001 bytes", o["sizeWarning"]) + + def test_docx_hint_has_no_qpdf(self): + path = self.make_file("big.docx", size=4_450_000) + _, o, _ = self.run_c7(["upload", path]) + self.assertNotIn("qpdf", o["sizeWarning"]) + + def test_413_explained(self): + path = self.make_file("big.pdf", size=5_000_000) + code, o, _ = self.run_c7(["upload", path, "--apply", "--skip-size-check"], + [(413, "Request Entity Too Large\n\nFUNCTION_PAYLOAD_TOO_LARGE\n")]) + self.assertEqual(code, 2) + self.assertIn("Split", o["meaning"]) + + def test_network_error_small_file_has_no_size_advice(self): + path = self.make_file("small.pdf", data=b"%PDF-1.4\n") + code, o, _ = self.run_c7(["upload", path, "--apply"], [(0, {"error": "network", "message": "reset"})]) + self.assertEqual(code, 1) + self.assertNotIn("4.5 MB", o["meaning"]) + + def test_network_error_large_file_mentions_size(self): + path = self.make_file("mid.pdf", size=3_500_000) + _, o, _ = self.run_c7(["upload", path, "--apply"], [(0, {"error": "network", "message": "reset"})]) + self.assertIn("4.5 MB", o["meaning"]) + + def test_unsupported_type(self): + path = self.make_file("notes.txt", data=b"x") + code, _, _ = self.run_c7(["upload", path]) + self.assertEqual(code, 2) + + +class TestCall(unittest.TestCase): + def setUp(self): + self.c7 = load_c7() + self.c7.api_key = lambda: "test-key" + self.addCleanup(setattr, urllib.request, "urlopen", urllib.request.urlopen) + + def call_with(self, exc): + def raiser(*a, **k): + raise exc + urllib.request.urlopen = raiser + return self.c7.call("POST", "/v2/add/pdf-upload", form=(b"x", "multipart/form-data; boundary=b")) + + def test_network_failures_return_json(self): + import http.client + import socket + for exc in (ConnectionResetError(54, "reset"), socket.timeout("timed out"), + http.client.RemoteDisconnected("closed"), http.client.IncompleteRead(b"x"), + BrokenPipeError(32, "Broken pipe"), urllib.error.URLError("no route")): + with self.subTest(exc=type(exc).__name__): + status, data = self.call_with(exc) + self.assertEqual((status, data["error"]), (0, "network")) + + def test_error_body_cut_off_keeps_status(self): + class CutBody: + def read(self, *a): + raise ConnectionResetError(54, "reset") + + def close(self): + pass + + status, data = self.call_with(urllib.error.HTTPError("https://context7.com/api/x", 413, "Too Large", {}, CutBody())) + self.assertEqual((status, data), (413, "")) + + +class TestLog(unittest.TestCase): + def test_write_failure_only_warns(self): + c7 = load_c7() + c7.LOG_PATH = os.path.join(tempfile.gettempdir(), "no-such-dir-c7-test", "registry.jsonl") + err = io.StringIO() + with contextlib.redirect_stderr(err): + c7.log("add", libraryId="/acme/a") + self.assertIn("could not write", err.getvalue()) + + def test_empty_log_prints_nothing_on_stdout(self): + c7 = load_c7() + c7.LOG_PATH = os.path.join(tempfile.gettempdir(), "no-such-dir-c7-test", "registry.jsonl") + out = io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()): + c7.cmd_log(None) + self.assertEqual(out.getvalue(), "") + + +class TestHelp(C7TestCase): + def test_every_command_has_help(self): + for name in ("whoami", "check", "allow", "add", "upload", "refresh", "wait", "log"): + with self.subTest(command=name): + out = io.StringIO() + with contextlib.redirect_stdout(out): + import sys + old, sys.argv = sys.argv, ["c7.py", name, "--help"] + try: + self.c7.main() + except SystemExit as e: + self.assertEqual(e.code, 0) + finally: + sys.argv = old + self.assertIn("Exit codes", out.getvalue()) + + +if __name__ == "__main__": + unittest.main() From be48e5aa3604adce4507ee88da8a62edd50046a5 Mon Sep 17 00:00:00 2001 From: Alex Samson Date: Sun, 22 Nov 2026 22:25:59 +0700 Subject: [PATCH 3/3] Harden CI and tests before the first run CI: - run every job on ubuntu-24.04: setup-python has no Python 3.8 or 3.9 builds for newer Ubuntu images, so ubuntu-latest would break those jobs - test Python 3.8 to 3.14 - actions/checkout and actions/setup-python v7; coverage 7.17.4, with the coverage table also written to the job summary Tests (58): - stub c7's own time module instead of patching the global time.sleep - help tests no longer depend on the terminal width; each command's own purpose and every flag's help text are checked - fail when a stubbed response is left unused - new: a real SIGTERM during a request (guarded, so a missing handler fails that test instead of killing the run), check, allow, refresh (queue full gives 9), api_key from the environment and from ~/.claude.json, multipart, network errors during add c7.py: build_parser() for testable help; close an HTTP error response when reading its body fails; say a network error during add is safe to resubmit and counts as a failure; clearer exit 9 help. context7.json: keep tests/ and .github/ out of the Context7 index. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 22 ++-- README.md | 2 +- context7.json | 6 +- docs/commands.mdx | 9 +- skills/context7-add/SKILL.md | 4 +- skills/context7-add/scripts/c7.py | 24 +++- tests/test_c7.py | 200 +++++++++++++++++++++++++++--- 7 files changed, 224 insertions(+), 43 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f86e974..49c35b7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -12,18 +12,15 @@ permissions: jobs: test: name: Tests (Python ${{ matrix.python }}) - runs-on: ${{ matrix.os }} + # Pinned: setup-python has no Python 3.8 or 3.9 builds for newer Ubuntu images. + runs-on: ubuntu-24.04 strategy: fail-fast: false matrix: - python: ["3.9", "3.10", "3.11", "3.12", "3.13"] - os: [ubuntu-latest] - include: - - python: "3.8" # the oldest version SKILL.md promises; not built for ubuntu-24.04 - os: ubuntu-22.04 + python: ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13", "3.14"] steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 + - uses: actions/checkout@v7 + - uses: actions/setup-python@v7 with: python-version: ${{ matrix.python }} - name: Syntax check @@ -33,17 +30,18 @@ jobs: skill: name: Skill and coverage - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 + - uses: actions/checkout@v7 + - uses: actions/setup-python@v7 with: python-version: "3.12" - name: Install tools - run: python -m pip install "skills-ref==0.1.1" "coverage==7.6.1" + run: python -m pip install "skills-ref==0.1.1" "coverage==7.17.4" - name: Validate the skill (Agent Skills specification) run: agentskills validate skills/context7-add - name: Coverage run: | python -m coverage run --source=skills/context7-add/scripts -m unittest discover -s tests python -m coverage report -m + python -m coverage report -m --format=markdown >> "$GITHUB_STEP_SUMMARY" diff --git a/README.md b/README.md index ef4491b..b9190ab 100644 --- a/README.md +++ b/README.md @@ -91,7 +91,7 @@ The tests are offline: they stub the Context7 API, so they need no key or networ python3 -m unittest discover -s tests -v ``` -CI runs them on Python 3.8 to 3.13, validates the skill against the Agent Skills +CI runs them on Python 3.8 to 3.14, validates the skill against the Agent Skills specification, and prints a coverage report. ## Notes diff --git a/context7.json b/context7.json index 4df0653..7f82260 100644 --- a/context7.json +++ b/context7.json @@ -3,5 +3,9 @@ "url": "https://context7.com/saalse/context7-add", "public_key": "pk_6NlYtGWUARfV17Y6zVg0H", "projectTitle": "context7-add", - "description": "Agent skill that indexes repos, docs sites, llms.txt, OpenAPI specs and files in Context7 and allows them in your teamspace policy so the Context7 MCP serves them." + "description": "Agent skill that indexes repos, docs sites, llms.txt, OpenAPI specs and files in Context7 and allows them in your teamspace policy so the Context7 MCP serves them.", + "excludeFolders": [ + "tests", + ".github" + ] } diff --git a/docs/commands.mdx b/docs/commands.mdx index 70be9a6..4d0bd80 100644 --- a/docs/commands.mdx +++ b/docs/commands.mdx @@ -41,7 +41,7 @@ python3 scripts/c7.py add https://github.com/acme/a https://github.com/acme/b ht ``` All inputs are validated before anything is sent, and stderr gets one progress line per URL. -When the queue fills up, Context7 answers 429 (rate limited), or the key is refused (401), +When the queue is full, when Context7 rate-limits you (429), or when the key is refused (401), `add` stops: the remaining URLs would be refused too. With several URLs, the output lists what was not submitted, starting with the URL that hit the limit: @@ -58,8 +58,9 @@ was not submitted, starting with the URL that hit the limit: } ``` -URLs refused for another reason (policy, not a documentation site, and so on) are listed in -`failed`; they aren't retried, and the exit code is the first such refusal. Only when nothing +URLs refused for another reason (policy, not a documentation site, and so on) or lost to a +network error are listed in `failed`; they aren't retried, and the exit code is the first such +failure. A network error is safe to resubmit. Only when nothing failed for real is the exit code 3 (key refused), 9 (queue full) or 6 (rate limited). To submit everything in one go, add `--queue`. When the queue is full, `add` then waits 30 s @@ -85,5 +86,5 @@ type is detected per URL otherwise. | 6 | rate limited | | 7 | unprocessable (no or too few docs), or not a documentation website | | 8 | `wait` timed out | -| 9 | submission queue full (5 libraries already processing). `add`: resubmit `notSubmitted` or use `--queue`; `refresh`, `upload`: try again later | +| 9 | submission queue full (5 libraries already processing). `add`: resubmit later (with several URLs, `notSubmitted` lists which) or use `--queue`; `refresh`, `upload`: try again later | | 130 | `add`: interrupted; the partial summary lists `notSubmitted` | diff --git a/skills/context7-add/SKILL.md b/skills/context7-add/SKILL.md index 5d3dd91..891265a 100644 --- a/skills/context7-add/SKILL.md +++ b/skills/context7-add/SKILL.md @@ -79,8 +79,8 @@ These come from real runs and contradict reasonable assumptions: - **Only 5 submissions in flight per user.** More get `400 user-has-active-task` (exit 9). Pass all URLs to one `add … --queue --apply` and run it in the background. It waits for free slots, so don't write your own retry loop. Without `--queue`, resubmit the output's - `notSubmitted` list later. URLs refused for other reasons are in `failed`, and the exit code - is the first such refusal. `--type` and `--base-url` need one URL per call. + `notSubmitted` list later. URLs refused for other reasons, or lost to a network error, are in + `failed`, and the exit code is the first such failure. `--type` and `--base-url` need one URL per call. - **Uploads stop at about 4.5 MB** (`413 FUNCTION_PAYLOAD_TOO_LARGE`). `upload` refuses larger files before sending. Split a PDF by pages (`qpdf --empty --pages in.pdf 1-3 -- in-p1-3.pdf`), one upload per part, with the page range in the file name and `--title`. diff --git a/skills/context7-add/scripts/c7.py b/skills/context7-add/scripts/c7.py index 5a0cc38..2c7268c 100755 --- a/skills/context7-add/scripts/c7.py +++ b/skills/context7-add/scripts/c7.py @@ -42,11 +42,12 @@ 6 rate limited (429) 7 library unprocessable (no or too few docs, or not a documentation website) 8 wait timed out - 9 submission queue full (5 libraries already processing). add: `notSubmitted` lists - what to resubmit, or rerun with --queue; refresh / upload: try again later + 9 submission queue full (5 libraries already processing). add: resubmit later (with + several URLs, `notSubmitted` lists which) or rerun with --queue; refresh / upload: + try again later 130 add: interrupted (Ctrl-C or SIGTERM); the partial summary lists `notSubmitted` -With several URLs, add exits 130 if interrupted, else with the first real refusal (listed in -`failed`), else 3, 9 or 6. A 401, 429 or full queue stops the run; that URL and the rest are +With several URLs, add exits 130 if interrupted, else with the first failure (a refusal or a +network error, listed in `failed`), else 3, 9 or 6. A 401, 429 or full queue stops the run; that URL and the rest are listed in `notSubmitted`. """ import argparse @@ -166,6 +167,11 @@ def call(method, path, body=None, params=None, form=None): raw = e.read() except (OSError, http.client.HTTPException): raw = b"" + finally: + try: + e.close() + except (OSError, http.client.HTTPException): + pass except urllib.error.URLError as e: return 0, {"error": "network", "message": str(e.reason)} except (OSError, http.client.HTTPException) as e: @@ -555,6 +561,8 @@ def submit_add(p, args): "Look for a docs subdomain or an llms.txt, or read it on the web") elif status == 429: result["meaning"] = "not submitted: rate limited; wait a few minutes, then resubmit" + elif status == 0: + result["meaning"] = "network error: Context7 may not have received it; safe to resubmit" stop = "queue" if err == QUEUE_FULL else "rate" if status == 429 else "auth" if status == 401 else None return result, code, stop @@ -775,7 +783,7 @@ def cmd_log(_): sys.stdout.write(f.read()) -def main(): +def build_parser(): p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) sub = p.add_subparsers(dest="cmd", required=True) apply_help = "make the change; without it the command is a dry run that only prints what it would do" @@ -832,7 +840,11 @@ def cmd(name, purpose): s.set_defaults(fn=cmd_wait) s = cmd("log", "Print what this skill changed before (registry.jsonl, one JSON object per line).") s.set_defaults(fn=cmd_log) - args = p.parse_args() + return p + + +def main(): + args = build_parser().parse_args() args.fn(args) diff --git a/tests/test_c7.py b/tests/test_c7.py index 8118d80..11f48e9 100644 --- a/tests/test_c7.py +++ b/tests/test_c7.py @@ -9,7 +9,10 @@ import json import os import signal +import sys import tempfile +import time +import types import unittest import urllib.error import urllib.request @@ -41,7 +44,8 @@ def setUp(self): self.c7 = load_c7() self.sent, self.logged, self.sleeps = [], [], [] self.c7.log = lambda action, **kw: self.logged.append((action, kw)) - self.c7.time.sleep = lambda s: self.sleeps.append(s) + # c7's own `time` name only: the real time module stays untouched + self.c7.time = types.SimpleNamespace(time=time.time, sleep=lambda s: self.sleeps.append(s)) self.c7.api_key = lambda: "test-key" self.sigterm = signal.getsignal(signal.SIGTERM) self.tmp = tempfile.TemporaryDirectory() @@ -62,7 +66,6 @@ def fake_call(method, path, body=None, params=None, form=None): self.c7.call = fake_call out, err, code = io.StringIO(), io.StringIO(), 0 with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): - import sys old_argv, sys.argv = sys.argv, ["c7.py"] + list(argv) try: self.c7.main() @@ -70,6 +73,7 @@ def fake_call(method, path, body=None, params=None, form=None): code = e.code or 0 finally: sys.argv = old_argv + self.assertEqual(queue, [], "stubbed responses left unused") text = out.getvalue() return code, (json.loads(text) if text.strip() else None), err.getvalue() @@ -195,6 +199,13 @@ def test_bad_key_stops_and_its_url_is_resubmittable(self): self.assertNotIn("failed", o) self.assertEqual(o["notSubmitted"], [A, B, C]) + def test_network_error_goes_to_failed_and_says_resubmit(self): + code, o, _ = self.run_c7(["add", A, B, "--apply"], + [(0, {"error": "network", "message": "timed out"}), ok("/acme/b")]) + self.assertEqual(code, 1) + self.assertEqual(o["failed"], [A]) + self.assertIn("safe to resubmit", o["results"][0]["meaning"]) + def test_dry_run_lists_every_input(self): code, o, _ = self.run_c7(["add", A, C]) self.assertEqual([r["input"] for r in o["results"]], [A, C]) @@ -358,9 +369,14 @@ def close(self): class TestLog(unittest.TestCase): + def missing_path(self): + base = tempfile.mkdtemp() + self.addCleanup(os.rmdir, base) + return os.path.join(base, "missing", "registry.jsonl") + def test_write_failure_only_warns(self): c7 = load_c7() - c7.LOG_PATH = os.path.join(tempfile.gettempdir(), "no-such-dir-c7-test", "registry.jsonl") + c7.LOG_PATH = self.missing_path() err = io.StringIO() with contextlib.redirect_stderr(err): c7.log("add", libraryId="/acme/a") @@ -368,7 +384,7 @@ def test_write_failure_only_warns(self): def test_empty_log_prints_nothing_on_stdout(self): c7 = load_c7() - c7.LOG_PATH = os.path.join(tempfile.gettempdir(), "no-such-dir-c7-test", "registry.jsonl") + c7.LOG_PATH = self.missing_path() out = io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()): c7.cmd_log(None) @@ -376,20 +392,170 @@ def test_empty_log_prints_nothing_on_stdout(self): class TestHelp(C7TestCase): - def test_every_command_has_help(self): - for name in ("whoami", "check", "allow", "add", "upload", "refresh", "wait", "log"): + PURPOSES = {"whoami": "Show plan, role, policy mode", "check": "Report whether each input is indexed", + "allow": "Add or remove allowlist", "add": "Submit repos, websites", + "upload": "Upload a PDF, DOCX or OpenAPI file", "refresh": "Re-crawl or re-parse", + "wait": "Poll until a library is indexed", "log": "Print what this skill changed"} + + def help_text(self, *argv): + out = io.StringIO() + with contextlib.redirect_stdout(out): + old, sys.argv = sys.argv, ["c7.py"] + list(argv) + ["--help"] + try: + self.c7.main() + except SystemExit as e: + self.assertEqual(e.code, 0) + finally: + sys.argv = old + return " ".join(out.getvalue().split()) # argparse wraps to the terminal width + + def test_every_command_has_its_own_purpose(self): + for name, purpose in self.PURPOSES.items(): + with self.subTest(command=name): + self.assertIn(purpose, self.help_text(name)) + + def test_top_level_help_lists_exit_codes(self): + text = self.help_text() + for code in ("9 submission queue full", "130 add: interrupted"): + self.assertIn(code, text) + + def test_every_flag_has_help_text(self): + for name in self.PURPOSES: with self.subTest(command=name): - out = io.StringIO() - with contextlib.redirect_stdout(out): - import sys - old, sys.argv = sys.argv, ["c7.py", name, "--help"] - try: - self.c7.main() - except SystemExit as e: - self.assertEqual(e.code, 0) - finally: - sys.argv = old - self.assertIn("Exit codes", out.getvalue()) + sub = self.subparsers()[name] + for action in sub._actions: + if action.option_strings and action.dest != "help": + self.assertTrue(action.help, f"{name} {action.option_strings} has no help") + + def subparsers(self): + parser = self.c7.build_parser() + action = next(a for a in parser._actions if a.__class__.__name__ == "_SubParsersAction") + return action.choices + + +@unittest.skipUnless(hasattr(signal, "SIGTERM") and os.name == "posix", "needs POSIX signals") +class TestRealSigterm(C7TestCase): + def test_sigterm_during_a_request_prints_partial_summary(self): + """A real SIGTERM, delivered while the second request is in flight, runs c7's own handler.""" + + class StraySigterm(Exception): + pass + + def guard(signum, frame): # if c7 failed to install its handler, fail this test, not the run + raise StraySigterm("SIGTERM reached the test's guard handler: c7 did not install its own") + + signal.signal(signal.SIGTERM, guard) + answers = [ok("/acme/a")] + + def fake_call(method, path, body=None, params=None, form=None): + self.sent.append((method, path, body)) + if answers: + return answers.pop(0) + self.assertIs(signal.getsignal(signal.SIGTERM), self.c7._sigterm) + os.kill(os.getpid(), signal.SIGTERM) # c7's handler turns this into KeyboardInterrupt + time.sleep(5) # interrupted as soon as the signal is handled + return ok("/acme/b") + + self.c7.call = fake_call + code, o, _ = self.run_main(["add", A, B, C, "--apply"]) + self.assertEqual(code, 130) + self.assertTrue(o["interrupted"]) + self.assertEqual(o["notSubmitted"], [B, C]) + self.assertIs(signal.getsignal(signal.SIGTERM), guard) # c7 put back what it found + + def run_main(self, argv): + out, err, code = io.StringIO(), io.StringIO(), 0 + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + old_argv, sys.argv = sys.argv, ["c7.py"] + list(argv) + try: + self.c7.main() + except SystemExit as e: + code = e.code or 0 + finally: + sys.argv = old_argv + return code, json.loads(out.getvalue()), err.getvalue() + + +class TestOtherCommands(C7TestCase): + POLICIES = (200, {"libraryFilters": {"mode": "select", "select": {"allowedLibraries": ["/acme"]}}, + "accessibleLibraryCount": 10, "sourceTypes": {}}) + + def test_check_library_id_covered(self): + search = (200, {"results": [{"id": "/acme/a", "title": "A", "state": "finalized", + "lastUpdateDate": "2026-01-01", "totalSnippets": 5, "totalTokens": 9}]}) + code, o, _ = self.run_c7(["check", "/acme/a"], [self.POLICIES, (200, {}), search]) + r = o["results"][0] + self.assertEqual(code, 0) + self.assertEqual((r["state"], r["coveredBy"]), ("ready", ["/acme"])) + self.assertEqual(r["index"]["totalSnippets"], 5) + + def test_check_blocked_library(self): + _, o, _ = self.run_c7(["check", "/other/x"], + [self.POLICIES, (403, {"error": "access_denied", "message": "no"})]) + self.assertEqual((o["results"][0]["state"], o["results"][0]["coveredBy"]), + ("blocked_by_policy_or_plan", [])) + + def test_allow_dry_run_and_already_present(self): + code, o, _ = self.run_c7(["allow", "/other/x"], + [self.POLICIES, (200, {"currentAccessibleLibraryCount": 10, "accessibleLibraryCount": 11})]) + self.assertEqual(code, 0) + self.assertTrue(o["dryRun"]) + self.assertEqual(self.sent[1][2]["dryRun"], True) + self.assertEqual(o["operation"], {"add": ["/other/x"]}) + _, o, _ = self.run_c7(["allow", "/acme"], [self.POLICIES]) + self.assertEqual(o["alreadyInDesiredState"], ["/acme"]) + + def test_allow_rejects_bad_entry(self): + code, _, _ = self.run_c7(["allow", "not an entry"]) + self.assertEqual(code, 2) + + def test_refresh_dry_run_and_queue_full(self): + search = (200, {"results": []}) + code, o, _ = self.run_c7(["refresh", "/acme/a"], [search]) + self.assertEqual((code, o["dryRun"]), (0, True)) + code, _, _ = self.run_c7(["refresh", "/acme/a", "--apply"], [search, QUEUE_FULL]) + self.assertEqual(code, 9) + + +class TestHelpers(C7TestCase): + def test_api_key_from_env(self): + c7 = load_c7() + old = os.environ.get("CONTEXT7_API_KEY") + os.environ["CONTEXT7_API_KEY"] = "env-key" + self.addCleanup(lambda: os.environ.pop("CONTEXT7_API_KEY") if old is None + else os.environ.__setitem__("CONTEXT7_API_KEY", old)) + self.assertEqual(c7.api_key(), "env-key") + + def test_api_key_from_claude_json(self): + c7 = load_c7() + home = tempfile.mkdtemp() + self.addCleanup(lambda: (os.remove(os.path.join(home, ".claude.json")), os.rmdir(home))) + with open(os.path.join(home, ".claude.json"), "w") as f: + json.dump({"mcpServers": {"context7-admin": {"headers": {"CONTEXT7_API_KEY": "admin-key"}}, + "context7": {"headers": {"Authorization": "Bearer file-key"}}}}, f) + saved = {k: os.environ.get(k) for k in ("HOME", "CONTEXT7_API_KEY")} + + def restore(): + for k, v in saved.items(): + if v is None: + os.environ.pop(k, None) + else: + os.environ[k] = v + + self.addCleanup(restore) + os.environ.pop("CONTEXT7_API_KEY", None) + os.environ["HOME"] = home + self.assertEqual(c7.api_key(), "file-key") # the admin MCP entry is skipped + + def test_multipart_body(self): + path = self.make_file("doc.pdf", data=b"%PDF-1.4 body") + body, ctype = self.c7.multipart({"projectTitle": "T"}, "pdfFile", path) + boundary = ctype.split("boundary=")[1] + self.assertTrue(ctype.startswith("multipart/form-data; boundary=")) + self.assertIn(b'name="projectTitle"\r\n\r\nT', body) + self.assertIn(b'name="pdfFile"; filename="doc.pdf"', body) + self.assertIn(b"Content-Type: application/pdf", body) + self.assertTrue(body.endswith(("--" + boundary + "--\r\n").encode())) if __name__ == "__main__":