← Back to dashboard
context7toolingfresh

Context7 + Claude Code Integration Guide

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

Context7 + Claude Code 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:

Official Documentation


MCP Server Setup

@upstash/context7-mcp (Official)

Context7 is natively an MCP server. No API key is needed for the free tier.

Bash
# Add Context7 to Claude Code
claude mcp add context7 -- npx -y @upstash/context7-mcp

.mcp.json Configuration

JSON
{
  "mcpServers": {
    "context7": {
      "command": "npx",
      "args": ["-y", "@upstash/context7-mcp"]
    }
  }
}

With API key (for higher rate limits):

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

Available MCP Tools

ToolDescription
resolve-library-idMap a library name to a Context7 library ID
get-library-docsFetch current documentation for a resolved library

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:

Step 1: Resolve the Library ID

Text
Tool: resolve-library-id
Input: { "libraryName": "nextjs" }
Output: { "id": "/vercel/next.js", "name": "Next.js", "version": "15.3.1" }

Step 2: Fetch Documentation

Text
Tool: get-library-docs
Input: { "context7CompatibleLibraryID": "/vercel/next.js", "topic": "app router caching", "tokens": 8000 }
Output: [current documentation for Next.js App Router caching, pulled from official docs]

Claude Code then uses this documentation to write accurate code — not training-data guesses.

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 get-library-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.


Managing the Docs Token Budget

Every get-library-docs (a.k.a. query-docs) call accepts a tokens parameter that caps how much documentation Context7 returns into the conversation. Larger values pull in more API surface and examples; smaller values keep the response lean. The documented default is 5000 tokens, configurable upward toward your context window. (API guide, DeepWiki MCP reference)

Text
get-library-docs(id, topic="app router caching", tokens=5000)

In a single-lookup session, the default is plenty. The budget problem appears in multi-lookup sessions — researching five libraries at 10k tokens each can burn 50k tokens of context before you write a line of code. A lean heuristic:

  • Narrow the topic. A focused topic (e.g. "streaming responses", "v3 migration") returns the relevant slice instead of the whole library. This matters more than the raw tokens number.
  • Fetch once, then reuse. Context7 docs are stable within a session — pull a library's docs a single time and refer back to them rather than re-querying for each follow-up.
  • Scale tokens to the task. Use a small budget for a single API signature; raise it only when you genuinely need broad coverage (migrations, breaking-changes audits).
  • Sequence, don't batch. Resolve and fetch one library, act on it, then move to the next — so unused docs never pile up in context.

Gotcha — the minimum-tokens floor. The MCP server applies a DEFAULT_MINIMUM_TOKENS floor (documented at 10000): a request below it is silently raised to the floor, so setting tokens=2000 may still return ~10k. This was historically an env var / CLI flag but has been hardcoded as a constant in the MCP path in some versions (see issue #659) — the Context7 website honors lower values while the MCP server may not. The exact behavior varies by @upstash/context7-mcp version, so don't rely on tiny tokens values to shrink responses; control the payload with a tight topic instead, and check your installed version if a low budget isn't being respected.


Integration Patterns

Use Context7 in CLAUDE.md

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

CLAUDE.md:

Markdown
## 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 `get-library-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:

Markdown
Fetch the current documentation for library $ARGUMENTS.

1. Use the Context7 MCP tool `resolve-library-id` with the library name "$ARGUMENTS"
2. Use `get-library-docs` with the resolved ID, fetching up to 10000 tokens
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:

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

Claude (with Context7):
1. Calls resolve-library-id("uploadthing") → gets current ID
2. Calls get-library-docs(id, topic="nextjs app router") → gets v7 upload patterns
3. Writes code using the exact current API
4. No hallucinated deprecated patterns

Environment Variables

Bash
# Optional (for higher rate limits)
CONTEXT7_API_KEY=...              # From context7.com/dashboard

# No other environment variables required
# Context7 fetches docs from public sources automatically

Supported Libraries

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

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

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

Markdown
# 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 `get-library-docs` (topic: relevant 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 CaseApproach
New library integrationresolve-library-idget-library-docs
Migration between versionsget-library-docs with topic "migration" or "v2 to v3"
Checking breaking changesFetch docs with topic "breaking changes changelog"
Finding correct type signaturesget-library-docs with topic "typescript types"
Edge case API detailsFetch with specific topic, e.g., "error handling"

Troubleshooting

IssueFix
Library not foundTry alternate names: "next" → "nextjs", "react-query" → "tanstack query"
Docs seem outdatedSpecify version in the topic: get-library-docs(id, topic="v5 api")
Rate limit hitAdd CONTEXT7_API_KEY for higher limits
MCP not connectingRun claude mcp list to verify Context7 is registered
Tokens too lowIncrease tokens parameter up to 20000 for detailed docs

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.