Context7 Integration Guide

Technology: context7 · Category: tooling · Last reviewed: 2026-08-23

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

Insight:

Context7 feeds live, version-accurate library docs into Claude Code, eliminating hallucinated APIs — it's the engine behind this repo's "no trained-data guessing" rule. Always resolve-library-id then query-docs before writing integration code against an unfamiliar or fast-moving SDK. The v4 tools take a plain-English query (the old topic/tokens knobs are gone) — a tight, single-concept query is now the only lever you have on what comes back.

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

Context7 Integration Guide

Focus: Feeding live, version-accurate library documentation into Claude Code sessions using the Context7 MCP server — eliminating hallucinated API calls.

Overview

Context7 is an MCP server built specifically for AI coding assistants. It solves one of the biggest LLM pain points: outdated training data causing hallucinated or deprecated API usage. When Claude Code is connected to Context7, it can resolve any library by name and pull current, version-specific documentation directly into its context — ensuring generated code uses the right API signatures every time.

Core value proposition: Instead of Claude guessing at a library's API, Context7 fetches the actual, current docs and injects them into the conversation.

Here's the core idea at a glance — Context7 turns guesswork into grounded code:

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"]

Renamed in v4. The docs tool is now query-docs (formerly get-library-docs), and both tools take a plain-English query instead of the old topic/tokens parameters. If you have older CLAUDE.md rules or slash commands referencing get-library-docs, update them — see the tool table below.

Official Documentation

Resource URL
Context7 Website https://context7.com
npm Package (MCP server) https://www.npmjs.com/package/@upstash/context7-mcp
npm Package (ctx7 CLI) https://www.npmjs.com/package/ctx7
GitHub https://github.com/upstash/context7
Manual install / all clients https://context7.com/docs/resources/all-clients
API reference https://context7.com/docs/api-guide
CLI reference https://context7.com/docs/clients/cli

MCP Server Setup

Context7 v4 ships two ways to consume it, both installable with one command:

API key recommended (not required). The free tier still works with no key, but the docs now recommend a free key from context7.com/dashboard for higher rate limits. Keep it out of the repo — see Environment Variables.

The ctx7 CLI (Node.js 18+) authenticates via OAuth, generates an API key, and wires up either mode. Target Claude Code with --claude:

npx ctx7 setup --claude

To undo it later: npx ctx7 remove (and, if you installed the CLI globally with npm install -g ctx7, also npm uninstall -g ctx7).

Remote (hosted) MCP — manual .mcp.json

The hosted server lives at https://mcp.context7.com/mcp; pass the key as a Bearer header.

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

Local stdio MCP — manual .mcp.json

The @upstash/context7-mcp package (v4.x) still runs as a local stdio process — handy when you'd rather not depend on the hosted endpoint:

# Add Context7 to Claude Code as a local stdio server
claude mcp add context7 -- npx -y @upstash/context7-mcp
{
  "mcpServers": {
    "context7": {
      "command": "npx",
      "args": ["-y", "@upstash/context7-mcp"]
    }
  }
}

With an API key for higher rate limits (pass it as a CLI flag on the server):

{
  "mcpServers": {
    "context7": {
      "command": "npx",
      "args": ["-y", "@upstash/context7-mcp", "--api-key", "${CONTEXT7_API_KEY}"]
    }
  }
}

Full per-client setup for 30+ clients: https://context7.com/docs/resources/all-clients

Available MCP Tools

Tool Purpose Required params
resolve-library-id Map a library name to a Context7 library ID libraryName, query
query-docs Fetch current docs for a resolved library ID libraryId, query

query-docs was get-library-docs before v4. The old context7CompatibleLibraryID, topic, and tokens parameters are gone — see How Context7 Works for the current parameter shapes. Neither tool should be called more than 3 times per question.


How Context7 Works in Practice

The workflow is always two steps:

You've got this — the sequence below shows exactly how the two tools cooperate per request:

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: "Context7 library ID"
    C->>M: "query-docs with libraryId and query"
    M-->>C: "Current docs"
    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 (one of several candidates):
  {
    "id": "/vercel/next.js",
    "name": "Next.js",
    "description": "Next.js enables you to create full-stack web applications...",
    "codeSnippets": 5762,
    "sourceReputation": "High",
    "benchmarkScore": 87.87,
    "versions": ["v16.2.9", "v15.1.8", "v14.3.0-canary.87", "..."]
  }

Pass the official library name with punctuation ("Next.js", not "nextjs") and a query describing what you're after — the query ranks the candidates by relevance. Pick the candidate with the highest Source Reputation and Benchmark Score (100 is best) whose owner matches the authoritative repo. To pin a version, append it to the ID: /vercel/next.js/v15.1.8.

Step 2: Fetch Documentation

Tool: query-docs
Input: { "libraryId": "/vercel/next.js", "query": "app router caching with fetch" }
Output: [current documentation for Next.js App Router caching, pulled from official docs]

There is no tokens or topic parameter in v4 — a single, specific query is the only lever on what comes back. Claude Code then uses this documentation to write accurate code — not training-data guesses. You can also skip Step 1 by giving query-docs a library ID directly (in the /org/project or /org/project/version form) when you already know it.

Natural Language Usage

When Context7 is connected to Claude Code, you can reference docs naturally:

"Using the latest React 19 API, implement a transition-based search input."

Claude will automatically call resolve-library-id for React and query-docs for React 19 transitions before writing code.

"Show me how to use Prisma's new omit field in a findMany query."

Claude will fetch current Prisma docs for the omit feature.

You can also nudge Context7 explicitly from a prompt: end a request with use context7, or name a known ID with use library /supabase/supabase, or just mention a version ("Next.js 14 middleware") and Context7 matches it.


Scoping the query (the only lever in v4)

Earlier versions exposed a tokens budget and a topic string on the docs tool. v4 removed both. The single query string is now your only control over what comes back — so how you phrase it is the whole game.

A tight, single-concept query returns the relevant slice; a vague or multi-topic one wastes the call. The tool's own guidance:

Heuristics for a lean session:

flowchart TD
    A["Need library docs"] --> B["Phrase one specific query"]
    B --> C{"Single concept<br/>or several?"}
    C -->|"single"| D["One query-docs call"]
    C -->|"several"| E["One call per concept<br/>(max 3 per question)"]
    D --> F["Fetch once"]
    E --> F
    F --> G["Reuse in session<br/>do not re-query"]
    G --> H["Next library only when done"]

Gone in v4: the tokens parameter and the DEFAULT_MINIMUM_TOKENS floor that older guides warned about. If you find a CLAUDE.md rule or slash command passing tokens=… or a topic=…, it's referencing the pre-v4 tool — drop those args and put the specificity into the query string instead.


Integration Patterns

Use Context7 in CLAUDE.md

Tell Claude Code to always use Context7 for new library integrations:

CLAUDE.md:

## Documentation Policy

When implementing features using any external library:
1. Always 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

This prevents hallucinated or outdated API usage.

Slash Command: Fetch Library Docs

.claude/commands/docs.md:

Fetch the current documentation for library $ARGUMENTS.

1. Use the Context7 MCP tool `resolve-library-id` with libraryName "$ARGUMENTS" and a
   `query` describing the feature you need
2. Use `query-docs` with the resolved `libraryId` and a specific, single-concept `query`
3. Display the documentation summary and key API patterns
4. Identify any breaking changes from previous versions if mentioned

This gives you current, accurate docs to work from.

Usage: /project:docs drizzle-orm

Pre-Implementation Research Pattern

For any new library integration inside Claude Code:

You: "Implement file uploads using uploadthing in our Next.js app."

Claude (with Context7):
1. Calls resolve-library-id(libraryName="UploadThing", query="nextjs app router uploads") → gets current ID
2. Calls query-docs(libraryId, query="nextjs app router file upload route") → gets current upload patterns
3. Writes code using the exact current API
4. No hallucinated deprecated patterns

Environment Variables

# Recommended (for higher rate limits) — free key from context7.com/dashboard
CONTEXT7_API_KEY=...

# The stdio server reads CONTEXT7_API_KEY automatically, or takes --api-key <key>
# (the flag wins if both are set). The hosted server (mcp.context7.com/mcp) takes
# it as an "Authorization: Bearer <key>" header. `npx ctx7 setup` provisions one
# for you via OAuth. No key is strictly required — the free tier just rate-limits
# harder.

Keep CONTEXT7_API_KEY in .env.local / your environment manager — never commit it (see ENV_MASTER.md).


Supported Libraries

Context7 covers thousands of libraries. Key examples relevant to this tech stack:

Library Context7 ID
Next.js /vercel/next.js
React /facebook/react
Supabase JS /supabase/supabase-js
Prisma /prisma/prisma
Drizzle ORM /drizzle-team/drizzle-orm
Clerk /clerk/javascript
Anthropic SDK /anthropic/anthropic-sdk-js
OpenAI SDK /openai/openai-node
Tailwind CSS /tailwindlabs/tailwindcss
Zod /colinhacks/zod
Hono /honojs/hono

Find more: run resolve-library-id with any library name — Context7 will find it.


Automation Workflows

Claude Code Hook: Auto-check Docs on Install

.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 — use Context7 MCP to fetch current docs before coding'; fi"
          }
        ]
      }
    ]
  }
}

Combined CLAUDE.md + Context7 Workflow

# CLAUDE.md — Context7 Integration

## New Dependency Rule

When you add a new npm package:
1. Use `resolve-library-id` to find it in Context7
2. Fetch docs with `query-docs` (query: the specific feature area)
3. Implement using the documented API
4. Note the version in a comment if the API may change

## Libraries Pre-approved (already docs-fetched)
- Next.js 15 (App Router)
- Supabase JS v2
- Clerk v6
- Drizzle ORM v0.40

Common Use Cases

Use Case Approach
New library integration resolve-library-id → query-docs
Migration between versions query-docs with query "v2 to v3 migration"
Checking breaking changes query-docs with query "breaking changes changelog"
Finding correct type signatures query-docs with query "typescript types for X"
Edge case API details query-docs with a specific query, e.g. "error handling"

Troubleshooting

Issue Fix
Library not found Try alternate names: "next" → "Next.js", "react-query" → "tanstack query"
Docs seem outdated Pin the version in the ID: query-docs("/vercel/next.js/v15.1.8", query="…")
Rate limit hit Add CONTEXT7_API_KEY (or run npx ctx7 setup) for higher limits
MCP not connecting Run claude mcp list to verify Context7 is registered
Docs too broad / off-target Tighten the query to a single concept (v4 has no tokens/topic knob)
get-library-docs not found It was renamed to query-docs in v4 — update the call

Best practice: Always combine Context7 with a CLAUDE.md rule that mandates doc lookup before implementing any new library feature. This makes hallucinated APIs structurally impossible in your workflow.

Official docs: