Try Live
Add Docs
Rankings
Pricing
Docs
Install
Install
Docs
Pricing
More...
More...
Try Live
Rankings
Enterprise
Create API Key
Add Docs
Context7 MCP Server
https://github.com/upstash/context7
Admin
Context7 MCP provides up-to-date, version-specific documentation and code examples directly from the
...
Tokens:
75,936
Snippets:
463
Trust Score:
9.5
Update:
4 days ago
Context
Skills
Chat
Benchmark
70.8
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# Context7 Platform Context7 is a documentation platform that provides up-to-date, version-specific library documentation and code examples directly to AI coding assistants. It solves the problem of LLMs relying on outdated training data by fetching current documentation from the source, preventing hallucinated APIs and generic answers based on old package versions. The platform works through two modes: CLI + Skills (using `ctx7` CLI commands) and MCP (Model Context Protocol server), enabling seamless integration with coding agents like Cursor, Claude Code, VS Code, and many others. The platform consists of multiple packages: an MCP server (`@upstash/context7-mcp`) for native tool integration, a TypeScript SDK (`@upstash/context7-sdk`) for programmatic access, AI SDK tools (`@upstash/context7-tools-ai-sdk`) for Vercel AI SDK integration, and a CLI (`ctx7`) for command-line access and agent setup. All packages work together to provide accurate library documentation to AI assistants, ensuring code generation uses correct, current APIs. ## REST API ### Search Library Endpoint Search for available libraries by name to find the correct Context7 library ID before fetching documentation. Returns matching libraries with metadata including trust scores, snippet counts, and available versions. ```bash # Search for React libraries curl "https://context7.com/api/v2/libs/search?libraryName=react&query=hooks" \ -H "Authorization: Bearer CONTEXT7_API_KEY" # Response: # [ # { # "id": "/facebook/react", # "name": "React", # "description": "A JavaScript library for building user interfaces", # "totalSnippets": 1250, # "trustScore": 95, # "benchmarkScore": 88, # "versions": ["v18.2.0", "v17.0.2"] # } # ] # Search for Next.js with specific query curl "https://context7.com/api/v2/libs/search?libraryName=nextjs&query=How%20to%20implement%20authentication" \ -H "Authorization: Bearer CONTEXT7_API_KEY" ``` ### Get Context Endpoint Retrieve documentation context for a specific library. Returns relevant documentation snippets based on your query in JSON or plain text format. ```bash # Get documentation as JSON (default) curl "https://context7.com/api/v2/context?libraryId=/facebook/react&query=useEffect" \ -H "Authorization: Bearer CONTEXT7_API_KEY" # Response: # [ # { # "title": "Using the Effect Hook", # "content": "The Effect Hook lets you perform side effects...", # "source": "react.dev/reference/react/useEffect" # } # ] # Get documentation as plain text (for LLM prompts) curl "https://context7.com/api/v2/context?libraryId=/facebook/react&query=useEffect&type=txt" \ -H "Authorization: Bearer CONTEXT7_API_KEY" # Get documentation for a specific version curl "https://context7.com/api/v2/context?libraryId=/vercel/next.js/v15.1.8&query=app%20router" \ -H "Authorization: Bearer CONTEXT7_API_KEY" ``` ### Complete API Workflow Example Python example demonstrating the full workflow: search for a library, then fetch documentation. ```python import requests import time headers = {"Authorization": "Bearer CONTEXT7_API_KEY"} # Step 1: Search for the library search_response = requests.get( "https://context7.com/api/v2/libs/search", headers=headers, params={"libraryName": "react", "query": "I need to manage state"} ) libraries = search_response.json() best_match = libraries[0] print(f"Found: {best_match['name']} ({best_match['id']})") # Step 2: Get documentation context context_response = requests.get( "https://context7.com/api/v2/context", headers=headers, params={"libraryId": best_match["id"], "query": "How do I use useState?"} ) docs = context_response.json() for doc in docs: print(f"Title: {doc['title']}") print(f"Content: {doc['content'][:200]}...") # Rate limit handling with exponential backoff def fetch_with_retry(url, headers, params, max_retries=3): for attempt in range(max_retries): response = requests.get(url, headers=headers, params=params) if response.status_code == 429: time.sleep(2 ** attempt) continue return response raise Exception("Max retries exceeded") ``` ## TypeScript SDK ### Context7 Client Initialization Initialize the Context7 SDK client for programmatic access to library documentation. Supports both environment variable and explicit API key configuration. ```typescript import { Context7, Context7Error } from "@upstash/context7-sdk"; // Option 1: Using environment variable (CONTEXT7_API_KEY) const client = new Context7(); // Option 2: Explicit API key configuration const clientWithKey = new Context7({ apiKey: "ctx7sk-your-api-key-here", }); // Error handling example try { const docs = await client.getContext("query", "/invalid/library"); } catch (error) { if (error instanceof Context7Error) { console.error("Context7 API Error:", error.message); } else { console.error("Unexpected error:", error); } } ``` ### searchLibrary Method Search for libraries matching a query and library name. Returns an array of Library objects with metadata or formatted text. ```typescript import { Context7 } from "@upstash/context7-sdk"; const client = new Context7(); // Search libraries - returns Library[] by default const libraries = await client.searchLibrary( "I need to build a UI with components", // query for relevance ranking "react" // library name to search ); console.log(`Found ${libraries.length} libraries`); console.log(libraries[0].id); // "/facebook/react" console.log(libraries[0].name); // "React" console.log(libraries[0].description); // "A JavaScript library for building user interfaces" console.log(libraries[0].totalSnippets); // 1250 console.log(libraries[0].trustScore); // 95 console.log(libraries[0].benchmarkScore); // 88 console.log(libraries[0].versions); // ["v18.2.0", "v17.0.2"] // Get results as formatted text const textResults = await client.searchLibrary( "database ORM", "prisma", { type: "txt" } ); console.log(textResults); // Formatted string output ``` ### getContext Method Retrieve documentation context for a specific library. Returns documentation snippets as an array or plain text suitable for LLM prompts. ```typescript import { Context7 } from "@upstash/context7-sdk"; const client = new Context7(); // Get documentation as JSON array (default) const docs = await client.getContext( "How do I use hooks?", // query describing what you need "/facebook/react" // Context7 library ID ); console.log(docs[0].title); // "Using the Effect Hook" console.log(docs[0].content); // Full documentation content with code examples console.log(docs[0].source); // "react.dev/reference/react/useEffect" // Get documentation as plain text (ideal for LLM context) const context = await client.getContext( "How do I use hooks?", "/facebook/react", { type: "txt" } ); console.log(context); // Plain text documentation ready for prompts // Query documentation for a specific version const versionedDocs = await client.getContext( "app router setup", "/vercel/next.js/v15.1.8" ); ``` ## Vercel AI SDK Tools ### resolveLibraryId Tool AI SDK tool that resolves a library name to a Context7-compatible library ID. Use this before queryDocs to find the correct library. ```typescript import { resolveLibraryId, queryDocs } from "@upstash/context7-tools-ai-sdk"; import { generateText, stepCountIs } from "ai"; import { openai } from "@ai-sdk/openai"; // Basic usage with generateText const { text } = await generateText({ model: openai("gpt-4o"), prompt: "Find React documentation about hooks", tools: { resolveLibraryId: resolveLibraryId(), queryDocs: queryDocs(), }, stopWhen: stepCountIs(5), }); console.log(text); // With explicit API key configuration const toolsWithKey = { resolveLibraryId: resolveLibraryId({ apiKey: "ctx7sk-your-key" }), queryDocs: queryDocs({ apiKey: "ctx7sk-your-key" }), }; ``` ### queryDocs Tool AI SDK tool that fetches documentation for a library using its Context7 library ID. Returns documentation content relevant to the query. ```typescript import { resolveLibraryId, queryDocs } from "@upstash/context7-tools-ai-sdk"; import { streamText, stepCountIs } from "ai"; import { openai } from "@ai-sdk/openai"; // Streaming response with documentation lookup const { textStream } = streamText({ model: openai("gpt-4o"), 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); } ``` ### Context7Agent Pre-built agent that handles the entire documentation lookup workflow automatically. Simplifies integration for common use cases. ```typescript import { Context7Agent } from "@upstash/context7-tools-ai-sdk/agent"; import { anthropic } from "@ai-sdk/anthropic"; // Create agent with Anthropic model const agent = new Context7Agent({ model: anthropic("claude-sonnet-4-20250514"), }); // Generate response with automatic documentation lookup const { text } = await agent.generate({ prompt: "How do I use React Server Components?", }); console.log(text); // Agent with OpenAI import { openai } from "@ai-sdk/openai"; const openaiAgent = new Context7Agent({ model: openai("gpt-4o"), }); const result = await openaiAgent.generate({ prompt: "Show me how to set up authentication middleware in Next.js", }); ``` ## MCP Server ### Running the MCP Server The MCP server provides native tool integration for AI coding assistants via the Model Context Protocol. Supports stdio and HTTP transport modes. ```bash # Run with stdio transport (default, for local MCP clients) npx @upstash/context7-mcp --api-key YOUR_API_KEY # Run with HTTP transport (for remote connections) npx @upstash/context7-mcp --transport http --port 3000 # Environment variable authentication export CONTEXT7_API_KEY=ctx7sk-your-key npx @upstash/context7-mcp ``` ### MCP Client Configuration Configure your AI coding agent to connect to the Context7 MCP server. Examples for popular clients. ```json // Cursor (~/.cursor/mcp.json) - Remote connection { "mcpServers": { "context7": { "url": "https://mcp.context7.com/mcp", "headers": { "CONTEXT7_API_KEY": "YOUR_API_KEY" } } } } // Cursor - Local connection { "mcpServers": { "context7": { "command": "npx", "args": ["-y", "@upstash/context7-mcp", "--api-key", "YOUR_API_KEY"] } } } // VS Code settings.json { "mcp": { "servers": { "context7": { "type": "http", "url": "https://mcp.context7.com/mcp", "headers": { "CONTEXT7_API_KEY": "YOUR_API_KEY" } } } } } // Claude Desktop (claude_desktop_config.json) { "mcpServers": { "context7": { "command": "npx", "args": ["-y", "@upstash/context7-mcp", "--api-key", "YOUR_API_KEY"] } } } ``` ### MCP Tools: resolve-library-id MCP tool that resolves a package/product name to a Context7-compatible library ID. Called automatically by AI assistants before querying documentation. ```typescript // Tool schema (for MCP client reference) // Tool: resolve-library-id // Parameters: // - query (string, required): The question or task for relevance ranking // - libraryName (string, required): Library name to search for // Example AI assistant interaction: // User: "How do I use React hooks?" // Assistant calls: resolve-library-id({ query: "How do I use React hooks?", libraryName: "react" }) // Returns: Library list with IDs like "/facebook/react" // Response format: // Available Libraries: // 1. Title: React // Context7-compatible library ID: /facebook/react // Description: A JavaScript library for building user interfaces // Code Snippets: 1250 // Source Reputation: High // Benchmark Score: 88 // Versions: v18.2.0, v17.0.2 ``` ### MCP Tools: query-docs MCP tool that retrieves up-to-date documentation and code examples for any programming library or framework using the Context7 library ID. ```typescript // Tool schema (for MCP client reference) // Tool: query-docs // Parameters: // - libraryId (string, required): Context7-compatible library ID (e.g., "/facebook/react") // - query (string, required): The question or task to get relevant documentation for // Example AI assistant interaction: // After resolving library ID, assistant calls: // query-docs({ libraryId: "/facebook/react", query: "useEffect cleanup function examples" }) // Returns relevant documentation snippets with code examples directly in the response ``` ## CLI Commands ### ctx7 setup Set up Context7 for your AI coding agent with a single command. Authenticates via OAuth, generates an API key, and installs the appropriate skill. ```bash # Interactive setup (recommended) npx ctx7 setup # Setup for specific agent npx ctx7 setup --claude # Claude Code npx ctx7 setup --cursor # Cursor npx ctx7 setup --opencode # OpenCode # Setup modes npx ctx7 setup --mcp # MCP server mode npx ctx7 setup --cli # CLI + Skills mode (no MCP server) # Project-level setup (instead of global) npx ctx7 setup --project # Non-interactive setup with existing API key npx ctx7 setup --api-key ctx7sk-your-key --yes # OAuth mode (IDE handles auth flow) npx ctx7 setup --oauth ``` ### ctx7 library Resolve a library name to a Context7-compatible library ID. Use this to find the correct ID before querying documentation. ```bash # Search for a library npx ctx7 library react # Search with relevance query npx ctx7 library react "how to use hooks" # Output as JSON npx ctx7 library nextjs --json # Example output: # 1. Title: React # Context7-compatible library ID: /facebook/react # Description: A JavaScript library for building user interfaces # Code Snippets: 1250 # Source Reputation: High # # Quick command: # ctx7 docs "/facebook/react" "<your question>" ``` ### ctx7 docs Query documentation for a library using its Context7 library ID. Returns relevant documentation snippets with code examples. ```bash # Query documentation npx ctx7 docs /facebook/react "useEffect examples" # Query specific version npx ctx7 docs /vercel/next.js/v15.1.8 "app router middleware" # Output as JSON npx ctx7 docs /supabase/supabase "authentication setup" --json # Example output: # Using the Effect Hook # The Effect Hook lets you perform side effects in function components... # # ```javascript # useEffect(() => { # document.title = `You clicked ${count} times`; # return () => { # // cleanup # }; # }, [count]); # ``` ``` ### ctx7 skills Manage AI coding skills - search, install, list, and remove skills from your coding agents. ```bash # Search for skills npx ctx7 skills search pdf npx ctx7 skills search react hooks # Install skills from a repository npx ctx7 skills install /anthropics/skills npx ctx7 skills install /anthropics/skills pdf # Install to specific client npx ctx7 skills install /anthropics/skills --cursor npx ctx7 skills install /anthropics/skills --claude npx ctx7 skills install /anthropics/skills --global # List installed skills npx ctx7 skills list --claude npx ctx7 skills list --cursor # Remove a skill npx ctx7 skills remove pdf ``` ## Summary Context7 enables AI coding assistants to access accurate, up-to-date library documentation instead of relying on outdated training data. The primary use cases include: integrating with MCP-compatible coding agents (Cursor, Claude Code, VS Code) for automatic documentation fetching, building custom AI applications with the TypeScript SDK or Vercel AI SDK tools, and using the CLI for quick documentation lookups during development. The platform supports version-specific documentation queries, ensuring generated code uses correct APIs for the exact library version in your project. Integration patterns vary by use case: for coding agents, use `npx ctx7 setup` for one-command installation; for custom AI applications, integrate the SDK directly or use AI SDK tools with `generateText`/`streamText`; for programmatic access, use the REST API with proper authentication and rate limit handling. All methods follow a two-step workflow: first resolve the library name to a Context7 ID, then query documentation with your specific question. The platform handles caching, retries, and error handling internally, making it straightforward to add accurate documentation context to any AI-powered development workflow.