← Back to dashboard
context7toolingfreshReader view (for NotebookLM)

Context7 Integration Guide

What is Context7?

The real model

resolve-library-id(libraryName, query) → query-docs(libraryId, query, language?): two calls per lookup, three calls max per tool.

Server 4.4.4 needs Node 20.18.1+; ctx7 0.8.1 needs Node 22.13+. Claude Code: the plugin (OAuth, ignores CONTEXT7_API_KEY), `npx ctx7 setup --claude`, or `claude mcp add --transport http` with a Bearer ctx7sk- key. Cursor uses url + headers in mcp.json, VS Code has the Upstash.context7-mcp extension, and claude.ai has a Context7 connector. OAuth lives at /mcp/oauth and works over HTTP only. Free is 1,000 calls a month and then blocked. Pro is $10/seat with 2,000 calls each, then $5 per 1k. IDs can 301 to new homes, so pick the official owner over high-benchmark forks. Pin versions as /org/project/v16.2.9.

Five Context7 primitives

Two MCP tools do the work; the rest is wiring, budget and your own docs.

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

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.

There are four ways to use the same index:

SurfaceWhat it isUse it for
MCP server (@upstash/context7-mcp, or hosted https://mcp.context7.com/mcp)Two agent tools: resolve-library-id and query-docsClaude Code, Cursor, VS Code, claude.ai, every MCP client
ctx7 CLIctx7 library / ctx7 docs in a terminal, plus ctx7 setup to wire up agentsOne-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/searchYour own scripts and pipelines
TypeScript SDK (@upstash/context7-sdk) and AI SDK tools (@upstash/context7-tools-ai-sdk)Typed wrappers over the REST APIAgents you build yourself

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

PackageVersionNode
@upstash/context7-mcp4.4.4 (2026-10-19)>=20.18.1
ctx7 (CLI)0.8.1 (2026-10-19)>=22.13.0
@upstash/context7-sdk0.5.1—
@upstash/context7-tools-ai-sdk1.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


MCP tools (v4.4)

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

ToolREST endpointRequired paramsOptional
resolve-library-idGET /api/v2/libs/searchlibraryName, query—
query-docsGET /api/v2/contextlibraryId, querylanguage
  • libraryName uses the official punctuation: Next.js, not nextjs.
  • query on resolve-library-id ranks the candidates. On query-docs it selects the documentation, so scope it to one concept.
  • language (added in 4.x) ranks code examples in that language first, for example TypeScript or Python. Leave it out when it doesn't apply.
  • Each candidate returned by resolve-library-id has an ID, name, description, code-snippet count, source reputation (High/Medium/Low/Unknown), benchmark score (0 to 100), and a list of versions.
  • The tool descriptions tell the agent not to call either tool more than 3 times per question.

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)
Endpointhttps://mcp.context7.com/mcp (API key), or https://mcp.context7.com/mcp/oauth (OAuth)npx -y @upstash/context7-mcp
Needs local NodeNoYes, Node 20.18.1 or newer
AuthAuthorization: Bearer <key> header, or OAuth 2.0--api-key <key> flag or CONTEXT7_API_KEY env (the flag wins)
OAuth availableYesNo. OAuth works only over remote HTTP
UpdatesAutomaticPin 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.

Claude Code

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

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

Text
/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).

Bash
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.

Bash
# 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):

JSON
{
  "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.

JSON
{
  "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):

JSON
{
  "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):

FreeProEnterprise
Price$0$10 / seat / monthPer seat, from $30/user/month for small teamspaces down to $2.50 at volume; self-serve up to 50 members
Included calls1,000 API calls / month2,000 / seat / month (per seat, not pooled)Custom
Over the limitBlocked, then 20 bonus calls per day until the month resetsNever blocked: $5 per 1,000 extra callsCustom
Private reposNoYes, parsing costs $5 per 1M tokens (refreshes bill changed content only)Yes
ExtrasPublic repos, basic access control, OAuth 2Team collaboration, rules, policiesSOC 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

Step 1: resolve the library ID

Text
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

Text
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

SourceExample
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

  • End a prompt with use context7, or say use library /supabase/supabase.
  • Mention a version ("Next.js 16 proxy") and Context7 matches it.
  • With the plugin or ctx7 setup, a skill or rule fires automatically on library questions.

Scoping the query

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

  • Good: "How to set up authentication with JWT in Express.js", "React useEffect cleanup function examples"
  • Too vague: "auth", "hooks"
  • Too broad: "routing and auth and caching in Next.js". Split it into one call per concept.

Session hygiene:

  • Fetch once, reuse. Docs don't change within a session.
  • Three-call ceiling per tool per question. After that, work from the best result.
  • Sequence, don't batch. Resolve and use one library before moving to the next.
  • Never put secrets, customer data or proprietary code in query. It is sent to Context7 (see Privacy).

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:

JSON
{
  "$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):

  • Rules (dashboard → rules tab) are prepended to every retrieved doc, either globally or per library. Example: "Use the App Router, not the Pages Router".
  • Policies turn source types on or off, and filter public libraries by verification, trust score, freshness or stars, or by a hand-picked allow-list. They apply to every MCP or API request made with a teamspace key. They are also available through GET/PATCH /api/v2/policies.

REST API and SDK (for codeAmani tooling)

Bash
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.

TypeScript
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:

Markdown
## 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:

  • Every external library or service, including well-known ones.
  • If Context7 doesn't have it, or its result disagrees with the vendor's own docs, the vendor's .md docs win. Record the disagreement in the tech folder's NOTES.md.
  • Context7 complements changelogs and security advisories; it doesn't replace them.

Slash command: /docs <library>

.claude/commands/docs.md:

Markdown
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:

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:

Bash
CONTEXT7_API_KEY=ctx7sk-...

Non-secret settings:

SettingValueNotes
Remote MCP URL (key)https://mcp.context7.com/mcpAuthorization: Bearer <key>
Remote MCP URL (OAuth)https://mcp.context7.com/mcp/oauthHTTP only
REST basehttps://context7.com/apiv2 search/context, v3 search
CTX7_TELEMETRY_DISABLED1Turns 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)

LibraryContext7 IDNote
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-typescriptThe old /anthropic/anthropic-sdk-js is a 404
OpenAI/websites/developers_openai/openai/openai-node 301s here
Stripe Node/stripe/stripe-nodeAlso /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

  • Context7 is the Documentation Policy engine. Every guide in this repo, and every integration in codeAmani projects, is written against Context7-fetched docs, with the vendor's own .md pages as the tie-breaker.
  • Authenticate everywhere. The free plan blocks at 1,000 calls a month, and each lookup is 2 calls. A guide refresh that touches 10 libraries can use 50 or more. Use OAuth (plugin or /mcp/oauth) on dev machines and a ctx7sk- key from the Hazina vault on headless or CI hosts. Move to Pro ($10/seat) once a second person relies on it or when we add private sources.
  • Server-side secrets only. The key never goes in a client bundle, a committed .mcp.json literal, or a workspace .vscode/settings.json. Use ${CONTEXT7_API_KEY} expansion or user-level settings.
  • Query hygiene is a privacy control. Only the agent-formulated query and the library name reach Context7. Queries are stored anonymously for benchmarking and are reranked by OpenAI, Gemini or Anthropic models. Never put customer data, M-Pesa phone numbers, keys, or proprietary code in a query.
  • AI routing. Context7 is the "library documentation lookup" row of the AI Routing Policy. It feeds Claude (primary) and doesn't replace the vendor docs for pricing, limits or changelogs.
  • Payments context. When looking up payments docs, query Stripe first (default rail). Daraja/M-Pesa coverage in Context7 is thin, so for Kenya-targeted projects use the daraja api/ guide and Safaricom's portal docs as the source of truth.
  • African-market note. Remote MCP adds one HTTPS round-trip per lookup, which is a dev-time cost only. Nothing here ships to end users on 2G/3G.
  • Candidate idea: publish this tech-stack repo as a private Context7 source (Pro) so agents can query-docs our own conventions. This has not been done yet.
  • Git Bash gotcha: when calling the REST API with curl from Git Bash, set MSYS_NO_PATHCONV=1. Otherwise libraryId=/vercel/next.js is rewritten into a Windows path and returns library_not_found.

Common Use Cases

Use CaseApproach
New library integrationresolve-library-id → query-docs (+ language)
Version migrationPinned ID + query "v2 to v3 migration"
Breaking changesquery-docs with "breaking changes", then confirm in the vendor changelog
Correct TS typesquery-docs with "typescript types for X", language: "TypeScript"
Multi-library question in a scriptGET /api/v3/search with up to 4 library hints

Troubleshooting

IssueFix
429 / blockedFree plan cap reached (1,000 calls a month). Authenticate, or wait for the 20 daily bonus calls, or upgrade
401 UnauthorizedThe key must start with ctx7sk. Remote uses a Bearer header, stdio uses --api-key
Plugin ignores my keyExpected: the plugin uses OAuth only. Use ctx7 setup or a manual entry for keys
301 library_redirectedUse redirectUrl and update stored IDs
Library not foundTry the official name and punctuation, or find the ID on context7.com
Wrong or outdated docsCheck the ID's owner (forks rank high), then pin a version /org/project/vX.Y.Z
Local server timeouts on Windowscmd /c npx …, or switch to remote
ERR_MODULE_NOT_FOUNDUse @upstash/context7-mcp@latest, or bunx/deno
ctx7 fails to startIt needs Node 22.13 or newer (the MCP server needs 20.18.1 or newer)
Connectivitycurl https://mcp.context7.com/ping; claude mcp list; claude mcp logs context7
get-library-docs not foundIt was renamed to query-docs in v4
Duplicate toolsYou 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.