Skip to content

Context7 Platform -- Up-to-date docs for AI agents

feat: add API key support for authentication across all transports

enesgulesb8086438a631
diff --git a/README.md b/README.md
index dc0fd7f6..c5844efa 100644
--- a/README.md
+++ b/README.md
@@ -75,7 +75,10 @@ Pasting the following configuration into your Cursor `~/.cursor/mcp.json` file i
{
"mcpServers": {
"context7": {
- "url": "https://mcp.context7.com/mcp"
+ "url": "https://mcp.context7.com/mcp",
+ "headers": {
+ "CONTEXT7_API_KEY": "your_api_key"
+ }
}
}
}
@@ -90,7 +93,7 @@ Pasting the following configuration into your Cursor `~/.cursor/mcp.json` file i
"mcpServers": {
"context7": {
"command": "npx",
- "args": ["-y", "@upstash/context7-mcp"]
+ "args": ["-y", "@upstash/context7-mcp", "--api-key", "your_api_key"]
}
}
}
@@ -106,7 +109,7 @@ Pasting the following configuration into your Cursor `~/.cursor/mcp.json` file i
"mcpServers": {
"context7": {
"command": "bunx",
- "args": ["-y", "@upstash/context7-mcp"]
+ "args": ["-y", "@upstash/context7-mcp", "--api-key", "your_api_key"]
}
}
}
@@ -158,7 +161,7 @@ Add this to your Windsurf MCP config file. See [Windsurf MCP docs](https://docs.
"mcpServers": {
"context7": {
"command": "npx",
- "args": ["-y", "@upstash/context7-mcp"]
+ "args": ["-y", "@upstash/context7-mcp", "--api-key", "your_api_key"]
}
}
}
@@ -195,7 +198,7 @@ Add this to your VS Code MCP config file. See [VS Code MCP docs](https://code.vi
"context7": {
"type": "stdio",
"command": "npx",
- "args": ["-y", "@upstash/context7-mcp"]
+ "args": ["-y", "@upstash/context7-mcp", "--api-key", "your_api_key"]
}
}
}
@@ -232,7 +235,7 @@ Or, for a local server:
"context7": {
"type": "stdio",
"command": "npx",
- "args": ["-y", "@upstash/context7-mcp"]
+ "args": ["-y", "@upstash/context7-mcp", "--api-key", "your_api_key"]
}
}
}
@@ -253,7 +256,7 @@ It can be installed via [Zed Extensions](https://zed.dev/extensions?query=Contex
"Context7": {
"command": {
"path": "npx",
- "args": ["-y", "@upstash/context7-mcp"]
+ "args": ["-y", "@upstash/context7-mcp", "--api-key", "your_api_key"]
},
"settings": {}
}
@@ -294,19 +297,19 @@ Run this command. See [Claude Code MCP docs](https://docs.anthropic.com/en/docs/
#### Claude Code Remote Server Connection
```sh
-claude mcp add --transport http context7 https://mcp.context7.com/mcp
+claude mcp add --transport http context7 https://mcp.context7.com/mcp --header "Context7-API-Key: your-key"
```
Or using SSE transport:
```sh
-claude mcp add --transport sse context7 https://mcp.context7.com/sse
+claude mcp add --transport sse context7 https://mcp.context7.com/sse --header "Context7-API-Key: your-key"
```
#### Claude Code Local Server Connection
```sh
-claude mcp add context7 -- npx -y @upstash/context7-mcp
+claude mcp add context7 -- npx -y @upstash/context7-mcp --api-key your-key
```
</details>
@@ -675,11 +678,12 @@ bun run dist/index.js
- `--transport <stdio|http|sse>` – Transport to use (`stdio` by default).
- `--port <number>` – Port to listen on when using `http` or `sse` transport (default `3000`).
+- `--api-key <key>` – API key for stdio transport if you want to authenticate requests.
Example with http transport and port 8080:
```bash
-bun run dist/index.js --transport http --port 8080
+bun run dist/index.js --transport http --port 8080 --api-key your_api_key
```
<details>
@@ -690,7 +694,7 @@ bun run dist/index.js --transport http --port 8080
"mcpServers": {
"context7": {
"command": "npx",
- "args": ["tsx", "/path/to/folder/context7-mcp/src/index.ts"]
+ "args": ["tsx", "/path/to/folder/context7-mcp/src/index.ts", "--api-key", "your_api_key"]
}
}
}
diff --git a/src/index.ts b/src/index.ts
index 267d9285..4f55cc84 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -17,12 +17,14 @@ const DEFAULT_MINIMUM_TOKENS = 10000;
const program = new Command()
.option("--transport <stdio|http|sse>", "transport type", "stdio")
.option("--port <number>", "port for HTTP/SSE transport", "3000")
+ .option("--api-key <key>", "API key for stdio transport")
.allowUnknownOption() // let MCP Inspector / other wrappers pass through extra flags
.parse(process.argv);
const cliOptions = program.opts<{
transport: string;
port: string;
+ apiKey?: string;
}>();
// Validate transport option
@@ -47,7 +49,7 @@ const CLI_PORT = (() => {
const sseTransports: Record<string, SSEServerTransport> = {};
// Function to create a new server instance with all tools registered
-function createServerInstance() {
+function createServerInstance(apiKey?: string) {
const server = new McpServer(
{
name: "Context7",
@@ -90,7 +92,7 @@ For ambiguous queries, request clarification before proceeding with a best-guess
},
},
async ({ libraryName }) => {
- const searchResponse: SearchResponse = await searchLibraries(libraryName);
+ const searchResponse: SearchResponse = await searchLibraries(libraryName, apiKey);
if (!searchResponse.results || searchResponse.results.length === 0) {
return {
@@ -136,7 +138,8 @@ ${resultsText}`,
"get-library-docs",
{
title: "Get Library Docs Tool",
- description: "Fetches up-to-date documentation for a library. You must call 'resolve-library-id' first to obtain the exact Context7-compatible library ID required to use this tool, UNLESS the user explicitly provides a library ID in the format '/org/project' or '/org/project/version' in their query.",
+ description:
+ "Fetches up-to-date documentation for a library. You must call 'resolve-library-id' first to obtain the exact Context7-compatible library ID required to use this tool, UNLESS the user explicitly provides a library ID in the format '/org/project' or '/org/project/version' in their query.",
inputSchema: {
context7CompatibleLibraryID: z
.string()
@@ -157,10 +160,14 @@ ${resultsText}`,
},
},
async ({ context7CompatibleLibraryID, tokens = DEFAULT_MINIMUM_TOKENS, topic = "" }) => {
- const fetchDocsResponse = await fetchLibraryDocumentation(context7CompatibleLibraryID, {
- tokens,
- topic,
- });
+ const fetchDocsResponse = await fetchLibraryDocumentation(
+ context7CompatibleLibraryID,
+ {
+ tokens,
+ topic,
+ },
+ apiKey
+ );
if (!fetchDocsResponse) {
return {
@@ -201,7 +208,10 @@ async function main() {
// Set CORS headers for all responses
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,DELETE");
- res.setHeader("Access-Control-Allow-Headers", "Content-Type, MCP-Session-Id, mcp-session-id");
+ res.setHeader(
+ "Access-Control-Allow-Headers",
+ "Content-Type, MCP-Session-Id, mcp-session-id, X-Context7-API-Key, context7-api-key, context7_api_key, x-api-key"
+ );
// Handle preflight OPTIONS requests
if (req.method === "OPTIONS") {
@@ -210,9 +220,22 @@ async function main() {
return;
}
+ // Function to extract header value safely, handling both string and string[] cases
+ const extractHeaderValue = (value: string | string[] | undefined): string | undefined => {
+ if (!value) return undefined;
+ return typeof value === "string" ? value : value[0];
+ };
+
+ // Check headers in order of preference
+ const apiKey =
+ extractHeaderValue(req.headers["x-context7-api-key"]) || // Standard with x- prefix
+ extractHeaderValue(req.headers["context7-api-key"]) || // Without x- prefix
+ extractHeaderValue(req.headers["context7_api_key"]) || // With underscores
+ extractHeaderValue(req.headers["x-api-key"]); // Generic API key header
+
try {
// Create new server instance for each request
- const requestServer = createServerInstance();
+ const requestServer = createServerInstance(apiKey);
if (url === "/mcp") {
const transport = new StreamableHTTPServerTransport({
@@ -292,7 +315,7 @@ async function main() {
startServer(initialPort);
} else {
// Stdio transport - this is already stateless by nature
- const server = createServerInstance();
+ const server = createServerInstance(cliOptions.apiKey);
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("Context7 Documentation MCP Server running on stdio");
diff --git a/src/lib/api.ts b/src/lib/api.ts
index 026e1b0e..1b320f65 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -1,18 +1,25 @@
import { SearchResponse } from "./types.js";
-const CONTEXT7_API_BASE_URL = "https://context7.com/api";
+const CONTEXT7_API_BASE_URL = "http://localhost:3000/api";
const DEFAULT_TYPE = "txt";
/**
* Searches for libraries matching the given query
* @param query The search query
+ * @param apiKey Optional API key for authentication
* @returns Search results or null if the request fails
*/
-export async function searchLibraries(query: string): Promise<SearchResponse> {
+export async function searchLibraries(query: string, apiKey?: string): Promise<SearchResponse> {
try {
const url = new URL(`${CONTEXT7_API_BASE_URL}/v1/search`);
url.searchParams.set("query", query);
- const response = await fetch(url);
+
+ const headers: Record<string, string> = {};
+ if (apiKey) {
+ headers["X-Context7-API-Key"] = apiKey;
+ }
+
+ const response = await fetch(url, { headers });
if (!response.ok) {
const errorCode = response.status;
if (errorCode === 429) {
@@ -39,6 +46,7 @@ export async function searchLibraries(query: string): Promise<SearchResponse> {
* Fetches documentation context for a specific library
* @param libraryId The library ID to fetch documentation for
* @param options Options for the request
+ * @param apiKey Optional API key for authentication
* @returns The documentation text or null if the request fails
*/
export async function fetchLibraryDocumentation(
@@ -46,7 +54,8 @@ export async function fetchLibraryDocumentation(
options: {
tokens?: number;
topic?: string;
- } = {}
+ } = {},
+ apiKey?: string
): Promise<string | null> {
try {
if (libraryId.startsWith("/")) {
@@ -56,11 +65,15 @@ export async function fetchLibraryDocumentation(
if (options.tokens) url.searchParams.set("tokens", options.tokens.toString());
if (options.topic) url.searchParams.set("topic", options.topic);
url.searchParams.set("type", DEFAULT_TYPE);
- const response = await fetch(url, {
- headers: {
- "X-Context7-Source": "mcp-server",
- },
- });
+
+ const headers: Record<string, string> = {
+ "X-Context7-Source": "mcp-server",
+ };
+ if (apiKey) {
+ headers["X-Context7-API-Key"] = apiKey;
+ }
+
+ const response = await fetch(url, { headers });
if (!response.ok) {
const errorCode = response.status;
if (errorCode === 429) {