Try Live
Add Docs
Rankings
Pricing
Enterprise
Docs
Install
Install
Docs
Pricing
Enterprise
More...
More...
Try Live
Rankings
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:
77,234
Snippets:
567
Trust Score:
9.5
Update:
2 weeks ago
Context
Skills
Chat
Benchmark
71.1
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# Context7 Platform Context7 is an AI-powered documentation platform that provides up-to-date, version-specific library documentation directly to LLMs and coding agents. It solves the problem of AI assistants relying on outdated training data by fetching real-time documentation from the source. The platform indexes thousands of libraries and frameworks, making current API references, code examples, and best practices available during inference. The platform operates in two modes: MCP (Model Context Protocol) server for native integration with AI coding agents, and CLI + Skills mode for terminal-based documentation lookup. Context7 offers a REST API, TypeScript SDK (`@upstash/context7-sdk`), Vercel AI SDK integration (`@upstash/context7-tools-ai-sdk`), and a command-line tool (`ctx7`). Library owners can claim their projects, configure parsing rules via `context7.json`, and manage versioned documentation through a web dashboard. ## REST API ### Search Libraries Searches the Context7 index by library name and returns matching libraries ranked by relevance to your query. ```bash # Search for React libraries related to state management curl -X GET "https://context7.com/api/v2/libs/search?libraryName=react&query=How%20to%20manage%20state%20with%20hooks" \ -H "Authorization: Bearer ctx7sk-your-api-key" # Response { "results": [ { "id": "/facebook/react", "title": "React", "description": "A JavaScript library for building user interfaces", "branch": "main", "lastUpdateDate": "2025-01-15T10:30:00.000Z", "state": "finalized", "totalTokens": 500000, "totalSnippets": 2500, "stars": 220000, "trustScore": 10, "benchmarkScore": 95.5, "versions": ["v18.2.0", "v17.0.2"] } ], "searchFilterApplied": false } ``` ### Get Documentation Context Retrieves LLM-reranked documentation snippets and code examples for a specific library based on your query. ```bash # Get documentation about Next.js middleware authentication curl -X GET "https://context7.com/api/v2/context?libraryId=/vercel/next.js&query=How%20to%20implement%20authentication%20with%20middleware&type=json" \ -H "Authorization: Bearer ctx7sk-your-api-key" # Response { "codeSnippets": [ { "codeTitle": "Middleware Authentication Example", "codeDescription": "Shows how to implement authentication checks in Next.js middleware", "codeLanguage": "typescript", "codeTokens": 150, "codeId": "https://github.com/vercel/next.js/blob/canary/docs/middleware.mdx#_snippet_0", "pageTitle": "Middleware", "codeList": [ { "language": "typescript", "code": "import { NextResponse } from 'next/server'\nimport type { NextRequest } from 'next/server'\n\nexport function middleware(request: NextRequest) {\n const token = request.cookies.get('token')\n if (!token) {\n return NextResponse.redirect(new URL('/login', request.url))\n }\n return NextResponse.next()\n}" } ] } ], "infoSnippets": [ { "pageId": "https://github.com/vercel/next.js/blob/canary/docs/middleware.mdx", "breadcrumb": "Routing > Middleware", "content": "Middleware allows you to run code before a request is completed...", "contentTokens": 200 } ] } # Get plain text response for LLM prompts curl -X GET "https://context7.com/api/v2/context?libraryId=/vercel/next.js&query=How%20to%20implement%20authentication%20with%20middleware&type=txt" \ -H "Authorization: Bearer ctx7sk-your-api-key" ``` ### Add GitHub Repository Submits a GitHub repository for documentation processing and indexing. ```bash # Add a public repository curl -X POST "https://context7.com/api/v2/add/repo/github" \ -H "Authorization: Bearer ctx7sk-your-api-key" \ -H "Content-Type: application/json" \ -d '{ "docsRepoUrl": "https://github.com/vercel/next.js" }' # Add a private repository with access token curl -X POST "https://context7.com/api/v2/add/repo/github" \ -H "Authorization: Bearer ctx7sk-your-api-key" \ -H "Content-Type: application/json" \ -d '{ "docsRepoUrl": "https://github.com/myorg/private-repo", "gitToken": "ghp_your-github-token", "private": true }' # Response { "libraryName": "/vercel/next.js", "message": "Repository submitted successfully" } ``` ### Refresh Library Triggers a refresh of an existing library to fetch the latest documentation updates. ```bash curl -X POST "https://context7.com/api/v1/refresh" \ -H "Authorization: Bearer ctx7sk-your-api-key" \ -H "Content-Type: application/json" \ -d '{ "libraryName": "/vercel/next.js" }' # Response { "message": "Refresh started successfully" } ``` ### Get Teamspace Policies Retrieves the current policy configuration for access control and library filters. ```bash curl -X GET "https://context7.com/api/v2/policies" \ -H "Authorization: Bearer ctx7sk-your-api-key" # Response { "sourceTypes": { "public_repos": { "enabled": true }, "private_sources": { "enabled": true }, "confluence": { "enabled": false }, "uploaded_files": { "enabled": true }, "websites": { "enabled": true }, "llmstxt": { "enabled": true } }, "libraryFilters": { "mode": "quality", "quality": { "requireVerified": false, "minTrustScore": null, "maxAgeDays": 365, "blockedLibraries": ["/org/repo"], "exceptedLibraries": ["/vercel/next.js"], "repoFilters": { "minStars": 100 } }, "select": { "allowedLibraries": [] } }, "accessibleLibraryCount": 4521 } ``` ### Update Teamspace Policies Incrementally updates policy configuration for source type access and library filtering. ```bash # Block a library and set quality filters curl -X PATCH "https://context7.com/api/v2/policies" \ -H "Authorization: Bearer ctx7sk-your-api-key" \ -H "Content-Type: application/json" \ -d '{ "sourceTypes": { "enable": ["websites"], "disable": ["confluence"] }, "libraryFilters": { "mode": "quality", "quality": { "minTrustScore": 4, "blockedLibraries": { "add": ["/org/untrusted-repo"] }, "repoFilters": { "minStars": 100 } } } }' ``` ### Add Website Submits a documentation website for crawling and indexing. ```bash curl -X POST "https://context7.com/api/v2/add/website" \ -H "Authorization: Bearer ctx7sk-your-api-key" \ -H "Content-Type: application/json" \ -d '{ "websiteUrl": "https://docs.example.com", "websiteBaseUrl": "https://docs.example.com/api" }' ``` ### Add OpenAPI Specification Submits an OpenAPI specification URL for automatic API documentation generation. ```bash curl -X POST "https://context7.com/api/v2/add/openapi" \ -H "Authorization: Bearer ctx7sk-your-api-key" \ -H "Content-Type: application/json" \ -d '{ "openApiUrl": "https://api.example.com/openapi.json" }' ``` ### Add LLMs.txt File Submits an llms.txt file for documentation processing. ```bash curl -X POST "https://context7.com/api/v2/add/llmstxt" \ -H "Authorization: Bearer ctx7sk-your-api-key" \ -H "Content-Type: application/json" \ -d '{ "llmstxtUrl": "https://docs.example.com/llms.txt" }' ``` ## TypeScript SDK ### Installation and Setup Install the SDK and initialize the client for programmatic access to Context7. ```typescript // Installation: npm install @upstash/context7-sdk import { Context7, Context7Error } from "@upstash/context7-sdk"; // Option 1: Use environment variable CONTEXT7_API_KEY const client = new Context7(); // Option 2: Pass API key directly const client = new Context7({ apiKey: "ctx7sk-your-api-key" }); ``` ### Search Libraries Searches for libraries and returns metadata including trust scores, snippet counts, and available versions. ```typescript import { Context7 } from "@upstash/context7-sdk"; const client = new Context7(); // Search for 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`); libraries.forEach((lib) => { console.log(`${lib.name} (${lib.id})`); console.log(` Snippets: ${lib.totalSnippets}`); console.log(` Trust Score: ${lib.trustScore}`); console.log(` Benchmark: ${lib.benchmarkScore}`); if (lib.versions) { console.log(` Versions: ${lib.versions.join(", ")}`); } }); // Get best library by score const sorted = libraries.sort((a, b) => b.benchmarkScore - a.benchmarkScore); const best = sorted[0]; console.log(`Best match: ${best.name} (${best.id})`); ``` ### Get Documentation Context Retrieves relevant documentation snippets for a specific library based on your query. ```typescript import { Context7, Context7Error } from "@upstash/context7-sdk"; const client = new Context7(); // Get documentation as JSON array (default) const docs = await client.getContext( "How do I use hooks for state management?", "/facebook/react" ); docs.forEach((doc) => { console.log(`Title: ${doc.title}`); console.log(`Source: ${doc.source}`); console.log(`Content: ${doc.content.substring(0, 200)}...`); }); // Get documentation as plain text for LLM prompts const context = await client.getContext( "How do I use hooks for state management?", "/facebook/react", { type: "txt" } ); console.log(context); // Query specific version const v18Docs = await client.getContext( "useEffect cleanup patterns", "/facebook/react/v18.2.0" ); // Error handling try { const docs = await client.getContext("query", "/invalid/library"); } catch (error) { if (error instanceof Context7Error) { console.error("Context7 API Error:", error.message); } } ``` ### Complete Workflow Example End-to-end example showing library search and documentation retrieval. ```typescript import { Context7 } from "@upstash/context7-sdk"; const client = new Context7(); async function getDocsForPrompt(libraryName: string, question: string) { // Step 1: Search for the library const libraries = await client.searchLibrary(question, libraryName); if (libraries.length === 0) { throw new Error(`No libraries found for "${libraryName}"`); } const library = libraries[0]; console.log(`Using: ${library.name} (${library.id})`); // Step 2: Get documentation context const context = await client.getContext(question, library.id, { type: "txt" }); // Step 3: Build prompt with documentation return ` Here is the relevant documentation for ${library.name}: ${context} User question: ${question} `; } const prompt = await getDocsForPrompt("react", "How do I use useEffect with cleanup?"); console.log(prompt); ``` ## Vercel AI SDK Integration ### Installation and Tool Setup Add Context7 documentation tools to your Vercel AI SDK applications. ```typescript // Installation: npm install @upstash/context7-tools-ai-sdk import { resolveLibraryId, queryDocs } from "@upstash/context7-tools-ai-sdk"; import { generateText, stepCountIs } from "ai"; import { openai } from "@ai-sdk/openai"; // Tools automatically use CONTEXT7_API_KEY environment variable const { text } = await generateText({ model: openai("gpt-4o"), prompt: "How do I create a server action in Next.js?", tools: { resolveLibraryId: resolveLibraryId(), queryDocs: queryDocs(), }, stopWhen: stepCountIs(5), }); console.log(text); // With explicit API key const tools = { resolveLibraryId: resolveLibraryId({ apiKey: "ctx7sk-your-api-key" }), queryDocs: queryDocs({ apiKey: "ctx7sk-your-api-key" }), }; ``` ### Streaming Responses Use Context7 tools with streaming text generation. ```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-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); } ``` ### Context7 Agent Use the pre-built agent for automatic documentation lookup workflows. ```typescript import { Context7Agent, AGENT_PROMPT } from "@upstash/context7-tools-ai-sdk"; import { anthropic } from "@ai-sdk/anthropic"; import { stepCountIs } from "ai"; // Basic usage 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); // Streaming responses 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 const customAgent = new Context7Agent({ model: anthropic("claude-sonnet-4-20250514"), apiKey: process.env.CONTEXT7_API_KEY, stopWhen: stepCountIs(8), // Allow more steps for complex queries system: `${AGENT_PROMPT} Additional instructions: - Always include TypeScript examples - Mention version compatibility when relevant`, }); ``` ## CLI Commands ### Setup Context7 Configure Context7 for your AI coding agent with OAuth authentication. ```bash # Interactive setup - prompts for mode and target npx ctx7 setup # MCP server mode for specific agents npx ctx7 setup --mcp --claude npx ctx7 setup --mcp --cursor npx ctx7 setup --mcp --opencode # CLI + Skills mode npx ctx7 setup --cli --claude npx ctx7 setup --cli --cursor npx ctx7 setup --cli --universal # Use existing API key npx ctx7 setup --api-key ctx7sk-your-api-key # Project-specific configuration npx ctx7 setup --project --yes ``` ### Search Libraries Search the Context7 index by library name and get library IDs for documentation queries. ```bash # Search for libraries with context query npx ctx7 library react "How to clean up useEffect with async operations" npx ctx7 library nextjs "How to set up app router with middleware" npx ctx7 library prisma "How to define one-to-many relations" # Output as JSON for scripting npx ctx7 library react "How to use hooks" --json | jq '.[0].id' # Example output shows: # Library ID: /facebook/react # Code Snippets: 2500 # Source Reputation: High # Benchmark Score: 95.5 # Versions: /facebook/react/v18.2.0, /facebook/react/v17.0.2 ``` ### Get Documentation Retrieve documentation for a library using its Context7 ID. ```bash # Get documentation with natural language query npx ctx7 docs /facebook/react "How to clean up useEffect with async operations" npx ctx7 docs /vercel/next.js "How to add middleware that redirects unauthenticated users" npx ctx7 docs /prisma/prisma "How to define one-to-many relations with cascade delete" # Get docs for specific version npx ctx7 docs /vercel/next.js/v14.3.0-canary.87 "How to set up app router" # Output as JSON npx ctx7 docs /facebook/react "How to use hooks" --json # Pipe to other tools npx ctx7 docs /vercel/next.js "middleware" | head -50 npx ctx7 docs /vercel/next.js "route protection" | grep -A 10 "middleware" ``` ### Skills Management Install, search, and manage AI coding skills from the Context7 registry. ```bash # Search for skills npx ctx7 skills search pdf npx ctx7 skills search typescript testing # Install skills from repository npx ctx7 skills install /anthropics/skills pdf --claude npx ctx7 skills install /anthropics/skills --all --global # Generate custom skill (requires login) npx ctx7 skills generate --claude # List installed skills npx ctx7 skills list npx ctx7 skills list --global # Remove a skill npx ctx7 skills remove pdf --claude # Suggest skills based on project dependencies npx ctx7 skills suggest ``` ### Authentication Manage authentication and API keys for CLI usage. ```bash # Log in via OAuth npx ctx7 login # Log in without browser (prints URL) npx ctx7 login --no-browser # Check login status npx ctx7 whoami # Log out npx ctx7 logout # Use API key via environment variable export CONTEXT7_API_KEY=ctx7sk-your-api-key npx ctx7 docs /facebook/react "hooks" ``` ## Library Configuration ### context7.json Schema Configure how Context7 parses and presents your library documentation. ```json { "$schema": "https://context7.com/schema/context7.json", "projectTitle": "My Library", "description": "A helpful library for developers", "branch": "main", "folders": ["docs", "guides"], "excludeFolders": [ "node_modules", "./build", "*.test", "docs/**/internal", "**/temp" ], "excludeFiles": [ "CHANGELOG.md", "LICENSE.md", "CODE_OF_CONDUCT.md" ], "rules": [ "Always use TypeScript strict mode", "Prefer async/await over callbacks", "Use the v2 API for new projects" ], "previousVersions": [ { "tag": "v1.2.1" }, { "tag": "v1.0.0" } ], "branchVersions": [ { "branch": "legacy-v1" } ] } ``` ## Summary Context7 enables AI coding assistants and LLM applications to access current, accurate library documentation instead of relying on potentially outdated training data. The primary use cases include building documentation-aware chatbots, code generation pipelines with current API knowledge, code review agents that verify implementations against current documentation, and providing real-time context to any LLM-powered development tool. The platform supports version-specific queries, allowing precise documentation retrieval for any supported library version. Integration patterns range from simple REST API calls for quick lookups to full SDK integration for production applications. The TypeScript SDK provides type-safe access with automatic retries and error handling. The Vercel AI SDK integration offers drop-in tools for `generateText` and `streamText` workflows, plus a pre-built `Context7Agent` for automated documentation lookup. For command-line workflows, the `ctx7` CLI provides direct terminal access to library search and documentation retrieval, with skill management for enhancing AI coding agents. Library owners can claim their projects and configure parsing rules to ensure their documentation is accurately indexed and presented to developers.