Context7 Platform -- Up-to-date docs for AI agents
CTX7-884: OAuth Support for MCP (#1176)
Fahreddin Özcanef82f3057cbc
diff --git a/.changeset/yellow-chairs-study.md b/.changeset/yellow-chairs-study.mdnew file mode 100644index 00000000..abf60976--- /dev/null+++ b/.changeset/yellow-chairs-study.md@@ -0,0 +1,10 @@+---+"@upstash/context7-mcp": minor+---++Add OAuth 2.0 authentication support for MCP server++- Add new `/mcp/oauth` endpoint requiring JWT authentication+- Implement JWT validation against authorization server JWKS+- Add OAuth Protected Resource Metadata endpoint (RFC 9728) at `/.well-known/oauth-protected-resource`+- Include `WWW-Authenticate` header for OAuth discoverydiff --git a/README.md b/README.mdindex 904a83da..0c58e2af 100644--- a/README.md+++ b/README.md@@ -39,6 +39,9 @@ Context7 fetches up-to-date code examples and documentation right into your LLM'> [!NOTE]> **API Key Recommended**: Get a free API key at [context7.com/dashboard](https://context7.com/dashboard) for higher rate limits.+> [!WARNING]+> **OAuth Support**: Currently, only **Claude Code** and **Cursor** are confirmed to work with OAuth authentication. Use API key authentication for other clients.+<details><summary><b>Install in Cursor</b></summary>diff --git a/docs/docs.json b/docs/docs.jsonindex f7a82457..49ee20fb 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -27,7 +27,10 @@{"group": "How To","pages": [- "howto/api-keys",+ {+ "group": "Authentication",+ "pages": ["howto/api-keys", "howto/oauth"]+ },"howto/claiming-libraries","howto/private-repositories","howto/team",diff --git a/docs/howto/api-keys.mdx b/docs/howto/api-keys.mdxindex e85f6056..0518311e 100644--- a/docs/howto/api-keys.mdx+++ b/docs/howto/api-keys.mdx@@ -1,5 +1,5 @@----title: Manage API Keys+title: API Keysdescription: Create and manage API keys for Context7 authentication---diff --git a/docs/howto/oauth.mdx b/docs/howto/oauth.mdxnew file mode 100644index 00000000..988d4cca--- /dev/null+++ b/docs/howto/oauth.mdx@@ -0,0 +1,43 @@+---+title: OAuth+description: Authenticate with Context7 MCP server using OAuth 2.0+---++<Warning>+ **Currently, only Claude Code and Cursor are confirmed to work with OAuth.** Other clients should use [API key authentication](/howto/api-keys) instead.+</Warning>++<Note>+ OAuth is only available for remote HTTP connections. For local MCP connections using stdio+ transport, use [API key authentication](/howto/api-keys) instead.+</Note>++Context7 MCP server supports OAuth 2.0 authentication for MCP clients that implement the [MCP OAuth specification](https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization).++## Why Use OAuth?++| Feature | OAuth | API Keys |+| -------------------------- | ----- | -------- |+| No manual key management | ✅ | ❌ |+| Automatic token refresh | ✅ | ❌ |+| Works with stdio transport | ❌ | ✅ |++## Configuration++To use OAuth, change the endpoint from `/mcp` to `/mcp/oauth` in your client configuration:++```diff+- "url": "https://mcp.context7.com/mcp"++ "url": "https://mcp.context7.com/mcp/oauth"+```++## How It Works++1. Your MCP client connects to the OAuth endpoint+2. You're redirected to Context7 to sign in+3. After signing in, you're redirected back to your client+4. Your client automatically handles token refresh++## Client Support++OAuth authentication requires your MCP client to support the [MCP OAuth specification](https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization). If your client doesn't support OAuth, use [API key authentication](/howto/api-keys) instead.diff --git a/docs/resources/all-clients.mdx b/docs/resources/all-clients.mdxindex 270fd147..05e49c15 100644--- a/docs/resources/all-clients.mdx+++ b/docs/resources/all-clients.mdx@@ -5,6 +5,10 @@ description: Installation examples for MCP clientsContext7 supports all MCP clients. Below are configuration examples for popular clients. If your client isn't listed, check its documentation for MCP server installation.+<Note>+ **OAuth Support:** Currently, only **Claude Code** and **Cursor** are confirmed to work with [OAuth authentication](/howto/oauth). For other clients, use API key authentication as shown in the examples below.+</Note>+<AccordionGroup><Accordion title="Cursor">diff --git a/packages/mcp/README.md b/packages/mcp/README.mdindex fc27e846..225c6eed 100644--- a/packages/mcp/README.md+++ b/packages/mcp/README.md@@ -1428,6 +1428,19 @@ CONTEXT7_API_KEY=your_api_key_here</details>+### OAuth Authentication++Context7 MCP server supports OAuth 2.0 authentication for MCP clients that implement the [MCP OAuth specification](https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization).++To use OAuth, change the endpoint from `/mcp` to `/mcp/oauth` in your client configuration:++```diff+- "url": "https://mcp.context7.com/mcp"++ "url": "https://mcp.context7.com/mcp/oauth"+```++> **Note:** OAuth is not supported with stdio transport. For local MCP connections, use API key authentication instead.+<details><summary><b>Testing with MCP Inspector</b></summary>diff --git a/packages/mcp/package.json b/packages/mcp/package.jsonindex 8db936be..c5e5e607 100644--- a/packages/mcp/package.json+++ b/packages/mcp/package.json@@ -49,6 +49,7 @@"@types/express": "^5.0.4","commander": "^14.0.0","express": "^5.1.0",+ "jose": "^6.1.3","undici": "^6.6.3","zod": "^3.24.2"},diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.tsindex 671bd33c..b4defaef 100644--- a/packages/mcp/src/index.ts+++ b/packages/mcp/src/index.ts@@ -6,11 +6,12 @@ import { z } from "zod";import { searchLibraries, fetchLibraryContext } from "./lib/api.js";import { ClientContext } from "./lib/encryption.js";import { formatSearchResults, extractClientInfoFromUserAgent } from "./lib/utils.js";+import { isJWT, validateJWT } from "./lib/jwt.js";import express from "express";import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";import { Command } from "commander";import { AsyncLocalStorage } from "async_hooks";-import { SERVER_VERSION } from "./lib/constants.js";+import { SERVER_VERSION, RESOURCE_URL, AUTH_SERVER_URL } from "./lib/constants.js";/** Default HTTP server port */const DEFAULT_PORT = 3000;@@ -316,11 +317,52 @@ async function main() {);};- app.all("/mcp", async (req: express.Request, res: express.Response) => {+ const handleMcpRequest = async (+ req: express.Request,+ res: express.Response,+ requireAuth: boolean+ ) => {try {+ const apiKey = extractApiKey(req);+ const resourceUrl = RESOURCE_URL;+ const baseUrl = new URL(resourceUrl).origin;++ // OAuth discovery info header, used by MCP clients to discover the authorization server+ res.set(+ "WWW-Authenticate",+ `Bearer resource_metadata="${baseUrl}/.well-known/oauth-protected-resource"`+ );++ if (requireAuth) {+ if (!apiKey) {+ return res.status(401).json({+ jsonrpc: "2.0",+ error: {+ code: -32001,+ message: "Authentication required. Please authenticate to use this MCP server.",+ },+ id: null,+ });+ }++ if (isJWT(apiKey)) {+ const validationResult = await validateJWT(apiKey);+ if (!validationResult.valid) {+ return res.status(401).json({+ jsonrpc: "2.0",+ error: {+ code: -32001,+ message: validationResult.error || "Invalid token. Please re-authenticate.",+ },+ id: null,+ });+ }+ }+ }+const context: ClientContext = {clientIp: getClientIp(req),- apiKey: extractApiKey(req),+ apiKey: apiKey,clientInfo: extractClientInfoFromUserAgent(req.headers["user-agent"]),transport: "http",};@@ -348,12 +390,62 @@ async function main() {});}}+ };++ // Anonymous access endpoint - no authentication required+ app.all("/mcp", async (req, res) => {+ await handleMcpRequest(req, res, false);+ });++ // OAuth-protected endpoint - requires authentication+ app.all("/mcp/oauth", async (req, res) => {+ await handleMcpRequest(req, res, true);});app.get("/ping", (_req: express.Request, res: express.Response) => {res.json({ status: "ok", message: "pong" });});+ // OAuth 2.0 Protected Resource Metadata (RFC 9728)+ // Used by MCP clients to discover the authorization server+ app.get(+ "/.well-known/oauth-protected-resource",+ (_req: express.Request, res: express.Response) => {+ res.json({+ resource: RESOURCE_URL,+ authorization_servers: [AUTH_SERVER_URL],+ scopes_supported: ["profile", "email"],+ bearer_methods_supported: ["header"],+ });+ }+ );++ app.get(+ "/.well-known/oauth-authorization-server",+ async (_req: express.Request, res: express.Response) => {+ const authServerUrl = AUTH_SERVER_URL;++ try {+ const response = await fetch(`${authServerUrl}/.well-known/oauth-authorization-server`);+ if (!response.ok) {+ console.error("[OAuth] Upstream error:", response.status);+ return res.status(response.status).json({+ error: "upstream_error",+ message: "Failed to fetch authorization server metadata",+ });+ }+ const metadata = await response.json();+ res.json(metadata);+ } catch (error) {+ console.error("[OAuth] Error fetching OAuth metadata:", error);+ res.status(502).json({+ error: "proxy_error",+ message: "Failed to proxy authorization server metadata",+ });+ }+ }+ );+// Catch-all 404 handler - must be after all other routesapp.use((_req: express.Request, res: express.Response) => {res.status(404).json({diff --git a/packages/mcp/src/lib/api.ts b/packages/mcp/src/lib/api.tsindex 4624f03d..cd5ea684 100644--- a/packages/mcp/src/lib/api.ts+++ b/packages/mcp/src/lib/api.ts@@ -1,8 +1,7 @@import { SearchResponse, ContextRequest, ContextResponse } from "./types.js";import { ClientContext, generateHeaders } from "./encryption.js";import { ProxyAgent, setGlobalDispatcher } from "undici";--const CONTEXT7_API_BASE_URL = "https://context7.com/api";+import { CONTEXT7_API_BASE_URL } from "./constants.js";/*** Parses error response from the Context7 APIdiff --git a/packages/mcp/src/lib/constants.ts b/packages/mcp/src/lib/constants.tsindex f2cecf19..c4154a91 100644--- a/packages/mcp/src/lib/constants.ts+++ b/packages/mcp/src/lib/constants.ts@@ -1,3 +1,16 @@-import pkg from "../../package.json" with { type: "json" };+import { readFileSync } from "fs";+import { fileURLToPath } from "url";+import { dirname, join } from "path";++const __dirname = dirname(fileURLToPath(import.meta.url));+const pkg = JSON.parse(readFileSync(join(__dirname, "../../package.json"), "utf-8"));export const SERVER_VERSION: string = pkg.version;++const CONTEXT7_BASE_URL = "https://context7.com";+const MCP_RESOURCE_URL = "https://mcp.context7.com";++export const CLERK_DOMAIN = "clerk.context7.com";+export const CONTEXT7_API_BASE_URL = process.env.CONTEXT7_API_URL || `${CONTEXT7_BASE_URL}/api`;+export const RESOURCE_URL = process.env.RESOURCE_URL || MCP_RESOURCE_URL;+export const AUTH_SERVER_URL = process.env.AUTH_SERVER_URL || CONTEXT7_BASE_URL;diff --git a/packages/mcp/src/lib/jwt.ts b/packages/mcp/src/lib/jwt.tsnew file mode 100644index 00000000..beacb113--- /dev/null+++ b/packages/mcp/src/lib/jwt.ts@@ -0,0 +1,38 @@+import * as jose from "jose";+import { CLERK_DOMAIN } from "./constants.js";++const JWKS_URL = `https://${CLERK_DOMAIN}/.well-known/jwks.json`;+const ISSUER = `https://${CLERK_DOMAIN}`;++const jwks = jose.createRemoteJWKSet(new URL(JWKS_URL));++export interface JWTValidationResult {+ valid: boolean;+ error?: string;+}++export function isJWT(token: string): boolean {+ const parts = token.split(".");+ return parts.length === 3;+}++export async function validateJWT(token: string): Promise<JWTValidationResult> {+ try {+ await jose.jwtVerify(token, jwks, {+ issuer: ISSUER,+ });++ return { valid: true };+ } catch (error) {+ if (error instanceof jose.errors.JWTExpired) {+ return { valid: false, error: "Token expired" };+ }+ if (error instanceof jose.errors.JWTClaimValidationFailed) {+ return { valid: false, error: "Invalid token claims" };+ }+ if (error instanceof jose.errors.JWSSignatureVerificationFailed) {+ return { valid: false, error: "Invalid signature" };+ }+ return { valid: false, error: "Invalid token" };+ }+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 2ebdbf1d..8890fd1c 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -53,6 +53,9 @@ importers:express:specifier: ^5.1.0version: 5.1.0+ jose:+ specifier: ^6.1.3+ version: 6.1.3undici:specifier: ^6.6.3version: 6.22.0@@ -1484,6 +1487,9 @@ packages:resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==}+ resolution: {integrity: sha512-0TpaTfihd4QMNwrz/ob2Bp7X04yuxJkjRGi4aKmOqwhov54i6u79oCv7T+C7lo70MKH6BesI3vscD1yb/yzKXQ==}+resolution: {integrity: sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==}engines: {node: '>=10'}@@ -3520,6 +3526,8 @@ snapshots:+ [email protected]: {}+