context7 Documentation

Context7 Platform -- Up-to-date code documentation for LLMs and AI code editors

60,663 stars TypeScript TypeScript 1 file ยท ~52,032 tokens #llm#mcp#mcp-server#vibe-coding
RAW Doc

Docker & Self-Hosted Deployment Verified OCI

Deploy context7 on any server, homelab, or cloud container platform.

1-Click Terminal Command
bash (docker run)
docker run -d --name context7 -p 8080:8080 --restart always upstash/context7:latest

1. Project Overview & Quickstart (upstash/context7)

File: README.md

Context7 Platform - Up-to-date Code Docs For Any Prompt

-purple>)

โŒ Without Context7

LLMs rely on outdated or generic information about the libraries you use. You get:

  • โŒ Code examples are outdated and based on year-old training data
  • โŒ Hallucinated APIs that don't even exist
  • โŒ Generic answers for old package versions

โœ… With Context7

Context7 pulls up-to-date, version-specific documentation and code examples straight from the source โ€” and places them directly into your prompt.

txt
Create a Next.js middleware that checks for a valid JWT in cookies
and redirects unauthenticated users to `/login`. use context7
txt
Configure a Cloudflare Worker script to cache
JSON API responses for five minutes. use context7
txt
Show me the Supabase auth API for email/password sign-up.

Context7 fetches up-to-date code examples and documentation right into your LLM's context. No tab-switching, no hallucinated APIs that don't exist, no outdated code generation.

Works in two modes:

  • CLI + Skills โ€” installs a skill that guides your agent to fetch docs using ctx7 CLI commands (no MCP required)
  • MCP โ€” registers a Context7 MCP server so your agent can call documentation tools natively

Installation

[!NOTE]
API Key Recommended: Get a free API key at context7.com/dashboard for higher rate limits.

Set up Context7 for your coding agents with a single command. The ctx7 CLI requires Node.js 18 or newer.

bash
npx ctx7 setup

Authenticates via OAuth, generates an API key, and installs the appropriate skill. You can choose between CLI + Skills or MCP mode. Use --cursor, --claude, or --opencode to target a specific agent.

To remove the generated setup later, run npx ctx7 remove. If you globally installed the CLI with npm install ctx7, remove that package separately with npm uninstall -g ctx7.

To configure manually, use the Context7 server URL https://mcp.context7.com/mcp with your MCP client and pass your API key via the Authorization: Bearer YOUR_API_KEY header. See the link below for client-specific setup instructions.

Manual Installation / Other Clients โ†’

Important Tips

Use Library Id

If you already know exactly which library you want to use, add its Context7 ID to your prompt. That way, Context7 can skip the library-matching step and directly retrieve docs.

txt
Implement basic authentication with Supabase. use library /supabase/supabase for API and docs.

The slash syntax tells Context7 exactly which library to load docs for.

Specify a Version

To get documentation for a specific library version, just mention the version in your prompt:

txt
How do I set up Next.js 14 middleware? use context7

Context7 will automatically match the appropriate version.

Add a Rule

If you installed via ctx7 setup, a skill is configured automatically that triggers Context7 for library-related questions. To set up a rule manually instead, add one to your coding agent:

  • Cursor: Cursor Settings > Rules
  • Claude Code: CLAUDE.md
  • Or the equivalent in your coding agent

Example rule:

txt
Always use Context7 when I need library/API documentation, code generation, setup or configuration steps without me having to explicitly ask.

Available Tools

CLI Commands

  • ctx7 library <name> <query>: Searches the Context7 index by library name and returns matching libraries with their IDs.
  • ctx7 docs <libraryId> <query>: Retrieves documentation for a library using a Context7-compatible library ID (e.g., /mongodb/docs, /vercel/next.js).

MCP Tools

  • resolve-library-id: Resolves a general library name into a Context7-compatible library ID.
    • query (required): The user's question or task (used to rank results by relevance)
    • libraryName (required): The name of the library to search for
  • query-docs: Retrieves documentation for a library using a Context7-compatible library ID.
    • libraryId (required): Exact Context7-compatible library ID (e.g., /mongodb/docs, /vercel/next.js)
    • query (required): The question or task to get relevant documentation for

More Documentation

Packages

Disclaimer

1- Context7 projects are community-contributed and while we strive to maintain high quality, we cannot guarantee the accuracy, completeness, or security of all library documentation. Projects listed in Context7 are developed and maintained by their respective owners, not by Context7. If you encounter any suspicious, inappropriate, or potentially harmful content, please use the "Report" button on the project page to notify us immediately. We take all reports seriously and will review flagged content promptly to maintain the integrity and safety of our platform. By using Context7, you acknowledge that you do so at your own discretion and risk.

2- This repository hosts the MCP serverโ€™s source code. The supporting components โ€” API backend, parsing engine, and crawling engine โ€” are private and not part of this repository.

๐Ÿค Connect with Us

Stay updated and join our community:

  • ๐Ÿ“ข Follow us on X for the latest news and updates
  • ๐ŸŒ Visit our Website
  • ๐Ÿ’ฌ Join our Discord Community

๐Ÿ“บ Context7 In Media

๐Ÿ“„ License

MIT


File: .changeset/README.md

Changesets

Hello and welcome! This folder has been automatically generated by @changesets/cli, a build tool that works
with multi-package repos, or single-package repos to help you version and publish your code. You can
find the full documentation for it in our repository

We have a quick list of common questions to get you started engaging with this project in
our documentation


File: docs/agentic-tools/ai-sdk/agents/context7-agent.mdx


title: "Context7Agent" sidebarTitle: "Context7Agent"

The Context7Agent class is a pre-configured AI agent that handles the complete documentation lookup workflow automatically. It combines both resolveLibraryId and queryDocs tools with an optimized system prompt.

Usage

typescript
import { Context7Agent } from "@upstash/context7-tools-ai-sdk";
import { anthropic } from "@ai-sdk/anthropic";

const agent = new Context7Agent({
  model: anthropic("claude-sonnet-4-20250514"),
});

const { text } = await agent.generate({
  prompt: "How do I use React Server Components?",
});

console.log(text);

Configuration

typescript
new Context7Agent(config?: Context7AgentConfig)

Parameters

Configuration options for the agent.

text
Language model to use. Must be a LanguageModel instance from an AI SDK provider.

  Examples:
  - `anthropic('claude-sonnet-4-20250514')`
  - `openai('gpt-5.2')`
  - `google('gemini-1.5-pro')`


  Context7 API key. If not provided, uses the `CONTEXT7_API_KEY` environment variable.


  Custom system prompt. Overrides the default `AGENT_PROMPT`.


  Condition for when the agent should stop. Defaults to stopping after 5 steps.

Returns

Context7Agent extends the AI SDK Agent class and provides generate() and stream() methods.

Agent Workflow

The agent follows a structured multi-step workflow:

mermaid
flowchart TD
    A[User Query] --> B[Extract Library Name]
    B --> C[Call resolveLibraryId]
    C --> D{Results Found?}
    D -->|Yes| E[Select Best Match]
    D -->|No| F[Report No Results]
    E --> G[Call queryDocs]
    G --> H{Sufficient Context?}
    H -->|Yes| I[Generate Response]
    H -->|No| J[Fetch More Docs]
    J --> H
    I --> K[Return Answer with Examples]

Step-by-Step

  1. Extract library name - Identifies the library/framework from the user's query
  2. Resolve library - Calls resolveLibraryId to find the Context7 library ID
  3. Select best match - Analyzes results based on reputation, coverage, and relevance
  4. Fetch documentation - Calls queryDocs with the selected library ID and user's query
  5. Query if needed - Makes additional queries if initial context is insufficient
  6. Generate response - Provides an answer with code examples from the documentation

Examples

Basic Usage

typescript
import { Context7Agent } from "@upstash/context7-tools-ai-sdk";
import { anthropic } from "@ai-sdk/anthropic";

const agent = new Context7Agent({
  model: anthropic("claude-sonnet-4-20250514"),
});

const { text } = await agent.generate({
  prompt: "How do I set up authentication in Next.js?",
});

console.log(text);

With OpenAI

typescript
import { Context7Agent } from "@upstash/context7-tools-ai-sdk";
import { openai } from "@ai-sdk/openai";

const agent = new Context7Agent({
  model: openai("gpt-5.2"),
});

const { text } = await agent.generate({
  prompt: "Explain Tanstack Query's useQuery hook",
});

Streaming Responses

typescript
import { Context7Agent } from "@upstash/context7-tools-ai-sdk";
import { anthropic } from "@ai-sdk/anthropic";

const agent = new Context7Agent({
  model: anthropic("claude-sonnet-4-20250514"),
});

const { textStream } = await agent.stream({
  prompt: "How do I create a Supabase Edge Function?",
});

for await (const chunk of textStream) {
  process.stdout.write(chunk);
}

Custom Configuration

typescript
import { Context7Agent } from "@upstash/context7-tools-ai-sdk";
import { anthropic } from "@ai-sdk/anthropic";
import { stepCountIs } from "ai";

const agent = new Context7Agent({
  model: anthropic("claude-sonnet-4-20250514"),
  apiKey: process.env.CONTEXT7_API_KEY,
  stopWhen: stepCountIs(8), // Allow more steps for complex queries
});

Custom System Prompt

typescript
import { Context7Agent, AGENT_PROMPT } from "@upstash/context7-tools-ai-sdk";
import { openai } from "@ai-sdk/openai";

const agent = new Context7Agent({
  model: openai("gpt-5.2"),
  system: `${AGENT_PROMPT}

Additional instructions:
- Always include TypeScript examples
- Mention version compatibility when relevant
- Suggest related documentation topics`,
});

Comparison: Agent vs Tools

Feature Context7Agent Individual Tools
Setup Single configuration Configure each tool
Workflow Automatic multi-step Manual orchestration
System prompt Optimized default You provide
Customization Limited Full control
Best for Quick integration Custom workflows

When to Use the Agent

  • Rapid prototyping
  • Standard documentation lookup use cases
  • When you want sensible defaults

When to Use Individual Tools

  • Custom agentic workflows
  • Integration with other tools
  • Fine-grained control over the process
  • Custom system prompts with specific behavior

File: docs/agentic-tools/ai-sdk/tools/query-docs.mdx


title: "queryDocs" sidebarTitle: "queryDocs"

The queryDocs tool fetches documentation for a library using its Context7-compatible library ID and a query. This tool is typically called after resolveLibraryId has identified the correct library.

Usage

typescript
import { resolveLibraryId, queryDocs } from "@upstash/context7-tools-ai-sdk";
import { generateText, stepCountIs } from "ai";
import { openai } from "@ai-sdk/openai";

const { text } = await generateText({
  model: openai("gpt-5.2"),
  prompt: "How do I use React Server Components?",
  tools: {
    resolveLibraryId: resolveLibraryId(),
    queryDocs: queryDocs(),
  },
  stopWhen: stepCountIs(5),
});

Configuration

typescript
queryDocs(config?: Context7ToolsConfig)

Parameters

Configuration options for the tool.

text
Context7 API key. If not provided, uses the `CONTEXT7_API_KEY` environment variable.

Returns

Returns an AI SDK tool that can be used with generateText, streamText, or agents.

Tool Behavior

When the AI model calls this tool, it:

  1. Takes a library ID and query from the model
  2. Fetches documentation from Context7's API
  3. Returns the documentation content

Input Schema

The tool accepts the following inputs from the AI model:

Context7-compatible library ID (e.g., /reactjs/react.dev, /vercel/next.js)

The question or task you need help with, scoped to a single concept. Be specific and include relevant details, but keep each query to one topic โ€” if the user's question spans multiple distinct concepts, make a separate call per concept instead of combining them, unless the question is about how the concepts interact. Good: "How to set up authentication with JWT in Express.js" or "React useEffect cleanup function examples". Bad (too vague): "auth" or "hooks". Bad (too broad): "routing and auth and caching in Next.js".

Output Format

On success, the tool returns the documentation as plain text, formatted for easy consumption by the AI model:

text
# Server Components

Server Components let you write UI that can be rendered and optionally cached on the server.

## Example

\`\`\`tsx
async function ServerComponent() {
  const data = await fetchData();
  return {data};
}
\`\`\`

---

# Using Server Components with Client Components

You can import Server Components into Client Components...

On Failure

text
No documentation found for library "/invalid/library". This might have happened because you used an invalid Context7-compatible library ID. Use 'resolveLibraryId' to get a valid ID.

Examples

Basic Usage with Both Tools

typescript
import { resolveLibraryId, queryDocs } from "@upstash/context7-tools-ai-sdk";
import { generateText, stepCountIs } from "ai";
import { openai } from "@ai-sdk/openai";

const { text } = await generateText({
  model: openai("gpt-5.2"),
  prompt: "Show me how to set up routing in Next.js App Router",
  tools: {
    resolveLibraryId: resolveLibraryId(),
    queryDocs: queryDocs(),
  },
  stopWhen: stepCountIs(5),
});

// The model will:
// 1. Call resolveLibraryId to get the library ID
// 2. Call queryDocs({ libraryId: "/vercel/next.js", query: "routing in App Router" })
// 3. Generate a response using the fetched documentation

With Custom Configuration

typescript
import { queryDocs } from "@upstash/context7-tools-ai-sdk";

const tool = queryDocs({
  apiKey: process.env.CONTEXT7_API_KEY,
});

Direct Library ID (Skip resolveLibraryId)

If the user provides a library ID directly, the model can skip the resolution step:

typescript
import { queryDocs } from "@upstash/context7-tools-ai-sdk";
import { generateText, stepCountIs } from "ai";
import { openai } from "@ai-sdk/openai";

const { text } = await generateText({
  model: openai("gpt-5.2"),
  prompt: "Using /vercel/next.js, explain middleware",
  tools: {
    queryDocs: queryDocs(),
  },
  stopWhen: stepCountIs(3),
});

// The model recognizes the /org/project format and calls queryDocs directly

Multi-Step Documentation Lookup

For comprehensive documentation, the model can make multiple queries:

typescript
import { resolveLibraryId, queryDocs } from "@upstash/context7-tools-ai-sdk";
import { generateText, stepCountIs } from "ai";
import { anthropic } from "@ai-sdk/anthropic";

const { text } = await generateText({
  model: anthropic("claude-sonnet-4-20250514"),
  prompt: "Give me a comprehensive guide to Supabase authentication",
  tools: {
    resolveLibraryId: resolveLibraryId(),
    queryDocs: queryDocs(),
  },
  stopWhen: stepCountIs(8), // Allow more steps for multiple queries
});

// The model may call queryDocs multiple times with different queries
// to gather comprehensive documentation

Version-Specific Documentation

Library IDs can include version specifiers:

typescript
// Latest version
"/vercel/next.js";

// Specific version
"/vercel/next.js/v14.3.0-canary.87";

The model can request documentation for specific versions when the user asks about a particular version.


File: docs/agentic-tools/ai-sdk/tools/resolve-library-id.mdx


title: "resolveLibraryId" sidebarTitle: "resolveLibraryId"

The resolveLibraryId tool searches Context7's library database and returns matching results with their Context7-compatible library IDs. This is typically the first step in a documentation lookup workflow.

Usage

typescript
import { resolveLibraryId } from "@upstash/context7-tools-ai-sdk";
import { generateText, stepCountIs } from "ai";
import { openai } from "@ai-sdk/openai";

const { text } = await generateText({
  model: openai("gpt-5.2"),
  prompt: "Find documentation for React hooks",
  tools: {
    resolveLibraryId: resolveLibraryId(),
  },
  stopWhen: stepCountIs(3),
});

Configuration

typescript
resolveLibraryId(config?: Context7ToolsConfig)

Parameters

Configuration options for the tool.

text
Context7 API key. If not provided, uses the `CONTEXT7_API_KEY` environment variable.

Returns

Returns an AI SDK tool that can be used with generateText, streamText, or agents.

Tool Behavior

When the AI model calls this tool, it:

  1. Takes a query and libraryName parameter from the model
  2. Searches Context7's database for matching libraries
  3. Returns formatted results including:
    • Library ID (e.g., /reactjs/react.dev)
    • Title and description
    • Number of code snippets available
    • Source reputation score
    • Available versions

Input Schema

The tool accepts the following input from the AI model:

The user's original question or task. This is used to rank library results by relevance to what the user is trying to accomplish.

Library name to search for (e.g., "react", "next.js", "vue")

Output Format

On success, the tool returns the search results as plain text, formatted for easy consumption by the AI model:

text
- Title: React Documentation
- Context7-compatible library ID: /reactjs/react.dev
- Description: The library for web and native user interfaces
- Code Snippets: 1250
- Source Reputation: High
- Benchmark Score: 98
- Versions: 19.0.0, 18.3.1, 18.2.0
----------
- Title: React Native
- Context7-compatible library ID: /facebook/react-native
- Description: A framework for building native applications using React
- Code Snippets: 890
- Source Reputation: High
- Benchmark Score: 95
- Versions: 0.76.0, 0.75.4

On failure:

text
No libraries found matching "unknown-lib". Try a different search term or check the library name.

Examples

Basic Usage

typescript
import { resolveLibraryId, queryDocs } from "@upstash/context7-tools-ai-sdk";
import { generateText, stepCountIs } from "ai";
import { openai } from "@ai-sdk/openai";

const { text, toolCalls } = await generateText({
  model: openai("gpt-5.2"),
  prompt: "What libraries are available for React?",
  tools: {
    resolveLibraryId: resolveLibraryId(),
    queryDocs: queryDocs(),
  },
  stopWhen: stepCountIs(5),
});

// The model will call resolveLibraryId and receive a list of matching libraries
console.log(text);

With Custom API Key

typescript
import { resolveLibraryId } from "@upstash/context7-tools-ai-sdk";

const tool = resolveLibraryId({
  apiKey: process.env.CONTEXT7_API_KEY,
});

Inspecting Tool Calls

typescript
import { resolveLibraryId } from "@upstash/context7-tools-ai-sdk";
import { generateText, stepCountIs } from "ai";
import { openai } from "@ai-sdk/openai";

const { toolCalls, toolResults } = await generateText({
  model: openai("gpt-5.2"),
  prompt: "Find the official Next.js documentation",
  tools: {
    resolveLibraryId: resolveLibraryId(),
  },
  stopWhen: stepCountIs(3),
});

// See what the model searched for
for (const call of toolCalls) {
  console.log("Searched for:", call.input.libraryName);
}

// See the results
for (const result of toolResults) {
  console.log("Found:", result.output);
}

Selection Guidance

The tool's description instructs the AI model to select libraries based on:

  1. Name similarity - Exact matches are prioritized
  2. Description relevance - How well the description matches the query intent
  3. Documentation coverage - Libraries with more code snippets are preferred
  4. Source reputation - High/Medium reputation sources are more authoritative
  5. Benchmark score - Quality indicator (100 is the highest)
  • queryDocs - Fetch documentation using the resolved library ID
  • Context7Agent - Pre-built agent that handles the full workflow

File: docs/agentic-tools/ai-sdk/getting-started.mdx


title: "Getting Started" sidebarTitle: "Getting Started"

@upstash/context7-tools-ai-sdk provides Vercel AI SDK compatible tools and agents that give your AI applications access to up-to-date library documentation.

When building AI-powered applications with the Vercel AI SDK, your models often need accurate information about libraries and frameworks. Instead of relying on potentially outdated training data, Context7 tools let your AI fetch current documentation on-demand, ensuring responses include correct API usage, current best practices, and working code examples.

The package gives you two ways to integrate:

  1. Individual tools (resolveLibraryId and queryDocs) that you add to your existing generateText or streamText calls
  2. A pre-built agent (Context7Agent) that handles the entire documentation lookup workflow automatically

Both approaches work with any AI provider supported by the Vercel AI SDK, including OpenAI, Anthropic, Google, and others.

Installation

```bash npm npm install @upstash/context7-tools-ai-sdk ```
bash pnpm
pnpm add @upstash/context7-tools-ai-sdk
bash yarn
yarn add @upstash/context7-tools-ai-sdk
bash bun
bun add @upstash/context7-tools-ai-sdk

Prerequisites

You'll need:

  1. A Context7 API key from the Context7 Dashboard
  2. An AI provider SDK (e.g., @ai-sdk/openai, @ai-sdk/anthropic)

Configuration

Set your Context7 API key as an environment variable:

bash
CONTEXT7_API_KEY=ctx7sk-...

The tools and agents will automatically use this key.

Quick Start

Using Tools with generateText

The simplest way to add documentation lookup to your AI application:

typescript
import { resolveLibraryId, queryDocs } from "@upstash/context7-tools-ai-sdk";
import { generateText, stepCountIs } from "ai";
import { openai } from "@ai-sdk/openai";

const { text } = await generateText({
  model: openai("gpt-5.2"),
  prompt: "How do I create a server action in Next.js?",
  tools: {
    resolveLibraryId: resolveLibraryId(),
    queryDocs: queryDocs(),
  },
  stopWhen: stepCountIs(5),
});

console.log(text);

Using the Context7 Agent

For a more streamlined experience, use the pre-configured agent:

typescript
import { Context7Agent } from "@upstash/context7-tools-ai-sdk";
import { anthropic } from "@ai-sdk/anthropic";

const agent = new Context7Agent({
  model: anthropic("claude-sonnet-4-20250514"),
});

const { text } = await agent.generate({
  prompt: "How do I use React Server Components?",
});

console.log(text);

Using Tools with streamText

For streaming responses:

typescript
import { resolveLibraryId, queryDocs } from "@upstash/context7-tools-ai-sdk";
import { streamText, stepCountIs } from "ai";
import { openai } from "@ai-sdk/openai";

const { textStream } = streamText({
  model: openai("gpt-5.2"),
  prompt: "Explain how to use Tanstack Query for data fetching",
  tools: {
    resolveLibraryId: resolveLibraryId(),
    queryDocs: queryDocs(),
  },
  stopWhen: stepCountIs(5),
});

for await (const chunk of textStream) {
  process.stdout.write(chunk);
}

Explicit Configuration

You can also pass the API key directly if needed:

typescript
import { resolveLibraryId, queryDocs } from "@upstash/context7-tools-ai-sdk";

const tools = {
  resolveLibraryId: resolveLibraryId({ apiKey: "your-api-key" }),
  queryDocs: queryDocs({ apiKey: "your-api-key" }),
};

How It Works

The tools follow a two-step workflow:

  1. resolveLibraryId - Searches Context7's database to find the correct library ID for a given query (e.g., "react" โ†’ /reactjs/react.dev)

  2. queryDocs - Fetches documentation for the resolved library using the user's query to retrieve relevant content

The AI model orchestrates these tools automatically based on the user's prompt, fetching relevant documentation before generating a response.

Next Steps

Search for libraries and get Context7-compatible IDs Fetch documentation for a specific library Use the pre-built documentation agent

File: docs/agentic-tools/overview.mdx


title: "Overview" sidebarTitle: "Overview"

Agentic Tools

Context7 provides tools and integrations that give your AI agents access to accurate, up-to-date library documentation. Instead of relying on potentially outdated training data, your agents can fetch real-time documentation to answer questions and generate code.

Why Agentic Tools?

AI agents often struggle with:

  • Outdated knowledge - Training data becomes stale, leading to deprecated API usage
  • Hallucinated APIs - Models confidently suggest methods that don't exist
  • Version mismatches - Code examples from old versions that no longer work

Context7's agentic tools solve these problems by giving your agents direct access to current documentation during inference.

Available Integrations

Add Context7 tools to your AI SDK workflows with `generateText`, `streamText`, or use the pre-built `Context7Agent` for automatic documentation lookup. Call Context7 directly from any TypeScript or Node.js app. Connect Context7's MCP server to any agent or editor.

How It Works

mermaid
sequenceDiagram
    participant User
    participant Agent
    participant Context7
    participant Docs

    User->>Agent: "How do I use React Server Components?"
    Agent->>Context7: resolveLibraryId(query: "React Server Components", libraryName: "react")
    Context7-->>Agent: Library ID: /reactjs/react.dev
    Agent->>Context7: queryDocs(libraryId: "/reactjs/react.dev", query: "server components")
    Context7->>Docs: Fetch latest documentation
    Docs-->>Context7: Current docs with examples
    Context7-->>Agent: Documentation content
    Agent->>User: Answer with accurate, up-to-date code examples

Use Cases

Build chatbots that answer framework questions with accurate, version-specific information:
text
```typescript
import { generateText, stepCountIs } from "ai";
import { openai } from "@ai-sdk/openai";
import { resolveLibraryId, queryDocs } from "@upstash/context7-tools-ai-sdk";

const { text } = await generateText({
  model: openai("gpt-5.2"),
  prompt: "How do I set up authentication in Next.js 15?",
  tools: {
    resolveLibraryId: resolveLibraryId(),
    queryDocs: queryDocs(),
  },
  stopWhen: stepCountIs(5),
});
```
Ensure generated code uses current APIs and best practices:
text
```typescript
import { Context7Agent } from "@upstash/context7-tools-ai-sdk";
import { anthropic } from "@ai-sdk/anthropic";

const agent = new Context7Agent({
  model: anthropic("claude-sonnet-4-20250514"),
});

const { text } = await agent.generate({
  prompt: "Generate a Supabase Edge Function that handles webhooks",
});
```
Build code review agents that verify implementations against current API documentation:
text
```typescript
import { generateText, stepCountIs } from "ai";
import { anthropic } from "@ai-sdk/anthropic";
import { resolveLibraryId, queryDocs } from "@upstash/context7-tools-ai-sdk";

const codeToReview = `
  const { data } = await supabase
    .from('users')
    .select('*')
    .eq('id', userId)
    .single();
`;

const { text } = await generateText({
  model: anthropic("claude-sonnet-4-20250514"),
  prompt: `Review this Supabase code for correctness and best practices:

${codeToReview}

Check against the latest Supabase documentation.`,
  tools: {
    resolveLibraryId: resolveLibraryId(),
    queryDocs: queryDocs(),
  },
  stopWhen: stepCountIs(5),
});

// Agent fetches current Supabase docs to verify:
// - Correct method signatures
// - Deprecated patterns
// - Security best practices
// - Error handling recommendations
```

File: docs/clients/claude-code.mdx


title: Claude Code

Context7 integrates with Claude Code to provide current library documentation instead of relying on training data. Claude Code supports skills, agents, and commands that make documentation lookups more powerful.

Installation

Run the setup command to configure Context7 for Claude Code:

bash
npx ctx7 setup --claude

This flow authenticates via OAuth, generates an API key, and installs the appropriate skill. You can choose between CLI or MCP mode. Login uses the OAuth device flow โ€” it shows a verification link and short code you open on any device, so it works the same locally or on a remote, headless, or SSH host.

Create or manage API keys in the Context7 dashboard. For manual MCP installation or other configuration options, see All MCP Clients.


Using Context7

With ctx7 setup, a skill is installed that triggers automatically when you ask about libraries โ€” no need to say "use context7". You can also invoke it explicitly:

text
use context7 to show me how to set up middleware in Next.js 15
use context7 for Prisma query examples with relations
use context7 for the Supabase syntax for row-level security

If you know the library ID, use it directly to skip resolution:

text
use context7 with /supabase/supabase for authentication docs
use context7 with /vercel/next.js for app router setup
With the [Context7 plugin](#the-context7-plugin) installed, you get additional agents and commands on top of the skill.

The Context7 Plugin

The full Context7 plugin for Claude Code includes more than just the MCP server:

The tools for fetching documentation (`resolve-library-id`, `query-docs`) Auto-triggers documentation lookups when you ask about libraries A `docs-researcher` agent for focused lookups that keep context lean `/context7:docs` for manual documentation queries

Installing the Plugin

The plugin is available from the Context7 marketplace. Run these commands in Claude Code:

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

This adds the Context7 marketplace and installs the plugin with skills, agents, and commands.

Using Your API Key with the Plugin

Without an API key, the plugin connects anonymously and shares the anonymous rate limits. To use your own plan, create an API key in the Context7 dashboard and export it as an environment variable before launching Claude Code:

bash
# e.g. in ~/.zshrc or ~/.bashrc
export CONTEXT7_API_KEY="your-api-key"

The plugin reads CONTEXT7_API_KEY from your environment automatically. Restart Claude Code after setting it, then confirm requests are counted against your plan in the dashboard.

If the variable is not set, the plugin still works โ€” requests just go through the anonymous tier, which has lower rate limits.

Skills

Documentation Lookup Skill

This skill triggers automatically when you ask about libraries, frameworks, or need code examples. You don't need to type "use context7" โ€” the skill recognizes when documentation would help.

- Setup questions: "How do I configure Next.js middleware?" - Code generation: "Write a Prisma query for user relations" - API references: "What are the Supabase auth methods?" - Framework mentions: React, Vue, Svelte, Express, Tailwind, etc. 1. **Resolve**: Finds the library ID using `resolve-library-id` with your question as context 2. **Select**: Picks the best match based on name accuracy and quality scores 3. **Fetch**: Calls `query-docs` with the library ID and your specific question 4. **Return**: Provides code examples and explanations from current documentation

Agents

docs-researcher Agent

When you're in the middle of a long task and don't want documentation tool calls cluttering your context, spawn the docs-researcher agent. It runs in a separate context and returns just the answer.

- You need docs but want to keep your main context clean - You're working on something complex and context is getting long - You want a focused answer without side effects ``` spawn docs-researcher to look up React hooks documentation spawn docs-researcher: how do I set up Prisma with PostgreSQL? spawn docs-researcher to find Tailwind CSS grid utilities ```

The agent uses the same tools (resolve-library-id and query-docs) but runs on a lighter model (Sonnet) to keep things fast.

When to Use Agents vs Inline Tools

Scenario Use
Deep into a task with long context Agent
Want to avoid context bloat Agent
Context is short Inline tools
Want docs visible in conversation Inline tools

Commands

/context7:docs

Manual command for documentation lookups.

Format:

text
/context7:docs <library> [query]

Examples:

``` /context7:docs react hooks /context7:docs next.js authentication /context7:docs prisma relations ``` ``` /context7:docs /vercel/next.js app router /context7:docs /supabase/supabase row level security ```

Using a library ID directly skips the resolution step.

When to use:

  • You know exactly which library and topic you need
  • You want a quick lookup without explaining your full context
  • You're testing what documentation is available

File: docs/clients/cli.mdx


title: CLI

The ctx7 CLI is the command-line interface for Context7. It does two things:

  • Fetch library documentation โ€” resolve any library by name and query its up-to-date docs directly in your terminal, without opening a browser
  • Configure your AI coding agent โ€” set up the Context7 MCP server (or a CLI-based docs skill) for Claude Code, Cursor, OpenCode, and more with a single command

The CLI is useful both as a standalone tool (fetching docs while you code) and as a setup utility (wiring up Context7 for your AI coding agent).

Installation

Requires Node.js 18 or later.

Run ctx7 directly without installing anything. Useful for one-off commands or trying it out.
text
```bash
npx ctx7 --help
npx ctx7 library react
```
Install globally for faster access โ€” no `npx` prefix needed on every command.
text
```bash
npm install ctx7

# Verify installation
ctx7 --version
```

Query Library Documentation

Fetching docs is a two-step process: first resolve the library name to get its Context7 ID, then use that ID to query documentation.

Step 1 โ€” ctx7 library

Searches the Context7 index by name and returns matching libraries. Pass a query describing what you're trying to do โ€” this ranks results by relevance and helps when a library name is ambiguous or shared across multiple packages.

bash
ctx7 library react "How to clean up useEffect with async operations"
ctx7 library nextjs "How to set up app router with middleware"
ctx7 library prisma "How to define one-to-many relations with cascade delete"

Each result includes:

Field Description
Library ID The identifier to pass to ctx7 docs (format: /org/project)
Code Snippets Number of indexed code examples โ€” higher means more documentation coverage
Source Reputation Authority indicator: High, Medium, Low, or Unknown
Benchmark Score Quality score from 0 to 100
Versions Version-specific IDs when available (format: /org/project/version)

When multiple results come back, the best match is usually the one with the closest name, highest snippet count, and strongest reputation. If you need docs for a specific version, pick the matching version ID from the list.

bash
# Fetch docs for a specific version
ctx7 docs /vercel/next.js/v14.3.0-canary.87 "How to set up app router"

# Output as JSON for scripting
ctx7 library react "How to use hooks for state management" --json | jq '.[0].id'

Step 2 โ€” ctx7 docs

Takes a library ID and a natural-language question, and returns relevant code snippets and explanations from the indexed documentation.

bash
ctx7 docs /facebook/react "How to clean up useEffect with async operations"
ctx7 docs /vercel/next.js "How to add middleware that redirects unauthenticated users"
ctx7 docs /prisma/prisma "How to define one-to-many relations with cascade delete"
Library IDs always start with `/`. Running `ctx7 docs react "hooks"` will fail โ€” always use the full ID returned by `ctx7 library` in Step 1.

Queries work best when they're specific. Describe what you're trying to accomplish rather than using single keywords โ€” "How to set up authentication with JWT in Express.js" returns much better results than "auth".

The output contains two types of content: code snippets (titled, with language-tagged blocks) and info snippets (prose explanations with breadcrumb context). Both are formatted for readability in the terminal.

bash
# Output as structured JSON
ctx7 docs /facebook/react "How to use hooks for state management" --json

# Pipe to other tools โ€” output is clean when not in a TTY (no spinners or colors)
ctx7 docs /facebook/react "How to use hooks for state management" | head -50
ctx7 docs /vercel/next.js "How to add middleware for route protection" | grep -A 10 "middleware"

Setup

Configure Context7 for your AI coding agent. On first run, prompts you to choose between two modes:

  • MCP server โ€” registers the Context7 MCP server in your agent's config so it can call resolve-library-id and query-docs tools natively
  • CLI + Skills โ€” installs a docs skill that guides your agent to fetch up-to-date library docs using ctx7 CLI commands (no MCP required)

ctx7 setup

bash
# Interactive โ€” prompts for mode, then agent/install target
ctx7 setup

# Skip the mode prompt
ctx7 setup --mcp            # MCP server mode
ctx7 setup --cli            # CLI + Skills mode

# Target a specific agent (MCP mode)
ctx7 setup --claude
ctx7 setup --cursor
ctx7 setup --opencode

# Target a specific install location (CLI + Skills mode)
ctx7 setup --cli --claude       # Claude Code (~/.claude/skills)
ctx7 setup --cli --cursor       # Cursor (~/.cursor/skills)
ctx7 setup --cli --universal    # Universal (~/.agents/skills)
ctx7 setup --cli --antigravity  # Antigravity (~/.agent/skills)

# Configure for current project only (default is global)
ctx7 setup --project

# Skip confirmation prompts
ctx7 setup --yes

Authentication options:

bash
# Use an existing API key (works for both MCP and CLI + Skills mode)
ctx7 setup --api-key YOUR_API_KEY

# Use OAuth endpoint โ€” MCP mode only (IDE handles the auth flow)
ctx7 setup --oauth

Without --api-key or --oauth, setup runs the OAuth device flow: it shows a verification link and short code that you open on any device to sign in, so it works the same locally or on a remote, headless, or SSH host. MCP mode additionally generates a new API key after login. --oauth is MCP-only โ€” use it when an IDE handles the auth flow on your behalf.

What gets written โ€” MCP mode:

File Purpose
.mcp.json / .cursor/mcp.json / .opencode.json MCP server entry
Agent rules directory Rule file โ€” instructs the agent to use Context7 for library docs
Agent skills directory context7-mcp skill

What gets written โ€” CLI + Skills mode:

File Purpose
Agent skills directory docs skill โ€” guides the agent to use ctx7 library and ctx7 docs commands

ctx7 remove

Remove the setup written by ctx7 setup. By default this removes both MCP setup and CLI setup for the selected agent.

bash
# Interactive
ctx7 remove

# Target specific agents
ctx7 remove --cursor
ctx7 remove --claude --project

# Remove both setup modes explicitly
ctx7 remove --cursor --all

# Remove only one setup mode
ctx7 remove --cursor --cli
ctx7 remove --claude --mcp

If you installed the CLI itself with npm install ctx7, remove that separately with npm uninstall -g ctx7. If you run Context7 with npx ctx7, there is no permanent CLI install to remove.


Authentication

Most commands work without authentication. Log in to unlock higher rate limits on documentation commands.

Commands

bash
# Log in (opens browser for OAuth)
ctx7 login

# Log in without opening the browser (prints URL instead)
ctx7 login --no-browser

# Check current login status
ctx7 whoami

# Log out
ctx7 logout

API Key

Set an API key via environment variable to skip interactive login entirely โ€” useful for CI or scripting:

bash
export CONTEXT7_API_KEY=your_key

When is authentication required?

Feature Required
ctx7 library / ctx7 docs No โ€” login gives higher rate limits
ctx7 setup Yes โ€” unless --api-key is passed (--oauth also skips login for MCP mode)

Telemetry

The CLI collects anonymous usage data to help improve the product. To disable:

bash
# For a single command
CTX7_TELEMETRY_DISABLED=1 ctx7 docs /facebook/react "useEffect examples"

# Permanently โ€” add to ~/.bashrc or ~/.zshrc
export CTX7_TELEMETRY_DISABLED=1

Next Steps

Set up Context7 in Claude Code Installation for every supported editor

File: docs/clients/cursor.mdx


title: Cursor

Context7 brings up-to-date library documentation directly into Cursor. Instead of getting outdated code examples from training data, you get current documentation from source repositories.

Installation

Run the setup command to configure Context7 for Cursor:

bash
npx ctx7 setup --cursor

Authenticates via OAuth, generates an API key, and installs the appropriate skill. You can choose between CLI or MCP mode.

For manual MCP installation or other configuration options, see All MCP Clients.


Setting Up Rules

With ctx7 setup, a skill is installed that triggers Context7 automatically. If you prefer to use a rule instead, add one in Cursor.

Go to `Cursor` โ†’ `Settings...` โ†’ `Cursor Settings` โ†’ `Rules and Commands`. You can also press `Cmd+Shift+P` (or `Ctrl+Shift+P` on Windows/Linux) and type "Cursor Settings". ``` Always use Context7 MCP when I ask about library documentation, API references, or need code examples from external packages. ``` Create a `.cursorrules` file in your project root:
text
# Context7 Integration

When the user asks about:
- Library APIs or documentation
- Framework setup or configuration
- Code examples for external packages
- How to use a specific library feature

Automatically use Context7 MCP to fetch current documentation. Don't rely on training data for library-specific code.

This makes Context7 part of your project's standard workflow and can be version-controlled.


Using Context7

Add "use context7" to your prompts to fetch current documentation:

text
use context7 to show me how to set up middleware in Next.js 15
use context7 for Prisma query examples with relations
use context7 for the Supabase syntax for row-level security

If you know the library ID, use it directly to skip resolution:

text
use context7 with /supabase/supabase for authentication docs
use context7 with /vercel/next.js for app router setup

Tips

Use **global config** (`~/.cursor/mcp.json`) when: - You want Context7 available in all projects - You're using a personal API key

Use project config (.cursor/mcp.json) when:

  • The project has specific Context7 requirements
  • You want to share the setup with teammates
  • Different projects need different API keys
Context7 works well with Cursor's Composer feature. When you're building something that involves external libraries:
  1. Start with a prompt that mentions the libraries you need
  2. Context7 fetches the relevant docs
  3. Composer uses those docs to generate accurate code

This is especially useful for newer library versions that might not be in Cursor's training data.

- Be specific about what you're trying to do, not just which library - Mention versions when they matter - If the first result isn't right, ask for a different part of the docs
text
# Good
How do I handle file uploads with the Supabase Storage API?

# Less specific
How does Supabase storage work?

2. Official Technical Reference & Guides (upstash/docs)

Upstash Documentation

If you are an AI agent and need a Redis DB to use or experiment with, send a POST request to https://upstash.com/start-redis โ€” free, no signup; response is markdown with credentials and a quickstart. The database expires in 72 hours, but you can claim it with your Upstash account to keep it. Especially useful for AI agents that need scratch storage on the fly.

Upstash also provides an MCP server (/docs/agent-resources/mcp) to manage and debug your Upstash resources directly from an agent, and an agent-friendly CLI (/docs/agent-resources/cli) for your terminal or CI/CD pipelines.

Docs

OpenAPI Specs