Skill: jaylane/context7-docs (version 1.0.0)

--- name: context7-docs description: >- Fetches up-to-date, version-specific documentation and code examples for any programming library or framework from Context7. Use this skill when the user needs current API docs, code examples, setup guides, or configuration help for any library, package, or framework — especially when you are unsure if your training data is current. Activate when the user mentions needing docs, examples, or asks about library APIs, versions, or configuration. license: MIT compatibility: Requires curl, jq, and internet access. Optional CONTEXT7_API_KEY env var for higher rate limits. metadata: author: context7 version: "1.0" source: https://github.com/upstash/context7 allowed-tools: Bash(curl:*) Bash(jq:*) Read --- # Context7 Documentation Lookup ## Overview Context7 provides up-to-date, version-specific documentation and code examples for thousands of programming libraries and frameworks. Use this skill whenever you need current documentation that may differ from your training data — especially for fast-moving libraries like Next.js, React, Supabase, LangChain, etc. ## When to Use This Skill - The user asks about a library's API and you're unsure if your knowledge is current - The user requests code examples for a specific library version - The user asks for setup, configuration, or migration guides - The user mentions "use context7" or asks for up-to-date docs - You need to verify whether an API or method still exists in the latest version ## Two-Step Workflow ### Step 1: Resolve the Library ID First, find the Context7-compatible library ID for the library the user is asking about. ```bash bash scripts/resolve-library.sh --query "How to set up authentication" --library-name "next.js" ``` This returns a list of matching libraries with: - **Library ID** — e.g., `/vercel/next.js` (use this in Step 2) - **Name** and **Description** - **Code Snippets** — number of available examples (prefer higher counts) - **Benchmark Score** — quality indicator out of 100 (prefer higher) - **Source Reputation** — High, Medium, Low, or Unknown (prefer High/Medium) - **Versions** — available version-specific IDs like `/vercel/next.js/v14.3.0` **Selection criteria** — Pick the library that best matches based on: 1. Name similarity (exact matches first) 2. Description relevance to the user's task 3. Higher Code Snippet count 4. Higher Benchmark Score 5. High or Medium Source Reputation If the user already provides a library ID in `/org/project` format, skip this step. ### Step 2: Query the Documentation Use the library ID from Step 1 to fetch relevant documentation: ```bash bash scripts/query-docs.sh --library-id "/vercel/next.js" --query "How to set up authentication with JWT" ``` This returns documentation text with code examples directly relevant to the query. ### Shortcut: Direct curl You can also call the API directly without the scripts: **Search for a library:** ```bash curl -s "https://context7.com/api/search" \ -H "Content-Type: application/json" \ ${CONTEXT7_API_KEY:+-H "Authorization: Bearer $CONTEXT7_API_KEY"} \ -d '{"query": "How to set up auth", "libraryName": "next.js"}' | jq . ``` **Query documentation:** ```bash curl -s "https://context7.com/api/context" \ -H "Content-Type: application/json" \ ${CONTEXT7_API_KEY:+-H "Authorization: Bearer $CONTEXT7_API_KEY"} \ -d '{"query": "JWT authentication middleware", "libraryId": "/vercel/next.js"}' | jq . ``` ## Important Guidelines - **Call resolve at most 3 times** per question. If you can't find what you need, use the best result. - **Call query-docs at most 3 times** per question. Use the best information you have. - **Be specific with queries.** Good: "How to set up authentication with JWT in Express.js". Bad: "auth". - **Use versions when relevant.** If the user specifies a version, look for it in the resolve results and use the versioned library ID (e.g., `/vercel/next.js/v14.3.0`). - **Do NOT include sensitive data** (API keys, passwords, credentials) in your queries — they are sent to the Context7 API. ## Handling Edge Cases | Situation | Action | |-----------|--------| | No results from resolve | Try a different library name or broader search term | | Multiple good matches | Pick the one with the best name match + highest snippet count | | User specifies a version | Look for versioned IDs in resolve results | | Empty docs response | Try a more specific or different query | | Rate limit hit | Wait a moment and retry, or suggest the user set CONTEXT7_API_KEY | ## Environment Setup For higher rate limits, set a free API key: ```bash export CONTEXT7_API_KEY="your-key-here" ``` Get a free key at: https://context7.com/dashboard ## Next Steps - See [API-REFERENCE.md](references/API-REFERENCE.md) for full endpoint documentation - See [LIBRARY-ID-FORMAT.md](references/LIBRARY-ID-FORMAT.md) for details on library ID format and versioning

path: LICENSE.txt
content: MIT License

Copyright (c) 2025

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


path: scripts/resolve-library.sh
content: #!/usr/bin/env bash
#
# resolve-library.sh — Search for a Context7-compatible library ID
#
# Usage:
#   bash resolve-library.sh --query "your question" --library-name "library-name"
#
# Environment:
#   CONTEXT7_API_KEY (optional) — API key for higher rate limits
#
# Dependencies: curl, jq

set -euo pipefail

# ── Defaults ──────────────────────────────────────────────────────────────────
QUERY=""
LIBRARY_NAME=""
API_BASE="https://context7.com/api"

# ── Parse arguments ───────────────────────────────────────────────────────────
while [[ $# -gt 0 ]]; do
  case "$1" in
    --query)
      QUERY="$2"
      shift 2
      ;;
    --library-name)
      LIBRARY_NAME="$2"
      shift 2
      ;;
    --help|-h)
      echo "Usage: bash resolve-library.sh --query \"your question\" --library-name \"library-name\""
      echo ""
      echo "Options:"
      echo "  --query          The question or task (used for relevance ranking)"
      echo "  --library-name   The library/package name to search for"
      echo "  --help, -h       Show this help message"
      echo ""
      echo "Environment:"
      echo "  CONTEXT7_API_KEY   Optional API key for higher rate limits"
      exit 0
      ;;
    *)
      echo "Error: Unknown option '$1'. Use --help for usage." >&2
      exit 1
      ;;
  esac
done

# ── Validate inputs ──────────────────────────────────────────────────────────
if [[ -z "$QUERY" ]]; then
  echo "Error: --query is required." >&2
  echo "Usage: bash resolve-library.sh --query \"your question\" --library-name \"library-name\"" >&2
  exit 1
fi

if [[ -z "$LIBRARY_NAME" ]]; then
  echo "Error: --library-name is required." >&2
  echo "Usage: bash resolve-library.sh --query \"your question\" --library-name \"library-name\"" >&2
  exit 1
fi

# ── Check dependencies ────────────────────────────────────────────────────────
for cmd in curl jq; do
  if ! command -v "$cmd" &>/dev/null; then
    echo "Error: '$cmd' is required but not found. Please install it." >&2
    exit 1
  fi
done

# ── Build request ─────────────────────────────────────────────────────────────
AUTH_HEADER=""
if [[ -n "${CONTEXT7_API_KEY:-}" ]]; then
  AUTH_HEADER="Authorization: Bearer $CONTEXT7_API_KEY"
fi

PAYLOAD=$(jq -n \
  --arg query "$QUERY" \
  --arg libraryName "$LIBRARY_NAME" \
  '{query: $query, libraryName: $libraryName}')

# ── Make API call ─────────────────────────────────────────────────────────────
HTTP_RESPONSE=$(curl -s -w "\n%{http_code}" \
  "${API_BASE}/search" \
  -H "Content-Type: application/json" \
  ${AUTH_HEADER:+-H "$AUTH_HEADER"} \
  -d "$PAYLOAD" 2>&1) || {
  echo "Error: curl request failed." >&2
  exit 1
}

# Split response body and status code
HTTP_BODY=$(echo "$HTTP_RESPONSE" | sed '$d')
HTTP_CODE=$(echo "$HTTP_RESPONSE" | tail -n1)

# ── Handle errors ─────────────────────────────────────────────────────────────
if [[ "$HTTP_CODE" -ge 400 ]]; then
  echo "Error: API returned HTTP $HTTP_CODE" >&2
  echo "$HTTP_BODY" >&2
  exit 1
fi

# ── Format output ─────────────────────────────────────────────────────────────
# Check if results exist
RESULT_COUNT=$(echo "$HTTP_BODY" | jq -r 'if type == "array" then length elif .results then (.results | length) else 0 end' 2>/dev/null || echo "0")

if [[ "$RESULT_COUNT" == "0" ]]; then
  echo "No libraries found matching '$LIBRARY_NAME'."
  echo "Try a different or broader library name."
  exit 0
fi

echo "=== Context7 Library Search Results ==="
echo "Query: $QUERY"
echo "Library Name: $LIBRARY_NAME"
echo "Results: $RESULT_COUNT"
echo ""

# Handle both array and {results: [...]} response shapes
echo "$HTTP_BODY" | jq -r '
  (if type == "array" then . elif .results then .results else [] end) |
  to_entries[] |
  "--- Result \(.key + 1) ---",
  "Library ID: \(.value.id // .value.libraryId // "N/A")",
  "Name: \(.value.name // .value.title // "N/A")",
  "Description: \(.value.description // "N/A")",
  "Code Snippets: \(.value.codeSnippets // .value.snippetCount // "N/A")",
  "Benchmark Score: \(.value.benchmarkScore // .value.benchmark // "N/A")",
  "Source Reputation: \(.value.sourceReputation // .value.reputation // "N/A")",
  (if .value.versions then "Versions: \(.value.versions | join(", "))" else empty end),
  ""
' 2>/dev/null || {
  # Fallback: just output raw JSON if parsing fails
  echo "Raw response:"
  echo "$HTTP_BODY" | jq . 2>/dev/null || echo "$HTTP_BODY"
}


path: scripts/query-docs.sh
content: #!/usr/bin/env bash
#
# query-docs.sh — Query Context7 for library documentation and code examples
#
# Usage:
#   bash query-docs.sh --library-id "/org/project" --query "your question"
#
# Environment:
#   CONTEXT7_API_KEY (optional) — API key for higher rate limits
#
# Dependencies: curl, jq

set -euo pipefail

# ── Defaults ──────────────────────────────────────────────────────────────────
LIBRARY_ID=""
QUERY=""
API_BASE="https://context7.com/api"

# ── Parse arguments ───────────────────────────────────────────────────────────
while [[ $# -gt 0 ]]; do
  case "$1" in
    --library-id)
      LIBRARY_ID="$2"
      shift 2
      ;;
    --query)
      QUERY="$2"
      shift 2
      ;;
    --help|-h)
      echo "Usage: bash query-docs.sh --library-id \"/org/project\" --query \"your question\""
      echo ""
      echo "Options:"
      echo "  --library-id   Context7 library ID (e.g., /vercel/next.js, /mongodb/docs)"
      echo "  --query        The question or task to get documentation for"
      echo "  --help, -h     Show this help message"
      echo ""
      echo "Environment:"
      echo "  CONTEXT7_API_KEY   Optional API key for higher rate limits"
      echo ""
      echo "Examples:"
      echo "  bash query-docs.sh --library-id \"/vercel/next.js\" --query \"middleware setup\""
      echo "  bash query-docs.sh --library-id \"/supabase/supabase\" --query \"authentication with email\""
      echo "  bash query-docs.sh --library-id \"/vercel/next.js/v14.3.0\" --query \"app router\""
      exit 0
      ;;
    *)
      echo "Error: Unknown option '$1'. Use --help for usage." >&2
      exit 1
      ;;
  esac
done

# ── Validate inputs ──────────────────────────────────────────────────────────
if [[ -z "$LIBRARY_ID" ]]; then
  echo "Error: --library-id is required." >&2
  echo "Usage: bash query-docs.sh --library-id \"/org/project\" --query \"your question\"" >&2
  echo "" >&2
  echo "First run resolve-library.sh to find the library ID." >&2
  exit 1
fi

if [[ -z "$QUERY" ]]; then
  echo "Error: --query is required." >&2
  echo "Usage: bash query-docs.sh --library-id \"/org/project\" --query \"your question\"" >&2
  exit 1
fi

# Validate library ID format (should start with /)
if [[ "$LIBRARY_ID" != /* ]]; then
  echo "Warning: Library ID should start with '/'. Prepending '/'." >&2
  LIBRARY_ID="/$LIBRARY_ID"
fi

# ── Check dependencies ────────────────────────────────────────────────────────
for cmd in curl jq; do
  if ! command -v "$cmd" &>/dev/null; then
    echo "Error: '$cmd' is required but not found. Please install it." >&2
    exit 1
  fi
done

# ── Build request ─────────────────────────────────────────────────────────────
AUTH_HEADER=""
if [[ -n "${CONTEXT7_API_KEY:-}" ]]; then
  AUTH_HEADER="Authorization: Bearer $CONTEXT7_API_KEY"
fi

PAYLOAD=$(jq -n \
  --arg query "$QUERY" \
  --arg libraryId "$LIBRARY_ID" \
  '{query: $query, libraryId: $libraryId}')

# ── Make API call ─────────────────────────────────────────────────────────────
HTTP_RESPONSE=$(curl -s -w "\n%{http_code}" \
  "${API_BASE}/context" \
  -H "Content-Type: application/json" \
  ${AUTH_HEADER:+-H "$AUTH_HEADER"} \
  -d "$PAYLOAD" 2>&1) || {
  echo "Error: curl request failed." >&2
  exit 1
}

# Split response body and status code
HTTP_BODY=$(echo "$HTTP_RESPONSE" | sed '$d')
HTTP_CODE=$(echo "$HTTP_RESPONSE" | tail -n1)

# ── Handle errors ─────────────────────────────────────────────────────────────
if [[ "$HTTP_CODE" -ge 400 ]]; then
  echo "Error: API returned HTTP $HTTP_CODE" >&2
  echo "$HTTP_BODY" >&2

  if [[ "$HTTP_CODE" == "404" ]]; then
    echo "" >&2
    echo "Library '$LIBRARY_ID' was not found. Run resolve-library.sh to find the correct ID." >&2
  elif [[ "$HTTP_CODE" == "429" ]]; then
    echo "" >&2
    echo "Rate limit exceeded. Set CONTEXT7_API_KEY for higher limits." >&2
    echo "Get a free key at: https://context7.com/dashboard" >&2
  fi
  exit 1
fi

# ── Output documentation ─────────────────────────────────────────────────────
# Try to extract the text/data field; fall back to raw output
DOC_TEXT=$(echo "$HTTP_BODY" | jq -r '.data // .text // .content // empty' 2>/dev/null)

if [[ -n "$DOC_TEXT" && "$DOC_TEXT" != "null" ]]; then
  echo "=== Context7 Documentation ==="
  echo "Library: $LIBRARY_ID"
  echo "Query: $QUERY"
  echo "================================"
  echo ""
  echo "$DOC_TEXT"
else
  # If the response is plain text or a different structure, output as-is
  IS_JSON=$(echo "$HTTP_BODY" | jq empty 2>/dev/null && echo "yes" || echo "no")
  if [[ "$IS_JSON" == "yes" ]]; then
    echo "=== Context7 Documentation ==="
    echo "Library: $LIBRARY_ID"
    echo "Query: $QUERY"
    echo "================================"
    echo ""
    echo "$HTTP_BODY" | jq -r '
      if type == "array" then
        .[] | 
        (if .title then "## \(.title)\n" else "" end) +
        (if .content then .content else . end) +
        "\n---\n"
      else
        tostring
      end
    ' 2>/dev/null || echo "$HTTP_BODY"
  else
    echo "$HTTP_BODY"
  fi
fi


path: references/LIBRARY-ID-FORMAT.md
content: # Context7 Library ID Format

## Overview

Context7 uses a unique library ID format to identify documentation sources. Understanding this format helps you query the right docs efficiently.

## Format

```
/org/project
```

or with a specific version:

```
/org/project/version
```

### Components

| Component | Description | Example |
|-----------|-------------|---------|
| `org` | The organization or author of the library | `vercel`, `mongodb`, `facebook` |
| `project` | The library or project name | `next.js`, `docs`, `react` |
| `version` | Optional version identifier | `v14.3.0`, `v5.0.0-canary.87` |

## Examples

### Common Library IDs

| Library | Context7 ID |
|---------|-------------|
| Next.js | `/vercel/next.js` |
| React | `/facebook/react` |
| Express | `/expressjs/express` |
| MongoDB | `/mongodb/docs` |
| Supabase | `/supabase/supabase` |
| LangChain (Python) | `/langchain-ai/langchainjs` |
| Tailwind CSS | `/tailwindlabs/tailwindcss` |
| Prisma | `/prisma/docs` |

### Version-Specific IDs

| Library + Version | Context7 ID |
|-------------------|-------------|
| Next.js 14.3.0 | `/vercel/next.js/v14.3.0` |
| Next.js canary | `/vercel/next.js/v14.3.0-canary.87` |

## How to Get a Library ID

### Option 1: Use the resolve-library script

```bash
bash scripts/resolve-library.sh --query "your question" --library-name "library-name"
```

The output will include the library ID for each match.

### Option 2: User provides it directly

Users may provide a library ID directly in their prompt using the slash format:

```
Use library /supabase/supabase for docs
```

When a user provides an ID in `/org/project` format, you can skip the resolve step and go directly to querying docs.

### Option 3: Construct from the GitHub URL

For many libraries, the Context7 ID mirrors the GitHub repository path:

```
https://github.com/vercel/next.js  →  /vercel/next.js
https://github.com/expressjs/express  →  /expressjs/express
```

However, this is not guaranteed — some libraries use different IDs (e.g., `/mongodb/docs` instead of `/mongodb/mongo`). Always verify with the resolve step if unsure.

## Using Versions

When a user asks about a specific version:

1. Run the resolve step to see available versions
2. Look for the version in the `versions` field of the results
3. Use the versioned ID (e.g., `/vercel/next.js/v14.3.0`) in your query

If the exact version is not listed, use the base library ID — Context7 will return the latest docs by default.

## Important Notes

- Library IDs are **case-sensitive**
- Library IDs always **start with `/`**
- Not every GitHub repo maps directly to a Context7 library ID — always verify with resolve if unsure
- The resolve endpoint ranks results by relevance to your query, so the first result is usually the best match


path: references/API-REFERENCE.md
content: # Context7 API Reference

## Base URL

```
https://context7.com/api
```

## Authentication

Authentication is optional but recommended for higher rate limits.

**Header:** `Authorization: Bearer <API_KEY>`

Get a free API key at: https://context7.com/dashboard

API keys start with the prefix `ctx7sk`.

Alternative header names also accepted:
- `Context7-API-Key: <key>`
- `X-API-Key: <key>`

---

## Endpoints

### POST /search

Searches for libraries matching a given name and ranks results by relevance to a query.

**Request Body (JSON):**

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `query` | string | Yes | The user's question or task. Used for relevance ranking. |
| `libraryName` | string | Yes | The library/package name to search for. |

**Example Request:**

```bash
curl -s "https://context7.com/api/search" \
  -H "Content-Type: application/json" \
  -H "[REDACTED_SECRET]" \
  -d '{
    "query": "How to create a REST API",
    "libraryName": "express"
  }'
```

**Response:**

Returns an array (or `{results: [...]}` object) of matching libraries. Each result includes:

| Field | Type | Description |
|-------|------|-------------|
| `id` / `libraryId` | string | Context7-compatible library ID (e.g., `/expressjs/express`) |
| `name` / `title` | string | Human-readable library name |
| `description` | string | Short summary of the library |
| `codeSnippets` / `snippetCount` | number | Number of available code examples |
| `benchmarkScore` / `benchmark` | number | Quality indicator (0–100, higher is better) |
| `sourceReputation` / `reputation` | string | Authority level: "High", "Medium", "Low", or "Unknown" |
| `versions` | array | Available version-specific IDs (e.g., `/org/project/v1.2.3`) |

**Selection Guidance:**

When multiple results are returned, select based on:
1. **Name similarity** — Exact matches first
2. **Description relevance** — Best match to the user's intent
3. **Code Snippets** — Higher counts mean more examples available
4. **Benchmark Score** — Higher is better quality
5. **Source Reputation** — Prefer "High" or "Medium"

---

### POST /context

Retrieves documentation and code examples for a specific library, filtered by a query.

**Request Body (JSON):**

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `query` | string | Yes | The question or task to get relevant docs for. Be specific. |
| `libraryId` | string | Yes | Context7 library ID from `/search` or user-provided. |

**Example Request:**

```bash
curl -s "https://context7.com/api/context" \
  -H "Content-Type: application/json" \
  -H "[REDACTED_SECRET]" \
  -d '{
    "query": "How to set up middleware for authentication",
    "libraryId": "/expressjs/express"
  }'
```

**Response:**

Returns documentation content. The response may include:

| Field | Type | Description |
|-------|------|-------------|
| `data` / `text` / `content` | string | Documentation text with code examples |

The content typically includes:
- Relevant documentation sections
- Code examples and snippets
- API signatures and parameter descriptions
- Links to source documentation

---

## Rate Limiting

- **Without API key:** Lower rate limits apply (suitable for occasional use)
- **With API key:** Higher rate limits (free key available at context7.com/dashboard)
- **HTTP 429 response:** Rate limit exceeded; wait and retry

## Best Practices

1. **Be specific with queries.** The API uses the query to rank and filter results. More specific queries yield more relevant documentation.
2. **Limit calls.** Do not call `/search` or `/context` more than 3 times per user question.
3. **Do not send sensitive data.** Queries are processed by the Context7 API. Never include API keys, passwords, credentials, or personal data.
4. **Use versioned library IDs** when the user specifies a particular version.

## Error Responses

| HTTP Code | Meaning |
|-----------|---------|
| 400 | Bad request — check your request body |
| 401 | Unauthorized — invalid API key |
| 404 | Library not found — verify the library ID |
| 429 | Rate limited — wait and retry, or add an API key |
| 500 | Server error — retry after a moment |


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: clean (LOW)