Context7 Integration Guide

Technology: context7 · Category: tooling · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/context7

Insight:

Context7 feeds live, version-accurate library docs into Claude Code and is the engine behind this repo's Documentation Policy. Always resolve-library-id then query-docs before writing integration code. The only levers are a tight, single-concept query and (new in 4.x) an optional language. The free plan is capped at 1,000 calls a month, so sign every client in with OAuth or a ctx7sk- key. Check the owner of the library ID you pick, because forks and mirrors often outrank the official repo.

 ██████╗ ██████╗ ███╗   ██╗████████╗███████╗██╗  ██╗████████╗███████╗
██╔════╝██╔═══██╗████╗  ██║╚══██╔══╝██╔════╝╚██╗██╔╝╚══██╔══╝╚════██║
██║     ██║   ██║██╔██╗ ██║   ██║   █████╗   ╚███╔╝    ██║       ██╔╝
██║     ██║   ██║██║╚██╗██║   ██║   ██╔══╝   ██╔██╗    ██║      ██╔╝
╚██████╗╚██████╔╝██║ ╚████║   ██║   ███████╗██╔╝ ██╗   ██║      ██║
 ╚═════╝ ╚═════╝ ╚═╝  ╚═══╝   ╚═╝   ╚══════╝╚═╝  ╚═╝   ╚═╝      ╚═╝

Context7 Integration Guide

Focus: Feeding live, version-accurate library documentation into Claude Code (and Cursor, VS Code, claude.ai) through the Context7 MCP server, so generated code uses real, current APIs.

Overview

Context7 (by Upstash) indexes library documentation (GitHub repos, doc websites, llms.txt files, OpenAPI specs) and serves the slice relevant to a question to an AI agent. Without it, the model writes from training data that may be a year old. With it, the model resolves the library, pulls current docs, and writes against them.

flowchart LR
    A["Library name + query"] --> B["resolve-library-id"]
    B --> C["Context7 library ID"]
    C --> D["query-docs"]
    D --> E["Live version-accurate docs"]
    E --> F["Claude Code writes grounded code"]

There are four ways to use the same index:

Surface What it is Use it for
MCP server (@upstash/context7-mcp, or hosted https://mcp.context7.com/mcp) Two agent tools: resolve-library-id and query-docs Claude Code, Cursor, VS Code, claude.ai, every MCP client
ctx7 CLI ctx7 library / ctx7 docs in a terminal, plus ctx7 setup to wire up agents One-off lookups, and the "CLI + Skills" mode (no MCP)
REST API (https://context7.com/api/...) GET /api/v2/libs/search, GET /api/v2/context, GET /api/v3/search Your own scripts and pipelines
TypeScript SDK (@upstash/context7-sdk) and AI SDK tools (@upstash/context7-tools-ai-sdk) Typed wrappers over the REST API Agents you build yourself

Current versions (verified 2026-10-20 with npm view)

Package Version Node
@upstash/context7-mcp 4.4.4 (2026-10-19) >=20.18.1
ctx7 (CLI) 0.8.1 (2026-10-19) >=22.13.0
@upstash/context7-sdk 0.5.1 —
@upstash/context7-tools-ai-sdk 1.0.3 —
@upstash/context7-pi (pi.dev extension) 0.1.3 —

The MCP server also ships as a context7.mcpb bundle on each GitHub release (mcpb-v4.4.4).

Official Documentation

Resource URL
Context7 website https://context7.com
Docs index (append .md to any page) https://context7.com/docs/llms.txt
Claude Code guide https://context7.com/docs/clients/claude-code
Cursor guide https://context7.com/docs/clients/cursor
VS Code guide https://context7.com/docs/clients/vscode
All MCP clients (manual config) https://context7.com/docs/resources/all-clients
CLI reference https://context7.com/docs/clients/cli
API guide https://context7.com/docs/api-guide
Plans and pricing https://context7.com/plans
GitHub https://github.com/upstash/context7
npm (MCP server) https://www.npmjs.com/package/@upstash/context7-mcp

MCP tools (v4.4)

The server exposes exactly two tools. They are read-only (readOnlyHint: true) and each maps to one REST endpoint.

Tool REST endpoint Required params Optional
resolve-library-id GET /api/v2/libs/search libraryName, query —
query-docs GET /api/v2/context libraryId, query language

History: query-docs was called get-library-docs before v4. Its old context7CompatibleLibraryID, topic and tokens parameters are gone. Any rule or slash command that still passes tokens= or topic= is pre-v4.


Setup: remote vs local

The decision comes first:

Remote (hosted) Local (stdio)
Endpoint https://mcp.context7.com/mcp (API key), or https://mcp.context7.com/mcp/oauth (OAuth) npx -y @upstash/context7-mcp
Needs local Node No Yes, Node 20.18.1 or newer
Auth Authorization: Bearer <key> header, or OAuth 2.0 --api-key <key> flag or CONTEXT7_API_KEY env (the flag wins)
OAuth available Yes No. OAuth works only over remote HTTP
Updates Automatic Pin a version or use @latest

codeAmani default: remote. It needs no Node process, has nothing to update, and avoids the Windows npx timeout problems listed under Troubleshooting. Use local stdio only when a client cannot speak HTTP MCP.

flowchart TD
    A["Which client?"] --> B{"Claude Code?"}
    B -->|"yes, interactive"| C["Plugin or ctx7 setup --claude"]
    B -->|"headless / CI / SSH"| D["claude mcp add --transport http + Bearer key"]
    A --> E{"Cursor?"}
    E --> F["~/.cursor/mcp.json remote url + headers"]
    A --> G{"VS Code?"}
    G --> H["Upstash.context7-mcp extension"]
    A --> I{"claude.ai?"}
    I --> J["Context7 connector (Settings > Connectors)"]

Claude Code

Pick one of the following. Installing two of them registers the same tools twice.

1. Context7 plugin (hosted, OAuth, no key).

/plugin marketplace add upstash/context7
/plugin install context7@context7-marketplace

Restart Claude Code, run /mcp, select Context7 and complete the browser sign-in. The plugin does not read CONTEXT7_API_KEY. For headless, SSH or CI hosts, use option 2 or 3.

2. ctx7 setup (one command, needs Node 22.13 or newer).

npx ctx7 setup --claude            # prompts for MCP vs CLI + Skills mode
npx ctx7 setup --mcp --claude      # MCP mode, no prompt
npx ctx7 setup --cli --claude      # CLI + Skills mode: writes a "docs" skill to ~/.claude/skills
npx ctx7 setup --claude --project  # write project config instead of global
npx ctx7 setup --api-key <key>     # reuse an existing key instead of OAuth

Without --api-key it runs the OAuth device flow: it prints a link and a short code you open on any device, so it works over SSH. It then generates a key and writes the MCP entry, a rule file, and a context7-mcp skill. Undo with npx ctx7 remove (--claude, --mcp, --cli, --project, --all narrow it down).

3. Manual claude mcp add.

# Remote (recommended)
claude mcp add --scope user --header "Authorization: Bearer $CONTEXT7_API_KEY" \
  --transport http context7 https://mcp.context7.com/mcp

# Local stdio
claude mcp add --scope user context7 -- npx -y @upstash/context7-mcp --api-key "$CONTEXT7_API_KEY"

Or in a project's .mcp.json (Claude Code expands ${VAR}, so the key stays out of git):

{
  "mcpServers": {
    "context7": {
      "type": "http",
      "url": "https://mcp.context7.com/mcp",
      "headers": { "Authorization": "Bearer ${CONTEXT7_API_KEY}" }
    }
  }
}

For OAuth instead of a key, point url at https://mcp.context7.com/mcp/oauth, drop the header, then run /mcp → Context7 → Authenticate.

Cursor

Edit ~/.cursor/mcp.json (global) or .cursor/mcp.json (project), or use Cursor Settings → Tools & MCP → New MCP Server. There is also a one-click install deeplink in the README. npx ctx7 setup --cursor does the same job.

{
  "mcpServers": {
    "context7": {
      "url": "https://mcp.context7.com/mcp",
      "headers": { "Authorization": "Bearer YOUR_API_KEY" }
    }
  }
}

Local form: "command": "npx", "args": ["-y", "@upstash/context7-mcp", "--api-key", "YOUR_API_KEY"]. Add a rule under Cursor Settings → Rules so you don't have to type "use context7".

VS Code (Copilot agent mode)

Install the Context7 MCP Server extension (Upstash.context7-mcp, VS Code 1.101 or newer). It registers the hosted server automatically, so no mcp.json is needed. Add a key under Settings → Context7: Api Key ("context7.apiKey"). Put it in user settings, not a committed .vscode/settings.json. Confirm with MCP: List Servers.

Manual alternative (.vscode/mcp.json; note the top-level key is servers, not mcpServers):

{
  "servers": {
    "context7": {
      "type": "http",
      "url": "https://mcp.context7.com/mcp",
      "headers": { "Authorization": "Bearer YOUR_API_KEY" }
    }
  }
}

claude.ai (web, desktop, mobile)

Context7 is available as a claude.ai connector: Settings → Connectors. Pick Context7 from the directory, or Add custom connector with the URL https://mcp.context7.com/mcp. It exposes the same two tools with the same schemas, including language. We confirmed this in the connected claude.ai Context7 connector on 2026-10-20. In a claude.ai org, an owner must allow the connector first. Claude Desktop can use the same connector or a local claude_desktop_config.json stdio entry.

Windows notes

If local npx times out on Windows, wrap it with cmd: "command": "cmd", "args": ["/c", "npx", "-y", "@upstash/context7-mcp", "--api-key", "YOUR_API_KEY"]. Switching to the remote server avoids the problem entirely.


API keys, plans and rate limits

Keys. Create them at context7.com/dashboard. The format is ctx7sk-…, and a key is shown once. Revoking a key is immediate and permanent. A key raises your rate limits and is required for private sources and teamspace rules and policies. ctx7 setup and OAuth create or replace keys for you.

Plans (from https://context7.com/plans, read 2026-10-20):

Free Pro Enterprise
Price $0 $10 / seat / month Per seat, from $30/user/month for small teamspaces down to $2.50 at volume; self-serve up to 50 members
Included calls 1,000 API calls / month 2,000 / seat / month (per seat, not pooled) Custom
Over the limit Blocked, then 20 bonus calls per day until the month resets Never blocked: $5 per 1,000 extra calls Custom
Private repos No Yes, parsing costs $5 per 1M tokens (refreshes bill changed content only) Yes
Extras Public repos, basic access control, OAuth 2 Team collaboration, rules, policies SOC 2, SSO (SAML/OIDC), up to 5,000 members and 100 teamspaces, SLA, self-hosted / on-prem

A Search API call (/api/v3/search) counts as one call, the same as a context call. An MCP resolve-library-id + query-docs pair counts as two.

Rate limits. Anonymous use gets "low rate limits", and keyed use gets limits "based on your plan". The exact anonymous numbers are not published. When you hit a limit the API returns HTTP 429 with Retry-After, RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset headers. Check usage in the dashboard Overview tab.


How Context7 works in practice

sequenceDiagram
    participant U as "You"
    participant C as "Claude Code"
    participant M as "Context7 MCP"
    U->>C: "Use the latest library API"
    C->>M: "resolve-library-id with libraryName and query"
    M-->>C: "Candidate library IDs"
    C->>M: "query-docs with libraryId, query, language"
    M-->>C: "Current docs and code snippets"
    C-->>U: "Code matching documented API"

Step 1: resolve the library ID

Tool: resolve-library-id
Input: { "libraryName": "Next.js", "query": "app router caching" }
Output (abridged; benchmark and snippet numbers from the REST search on 2026-10-20):
  - /vercel/next.js         Next.js        benchmark ~77  ~5.9k snippets
  - /websites/nextjs        Next.js        benchmark ~73  ~6.9k snippets
  - /vercel/next-learn      Learn Next.js  ...

Pick the candidate whose owner is the authoritative project first, then compare reputation, snippet count and benchmark score. Benchmark alone misleads. Resolving "Context7" on 2026-10-20 ranked three third-party forks (benchmark 83 to 86) above the official /upstash/context7 (81.9).

Step 2: fetch documentation

Tool: query-docs
Input: { "libraryId": "/vercel/next.js", "query": "app router caching with fetch", "language": "TypeScript" }
Output: code snippets and prose from the current Next.js docs, each with its source URL

Skip step 1 when you already know the ID. The /org/project path on context7.com is the ID.

Library ID formats

Source Example
GitHub (and GitLab/Bitbucket) repo /vercel/next.js
Website /websites/nextjs
llms.txt source /llmstxt/<source>
Package source /packages/<name> or /npm/<name>
Uploaded docs /docs/<name>
Pinned version /vercel/next.js/v16.2.9 or /vercel/next.js@v16.2.9

IDs move. A moved ID returns HTTP 301 library_redirected with a redirectUrl. The API follows it for you, but update stale IDs in rules (see the table below).

Prompt shortcuts


Scoping the query

The query (plus the optional language) is your only control over what comes back.

Session hygiene:


Adding private or your own libraries

Public library (free, anyone can do it): paste a public GitHub URL at context7.com/add-library, or use POST /api/v2/add/repo/github. Context7 indexes .md, .mdx, .markdown, .rst, .txt and .ipynb. It generates docs from source code only when a repo has almost no docs. After that it auto-refreshes based on popularity. The Context7 GitHub Action triggers a refresh on every push.

Own it: claim the library (howto/claiming-libraries) for an admin panel, versions and higher refresh limits. Then commit a context7.json at the repo root:

{
  "$schema": "https://context7.com/schema/context7.json",
  "projectTitle": "codeAmani Tech Stack",
  "description": "Integration guides and conventions for the codeAmani stack",
  "folders": ["docs"],
  "excludeFolders": ["**/archive", "node_modules"],
  "excludeFiles": ["CHANGELOG.md"],
  "rules": ["Use Stripe by default; M-Pesa only for Kenya-targeted projects"],
  "previousVersions": [{ "tag": "v1.0.0" }]
}

excludeFolders always beats folders. projectTitle can be up to 100 characters and description up to 500, and both are moderated (no promotional or agent-instruction text).

Private sources (Pro or Enterprise only): in the teamspace Sources tab, add GitHub, GitLab, Bitbucket, any Git URL, Confluence, or OpenAPI. The API also takes PDF/DOCX uploads (50 MB per file, up to 50 files / 200 MB), llms.txt, websites and Notion. Tick Generate docs for code-only repos. Parsing costs $5 per 1M tokens. Only Owners and Admins can add, refresh or remove sources. Private libraries are queried with the same two tools, through a key that belongs to the teamspace.

Teamspace controls (Pro and Enterprise):


REST API and SDK (for codeAmani tooling)

curl -G "https://context7.com/api/v2/context" \
  -H "Authorization: Bearer $CONTEXT7_API_KEY" \
  --data-urlencode "libraryId=/vercel/next.js" \
  --data-urlencode "query=How to add a proxy that redirects unauthenticated users" \
  --data-urlencode "type=json"

GET /api/v3/search?query=…&library=Next.js&library=OpenAI&language=TypeScript picks up to four libraries for you in a single call. It returns 404 no_documentation_found when nothing matches, which you should treat as an empty result.

TypeScript (@upstash/context7-sdk@0.5.1). The full runnable file is examples/sdk-fetch-docs.mts.

import { Context7, Context7Error } from "@upstash/context7-sdk";

const client = new Context7(); // reads CONTEXT7_API_KEY; 30s timeout + retries on 408/425/429/5xx by default

const libs = await client.searchLibrary("app router caching", "Next.js");
const nextjs = libs.find((l) => l.id === "/vercel/next.js") ?? libs[0];
const text = await client.getContext("app router caching with fetch", nextjs.id, { type: "txt" });

Errors are thrown as Context7Error, with status, code, requestId, rateLimit and retryable. client.search(query, { libraries, version, language }) wraps /api/v3/search. For Vercel AI SDK agents, @upstash/context7-tools-ai-sdk provides resolveLibraryId and queryDocs tools plus a ready-made Context7Agent.


Documentation Policy (this repo's CLAUDE.md)

The tech-stack CLAUDE.md makes Context7 mandatory:

## Documentation Policy

When implementing features using any external library or service:

1. Use the **Context7 MCP** tool `resolve-library-id` to find the library
2. Use `query-docs` to fetch current docs for the specific API you need
3. Write code that matches the fetched documentation exactly
4. Never use remembered API patterns if they differ from fetched docs

As of 4.4.4 the policy is still accurate: both tool names are current. It doesn't mention language. Passing language: "TypeScript" matches the "TypeScript everywhere" convention and gives better snippets, so it's worth adding the next time the convention block is edited. That edit belongs in CLAUDE.md, followed by npm run sync:conventions. How to apply the policy:

Slash command: /docs <library>

.claude/commands/docs.md:

Fetch current documentation for $ARGUMENTS.

1. Call `resolve-library-id` with libraryName "$ARGUMENTS" and a query describing the feature.
   Pick the candidate whose owner is the official project (not a fork), then reputation and snippets.
2. Call `query-docs` with that libraryId, one single-concept query, and language "TypeScript".
3. Summarize the key API shapes and any breaking changes mentioned.
Stop after 3 calls per tool.

Hook: nudge after installs

.claude/settings.json:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "if echo \"$CLAUDE_TOOL_INPUT\" | grep -qE 'npm install|pnpm add|yarn add'; then echo 'Library installed: fetch its docs with Context7 before coding'; fi"
          }
        ]
      }
    ]
  }
}

Environment Variables

The only secret is the API key:

CONTEXT7_API_KEY=ctx7sk-...

Non-secret settings:

Setting Value Notes
Remote MCP URL (key) https://mcp.context7.com/mcp Authorization: Bearer <key>
Remote MCP URL (OAuth) https://mcp.context7.com/mcp/oauth HTTP only
REST base https://context7.com/api v2 search/context, v3 search
CTX7_TELEMETRY_DISABLED 1 Turns off anonymous ctx7 CLI telemetry
Local stdio flags --transport stdio|http, --port (default 3000), --api-key --api-key is rejected with --transport http

Keep CONTEXT7_API_KEY in .env.local or the Hazina vault, never in a committed .mcp.json literal or .vscode/settings.json (see ENV_MASTER.md).


Library IDs for the codeAmani stack (verified live 2026-10-20)

Library Context7 ID Note
Next.js /vercel/next.js
React /reactjs/react.dev /facebook/react now 301s to /react/react; react.dev ranks higher
Supabase /supabase/supabase, /supabase/supabase-js
Clerk /clerk/javascript, /clerk/clerk-docs
Drizzle ORM /drizzle-team/drizzle-orm-docs /drizzle-team/drizzle-orm has fewer snippets
Anthropic TS SDK /anthropics/anthropic-sdk-typescript The old /anthropic/anthropic-sdk-js is a 404
OpenAI /websites/developers_openai /openai/openai-node 301s here
Stripe Node /stripe/stripe-node Also /websites/stripe
Tailwind CSS /tailwindlabs/tailwindcss.com /tailwindlabs/tailwindcss 301s here
Zod /colinhacks/zod
Hono /honojs/hono
Prisma /prisma/orm /prisma/prisma 301s here
Context7 itself /upstash/context7

codeAmani notes


Common Use Cases

Use Case Approach
New library integration resolve-library-id → query-docs (+ language)
Version migration Pinned ID + query "v2 to v3 migration"
Breaking changes query-docs with "breaking changes", then confirm in the vendor changelog
Correct TS types query-docs with "typescript types for X", language: "TypeScript"
Multi-library question in a script GET /api/v3/search with up to 4 library hints

Troubleshooting

Issue Fix
429 / blocked Free plan cap reached (1,000 calls a month). Authenticate, or wait for the 20 daily bonus calls, or upgrade
401 Unauthorized The key must start with ctx7sk. Remote uses a Bearer header, stdio uses --api-key
Plugin ignores my key Expected: the plugin uses OAuth only. Use ctx7 setup or a manual entry for keys
301 library_redirected Use redirectUrl and update stored IDs
Library not found Try the official name and punctuation, or find the ID on context7.com
Wrong or outdated docs Check the ID's owner (forks rank high), then pin a version /org/project/vX.Y.Z
Local server timeouts on Windows cmd /c npx …, or switch to remote
ERR_MODULE_NOT_FOUND Use @upstash/context7-mcp@latest, or bunx/deno
ctx7 fails to start It needs Node 22.13 or newer (the MCP server needs 20.18.1 or newer)
Connectivity curl https://mcp.context7.com/ping; claude mcp list; claude mcp logs context7
get-library-docs not found It was renamed to query-docs in v4
Duplicate tools You installed both the plugin and a manual or ctx7 entry. Keep one

Best practice: pair Context7 with the CLAUDE.md Documentation Policy so that looking up docs before implementing is mandatory, not optional.

Official docs: