> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/upstash/context7/llms.txt
> Use this file to discover all available pages before exploring further.

# Installation

> Installation instructions for Context7 MCP server, SDK, CLI, and AI SDK tools

Context7 provides multiple packages for different use cases. Choose the installation method that fits your needs.

## MCP Server

The MCP server enables AI coding assistants to access Context7's documentation database.

### Package Information

* **Package**: `@upstash/context7-mcp`
* **Version**: Latest on [npm](https://www.npmjs.com/package/@upstash/context7-mcp)
* **Repository**: [github.com/upstash/context7](https://github.com/upstash/context7)

### Installation Options

<Tabs>
  <Tab title="Remote Server (Recommended)">
    Connect to Context7's hosted MCP server - no installation required.

    <CodeGroup>
      ```json Cursor theme={null}
      {
        "mcpServers": {
          "context7": {
            "url": "https://mcp.context7.com/mcp",
            "headers": {
              "CONTEXT7_API_KEY": "YOUR_API_KEY"
            }
          }
        }
      }
      ```

      ```bash Claude Code theme={null}
      claude mcp add --scope user \
        --header "CONTEXT7_API_KEY: YOUR_API_KEY" \
        --transport http context7 \
        https://mcp.context7.com/mcp
      ```

      ```json OpenCode theme={null}
      "mcp": {
        "context7": {
          "type": "remote",
          "url": "https://mcp.context7.com/mcp",
          "headers": {
            "CONTEXT7_API_KEY": "YOUR_API_KEY"
          },
          "enabled": true
        }
      }
      ```
    </CodeGroup>

    <Tip>
      Remote servers are faster, more reliable, and don't require Node.js installation.
    </Tip>
  </Tab>

  <Tab title="Local Server">
    Run the MCP server locally using npx:

    <CodeGroup>
      ```json Cursor theme={null}
      {
        "mcpServers": {
          "context7": {
            "command": "npx",
            "args": ["-y", "@upstash/context7-mcp", "--api-key", "YOUR_API_KEY"]
          }
        }
      }
      ```

      ```bash Claude Code theme={null}
      claude mcp add --scope user context7 -- \
        npx -y @upstash/context7-mcp --api-key YOUR_API_KEY
      ```

      ```json OpenCode theme={null}
      {
        "mcp": {
          "context7": {
            "type": "local",
            "command": ["npx", "-y", "@upstash/context7-mcp", "--api-key", "YOUR_API_KEY"],
            "enabled": true
          }
        }
      }
      ```
    </CodeGroup>

    <Note>
      Requires Node.js 18 or higher. The `-y` flag automatically installs the latest version.
    </Note>
  </Tab>

  <Tab title="OAuth Authentication">
    Use OAuth for authentication instead of API keys:

    ```json theme={null}
    {
      "mcpServers": {
        "context7": {
          "url": "https://mcp.context7.com/mcp/oauth"
        }
      }
    }
    ```

    <Warning>
      OAuth is only available for remote HTTP connections. Your MCP client must support the [MCP OAuth specification](https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization).
    </Warning>
  </Tab>
</Tabs>

### Running as HTTP Server

You can also run the MCP server as a standalone HTTP server:

```bash theme={null}
npx @upstash/context7-mcp --transport http --port 3000
```

The server will start at `http://localhost:3000/mcp`.

**Available endpoints**:

* `/mcp` - MCP protocol endpoint (anonymous access)
* `/mcp/oauth` - OAuth-protected endpoint
* `/ping` - Health check
* `/.well-known/oauth-protected-resource` - OAuth metadata

## SDK

The TypeScript/JavaScript SDK provides programmatic access to Context7's API.

### Installation

<CodeGroup>
  ```bash npm theme={null}
  npm install @upstash/context7-sdk
  ```

  ```bash yarn theme={null}
  yarn add @upstash/context7-sdk
  ```

  ```bash pnpm theme={null}
  pnpm add @upstash/context7-sdk
  ```
</CodeGroup>

### Usage

```typescript theme={null}
import { Context7 } from '@upstash/context7-sdk';

// Initialize with API key
const ctx7 = new Context7({
  apiKey: 'ctx7sk_...' // or set CONTEXT7_API_KEY env var
});

// Search for libraries
const libraries = await ctx7.searchLibrary(
  'How to set up authentication?',
  'next.js',
  { type: 'json' }
);

console.log(libraries);
// [
//   {
//     id: '/vercel/next.js',
//     name: 'Next.js',
//     description: 'The React Framework for the Web',
//     codeSnippets: 1250,
//     reputation: 'High',
//     benchmarkScore: 98,
//     versions: ['15.1.5', '14.2.0', ...]
//   }
// ]

// Get documentation for a library
const docs = await ctx7.getContext(
  'How to create middleware?',
  '/vercel/next.js',
  { type: 'json' }
);

console.log(docs);
// [
//   {
//     type: 'code',
//     content: 'export function middleware(request) {...}',
//     title: 'Basic Middleware',
//     url: 'https://nextjs.org/docs/middleware'
//   },
//   ...
// ]
```

### API Methods

#### searchLibrary

Search for libraries matching a query.

```typescript theme={null}
await ctx7.searchLibrary(
  query: string,        // User's question/task
  libraryName: string,  // Library name to search
  options?: {
    type: 'json' | 'txt'  // Response format (default: 'json')
  }
): Promise<Library[] | string>
```

#### getContext

Get documentation for a specific library.

```typescript theme={null}
await ctx7.getContext(
  query: string,      // User's question/task
  libraryId: string,  // Context7 library ID (e.g., '/vercel/next.js')
  options?: {
    type: 'json' | 'txt'  // Response format (default: 'json')
  }
): Promise<Documentation[] | string>
```

### Error Handling

```typescript theme={null}
import { Context7, Context7Error } from '@upstash/context7-sdk';

try {
  const ctx7 = new Context7({ apiKey: 'invalid' });
  await ctx7.searchLibrary('query', 'library');
} catch (error) {
  if (error instanceof Context7Error) {
    console.error('Context7 error:', error.message);
  }
}
```

## CLI

The `ctx7` CLI provides tools for authentication and quick MCP setup.

### Installation

<CodeGroup>
  ```bash npx (Recommended) theme={null}
  npx ctx7 --help
  ```

  ```bash Global Install theme={null}
  npm install -g ctx7
  ctx7 --help
  ```
</CodeGroup>

### Commands

#### setup

Configure Context7 MCP for your AI coding agents:

```bash theme={null}
# Interactive setup
npx ctx7 setup

# Setup for specific agent
npx ctx7 setup --cursor
npx ctx7 setup --claude
npx ctx7 setup --opencode

# Project-specific setup
npx ctx7 setup --project

# Use existing API key
npx ctx7 setup --api-key ctx7sk_...

# Use OAuth endpoint
npx ctx7 setup --oauth
```

This command:

* Authenticates via OAuth (or uses provided API key)
* Generates API key automatically if using OAuth
* Configures MCP server in your agent's config file
* Adds a rule to auto-invoke Context7
* Installs Context7 skill

#### auth

Manage authentication:

```bash theme={null}
# Log in with OAuth
npx ctx7 auth login

# Log out
npx ctx7 auth logout

# Check login status
npx ctx7 auth status
```

#### skills

Manage Context7 skills:

```bash theme={null}
# Search for skills
npx ctx7 skills search pdf

# Install skills
npx ctx7 skills install /anthropics/skills

# List installed skills
npx ctx7 skills list

# Remove skills
npx ctx7 skills remove skillname
```

## AI SDK Tools

Pre-built tools for [Vercel AI SDK](https://sdk.vercel.ai/) that provide Context7 functionality.

### Installation

<CodeGroup>
  ```bash npm theme={null}
  npm install @upstash/context7-tools-ai-sdk @upstash/context7-sdk ai zod
  ```

  ```bash yarn theme={null}
  yarn add @upstash/context7-tools-ai-sdk @upstash/context7-sdk ai zod
  ```

  ```bash pnpm theme={null}
  pnpm add @upstash/context7-tools-ai-sdk @upstash/context7-sdk ai zod
  ```
</CodeGroup>

<Note>
  Requires peer dependencies: `@upstash/context7-sdk`, `ai` (v6.0.0+), and `zod` (v4.0.0+)
</Note>

### Usage

```typescript theme={null}
import { resolveLibraryId, queryDocs } from '@upstash/context7-tools-ai-sdk';
import { generateText } from 'ai';
import { openai } from '@ai-sdk/openai';

const { text } = await generateText({
  model: openai('gpt-4o'),
  prompt: 'How do I create middleware in Next.js?',
  tools: {
    resolveLibraryId: resolveLibraryId({ apiKey: 'ctx7sk_...' }),
    queryDocs: queryDocs({ apiKey: 'ctx7sk_...' })
  },
  maxSteps: 5
});

console.log(text);
```

### Available Tools

#### resolveLibraryId

Resolves a library name to a Context7-compatible library ID.

```typescript theme={null}
import { resolveLibraryId } from '@upstash/context7-tools-ai-sdk';

const tool = resolveLibraryId({
  apiKey: 'ctx7sk_...' // optional, uses CONTEXT7_API_KEY env var if not provided
});
```

#### queryDocs

Fetches documentation for a library using its Context7 library ID.

```typescript theme={null}
import { queryDocs } from '@upstash/context7-tools-ai-sdk';

const tool = queryDocs({
  apiKey: 'ctx7sk_...' // optional, uses CONTEXT7_API_KEY env var if not provided
});
```

### Context7 Agent

A pre-configured agent that combines both tools:

```typescript theme={null}
import { Context7Agent } from '@upstash/context7-tools-ai-sdk';
import { openai } from '@ai-sdk/openai';

const agent = new Context7Agent({
  model: openai('gpt-4o'),
  apiKey: 'ctx7sk_...',
  maxSteps: 5
});

const result = await agent.run(
  'Show me how to implement caching in Redis with Node.js'
);

console.log(result.text);
```

### System Prompts

The package exports system prompts that you can use in your own agents:

```typescript theme={null}
import {
  SYSTEM_PROMPT,
  AGENT_PROMPT,
  RESOLVE_LIBRARY_ID_DESCRIPTION,
  QUERY_DOCS_DESCRIPTION
} from '@upstash/context7-tools-ai-sdk';
```

## Getting an API Key

<Steps>
  <Step title="Visit the dashboard">
    Go to [context7.com/dashboard](https://context7.com/dashboard)
  </Step>

  <Step title="Sign in">
    Authenticate with your GitHub, Google, or email account
  </Step>

  <Step title="Generate API key">
    Click "Create API Key" and give it a name
  </Step>

  <Step title="Copy the key">
    Copy your API key (starts with `ctx7sk_`) and store it securely
  </Step>
</Steps>

<Warning>
  API keys provide higher rate limits than anonymous access. Keep your API key secure and never commit it to version control.
</Warning>

## Environment Variables

All packages support the `CONTEXT7_API_KEY` environment variable:

```bash theme={null}
export CONTEXT7_API_KEY=ctx7sk_...
```

Or add to your `.env` file:

```bash theme={null}
CONTEXT7_API_KEY=ctx7sk_...
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Quickstart Guide" icon="rocket" href="/quickstart">
    Get Context7 running in under 5 minutes
  </Card>

  <Card title="API Reference" icon="book" href="https://context7.com/docs/api-guide">
    Explore the REST API documentation
  </Card>

  <Card title="Adding Libraries" icon="plus" href="/guides/adding-libraries">
    Submit your library to Context7
  </Card>

  <Card title="Troubleshooting" icon="wrench" href="/guides/troubleshooting">
    Common issues and solutions
  </Card>
</CardGroup>
