Context7 Platform -- Up-to-date docs for AI agents
CTX7-2857: Require authentication on the hosted MCP endpoint (#3223)
Fahreddin Özcan48eb9f0c8fd1
diff --git a/.changeset/tough-ants-authenticate.md b/.changeset/tough-ants-authenticate.mdnew file mode 100644index 00000000..142df532--- /dev/null+++ b/.changeset/tough-ants-authenticate.md@@ -0,0 +1,5 @@+---+"@upstash/context7-mcp": minor+---++Require credentials on the HTTP `/mcp` endpoint by default. Set `MCP_AUTH_ENFORCEMENT=observe` to keep anonymous `/mcp` access and record privacy-safe authentication migration events; `/mcp/oauth` and Claude Code plugin requests keep their challenge in both modes. `/mcp/oauth` stays as a compatibility alias, each endpoint publishes its own OAuth protected-resource metadata, an empty or scheme-only `Authorization: Bearer` header counts as a missing credential, and CORS responses expose `WWW-Authenticate` and `MCP-Session-Id`.diff --git a/.env.example b/.env.exampleindex 664c7c00..001dad6d 100644--- a/.env.example+++ b/.env.example@@ -16,6 +16,9 @@ VERCEL_MARKETPLACE_OIDC_AUDIENCE=# Required for hosted HTTP deployments. Must match context7.com.MCP_CLIENT_IP_ASSERTION_KEY=+# Defaults to required. Set observe to accept requests without credentials on+# /mcp and record them, for example during a migration.+MCP_AUTH_ENFORCEMENT=# Network / certificatesHTTPS_PROXY=diff --git a/docs/clients/cursor.mdx b/docs/clients/cursor.mdxindex fd0de0ef..03398ec1 100644--- a/docs/clients/cursor.mdx+++ b/docs/clients/cursor.mdx@@ -84,7 +84,7 @@ use context7 with /vercel/next.js for app router setup## Cursor Cloud Agents-Cursor Cloud Agents use MCP servers configured for the cloud agent, not the MCP configuration from your local Cursor installation. If Context7 works in the IDE but a Cloud Agent reports an anonymous quota, add an authenticated HTTP server in the Cloud Agent UI.+Cursor Cloud Agents use MCP servers configured for the cloud agent, not the MCP configuration from your local Cursor installation. If Context7 works in the IDE but not in a Cloud Agent, add an authenticated HTTP server in the Cloud Agent UI.<Note>The MCP connection is independent of the model selected for the agent. You can@@ -188,9 +188,9 @@ To verify authentication conclusively, query a private library that belongs to tUse Context7 to query <YOUR_PRIVATE_LIBRARY_ID>. Summarize its installation docs.```-If the private library can be read, the Cloud Agent is using the API key. If the agent reports **Monthly quota exceeded** even though the key has quota, the request is reaching Context7 anonymously; recheck the header name and start a new run after saving the MCP server.+If the private library can be read, the Cloud Agent is using the API key. If the private library cannot be read, Context7 did not receive the key; recheck the header name and start a new run after saving the MCP server.-After the API-key header is applied, the same Cloud Agent should be able to resolve a library and return documentation without the anonymous quota error:+After the API-key header is applied, the same Cloud Agent should be able to resolve a library and return documentation:<Frame><img src="/images/clients/cursor/cloud-agents/06-verify-context7.png" alt="Successful Context7 documentation query from a Cursor Cloud Agent" />@@ -210,8 +210,8 @@ See Cursor's documentation for [custom MCP servers](https://cursor.com/docs/clou### Troubleshooting<AccordionGroup>-<Accordion title="Monthly quota exceeded">-The request is usually anonymous. Confirm that the custom server URL is `https://mcp.context7.com/mcp`, the header is named `Context7-API-Key`, and the saved value is the current API key. Then enable the server and start a new Cloud Agent run.+<Accordion title="The API key is not applied">+Confirm that the custom server URL is `https://mcp.context7.com/mcp`, the header is named `Context7-API-Key`, and the saved value is the current API key. Then enable the server and start a new Cloud Agent run. The server can report a ready status without the key, so use the private-library check above to verify.</Accordion><Accordion title="The server is ready, but private docs are unavailable">diff --git a/docs/clients/pi.mdx b/docs/clients/pi.mdxindex 788024f6..be4b6ea6 100644--- a/docs/clients/pi.mdx+++ b/docs/clients/pi.mdx@@ -22,7 +22,7 @@ Choose one of the following connection methods. These commands save the server iAdd the remote server and sign in:```bash-pi mcp add context7 --url https://mcp.context7.com/mcp/oauth --exposure direct+pi mcp add context7 --url https://mcp.context7.com/mcp --exposure directpi mcp login context7```@@ -40,8 +40,6 @@ pi mcp add context7 --url https://mcp.context7.com/mcp \Add the export to your shell profile to make the key available in future sessions. Pi saves an environment variable reference in its configuration.-To try Context7 without an API key at the anonymous rate limit, omit `--bearer-token-env-var CONTEXT7_API_KEY`.-### Local serverTo run the Context7 MCP server locally over stdio, use this option. It requires Node.js and `npx`:diff --git a/docs/integrations/eve.mdx b/docs/integrations/eve.mdxindex c57e2711..5c49ac8a 100644--- a/docs/integrations/eve.mdx+++ b/docs/integrations/eve.mdx@@ -36,7 +36,7 @@ For more details on how eve handles MCP connections, see the [eve MCP connection});```- The API key is optional, so the connection can use Context7's anonymous limits when `CONTEXT7_API_KEY` is not set. For higher rate limits, create an API key in the [Context7 dashboard](https://context7.com/dashboard).+ Set `CONTEXT7_API_KEY` so the hosted Context7 MCP server can identify you and apply your plan's limits. Create a free key in the [Context7 dashboard](https://context7.com/dashboard) and set it as described in the next step.</Step><Step title="Configure an API key (recommended)">diff --git a/docs/resources/all-clients.mdx b/docs/resources/all-clients.mdxindex 0f8d83bb..0e889b2e 100644--- a/docs/resources/all-clients.mdx+++ b/docs/resources/all-clients.mdx@@ -138,7 +138,7 @@ Pi has built-in MCP support from version 0.99.0. Run `pi update` to update Pi, t##### OAuth```sh-pi mcp add context7 --url https://mcp.context7.com/mcp/oauth --exposure direct+pi mcp add context7 --url https://mcp.context7.com/mcp --exposure directpi mcp login context7```@@ -154,8 +154,6 @@ pi mcp add context7 --url https://mcp.context7.com/mcp \--bearer-token-env-var CONTEXT7_API_KEY --exposure direct```-For anonymous access at a lower rate limit, omit `--bearer-token-env-var CONTEXT7_API_KEY`.-##### Local server connectionWith Node.js and `npx` installed, run:@@ -202,20 +200,15 @@ openclaw mcp login context7OpenClaw also provides a code-based login fallback for headless or remote environments. See [Set Up OAuth](/howto/oauth) for more details.-#### API Key or Anonymous Access+#### API Key-To connect without OAuth, register the standard endpoint:+To connect with an API key, register the standard endpoint:```shopenclaw mcp add context7 \--url https://mcp.context7.com/mcp \- --transport streamable-http-```--This works without an API key at the anonymous rate limit. For higher limits, create a key in the [Context7 dashboard](https://context7.com/dashboard) and append this option to the command:--```sh---header "Authorization: Bearer YOUR_API_KEY"+ --transport streamable-http \+ --header "Authorization: Bearer YOUR_API_KEY"```Verify that OpenClaw can connect and discover the Context7 tools:@@ -926,10 +919,10 @@ See [Warp Model Context Protocol Documentation](https://docs.warp.dev/knowledge-Run this command in your terminal. See [Amp MCP docs](https://ampcode.com/manual#mcp) for more info.-#### Without API Key (Basic Usage)+#### With OAuth```sh-amp mcp add context7 https://mcp.context7.com/mcp+amp mcp add context7 https://mcp.context7.com/mcp/oauth```#### With API Key (Higher Rate Limits & Private Repos)@@ -1102,7 +1095,7 @@ docker build -t context7-mcp .Context7 is available in the [Docker MCP Catalog](https://hub.docker.com/mcp/server/context7/overview) as a **remote** server, so you don't need to build, pull, or run a local image. The MCP Toolkit connects to the hosted endpoint for you.1. In Docker Desktop, open **MCP Toolkit → Catalog**, search for **Context7**, and enable it.-2. (Optional) In the server's **Config** tab, set your Context7 API key (`CONTEXT7_API_KEY`) for higher rate limits. The server also works without one.+2. In the server's **Config** tab, set your free Context7 API key (`CONTEXT7_API_KEY`).3. Connect your MCP client to Docker's MCP gateway. Either run `docker mcp client connect <client>` (for example `vscode`, `cursor`, or `claude-desktop`), or add the gateway to your client config manually:```json@@ -1426,7 +1419,7 @@ droid mcp add context7 "npx -y @upstash/context7-mcp" --env CONTEXT7_API_KEY=YOU[Emdash](https://github.com/generalaction/emdash) is an orchestration layer for running multiple coding agents in parallel.-Context7 is available as a built-in entry in Emdash's MCP catalog. Enable it from the MCP view and provide your `CONTEXT7_API_KEY` (optional, for higher rate limits). Emdash adapts and writes the MCP config into your selected coding agent's config (Codex, Claude Code, Cursor, etc.) for you.+Context7 is available as a built-in entry in Emdash's MCP catalog. Enable it from the MCP view and authenticate with OAuth, or provide your `CONTEXT7_API_KEY` when the selected agent does not support OAuth. Emdash adapts and writes the MCP config into your selected coding agent's config (Codex, Claude Code, Cursor, etc.) for you.See the [Emdash repository](https://github.com/generalaction/emdash) for more information.@@ -1434,7 +1427,7 @@ See the [Emdash repository](https://github.com/generalaction/emdash) for more in<Accordion title="Desktop Extension">-Install the [context7.mcpb](https://github.com/upstash/context7/tree/master/packages/mcp/mcpb/context7.mcpb) file and add it to your client. See [MCP bundles docs](https://github.com/modelcontextprotocol/mcpb#mcp-bundles-mcpb) for more info.+Install the [context7.mcpb](https://github.com/upstash/context7/releases/download/mcpb-v4.1.1/context7.mcpb) file and add it to your client. See [MCP bundles docs](https://github.com/modelcontextprotocol/mcpb#mcp-bundles-mcpb) for more info.</Accordion>diff --git a/docs/resources/developer.mdx b/docs/resources/developer.mdxindex 030c784a..d1e449f3 100644--- a/docs/resources/developer.mdx+++ b/docs/resources/developer.mdx@@ -49,6 +49,8 @@ HTTP transport on port 8080:node packages/mcp/dist/index.js --transport http --port 8080```+HTTP transport requires a credential on every request by default. Clients send `Authorization: Bearer YOUR_API_KEY`. Set `MCP_AUTH_ENFORCEMENT=observe` to also accept requests without credentials on `/mcp`.+Stdio transport with API key:```bashdiff --git a/packages/mcp/README.md b/packages/mcp/README.mdindex 4be1e7e4..335e5c1b 100644--- a/packages/mcp/README.md+++ b/packages/mcp/README.md@@ -157,10 +157,10 @@ claude mcp add --scope user --header "Authorization: Bearer YOUR_API_KEY" --tranRun this command in your terminal. See [Amp MCP docs](https://ampcode.com/manual#mcp) for more info.-#### Without API Key (Basic Usage)+#### With OAuth```sh-amp mcp add context7 https://mcp.context7.com/mcp+amp mcp add context7 https://mcp.context7.com/mcp/oauth```#### With API Key (Higher Rate Limits & Private Repos)@@ -1331,12 +1331,6 @@ Run this command in your terminal:droid mcp add context7 https://mcp.context7.com/mcp --type http --header "Authorization: Bearer YOUR_API_KEY"```-Or without an API key (basic usage with rate limits):--```sh-droid mcp add context7 https://mcp.context7.com/mcp --type http-```-#### Factory Local Server Connection (Stdio)Run this command in your terminal:@@ -1378,12 +1372,6 @@ autohand mcp add context7 npx -y @upstash/context7-mcp --api-key YOUR_API_KEYAdd `--scope project` before `context7` to save the server in the current project's `.autohand` configuration instead of your user configuration.-For basic usage without an API key, you can connect to the remote server instead:--```sh-autohand mcp add --transport http context7 https://mcp.context7.com/mcp-```-</details>## 🔨 Available Tools@@ -1454,6 +1442,8 @@ Example with HTTP transport and port 8080:bun run dist/index.js --transport http --port 8080```+HTTP transport requires a credential on every request by default. Clients send `Authorization: Bearer YOUR_API_KEY`. Set `MCP_AUTH_ENFORCEMENT=observe` to also accept requests without credentials on `/mcp`.+Another example with stdio transport:```bash@@ -1547,6 +1537,9 @@ Prometheus receives these metric families:- `context7_mcp_subscriptions_active` and `context7_mcp_subscription_duration`- `context7_mcp_upstream_requests_total` and `context7_mcp_upstream_request_duration`- `context7_mcp_authentication_attempts_total` and `context7_mcp_authentication_duration`+- `context7_mcp_authentication_events_total` for bounded authentication lifecycle events such as+ credential challenges, metadata discovery, credentialed initialization, and authenticated tool+ use- `context7_mcp_upstream_requests_active` and `context7_mcp_authentication_active`- `nodejs_eventloop_*`, `v8js_gc_duration`, `v8js_memory_heap_*`, and`v8js_resource_active` from the official OpenTelemetry Node runtime instrumentation@@ -1557,12 +1550,18 @@ the separate subscription metrics track the active stream and its bounded terminUpstream outcomes distinguishHTTP, response-decoding, network, timeout, and cancellation failures and include both the boundedstatus-code class and the exact numeric HTTP status. Authentication reports accepted, missing,-invalid, and unexpected-error outcomes. The OAuth authorization-server metadata proxy caps its-upstream fetch at 10 seconds and returns `502` if that dependency times out.+invalid, and unexpected-error outcomes. Authentication event series use only the bounded route,+enforcement mode, event, method, and outcome dimensions. The OAuth authorization-server metadata+proxy caps its upstream fetch at 10 seconds and returns `502` if that dependency times out.The labels intentionally exclude API keys, client IPs, queries, library IDs, session IDs, and rawerror text. Expose port `9464` only to your Prometheus scraper or `ServiceMonitor`, not through the-public MCP ingress.+public MCP ingress. For continuity with existing MCP series, the route label uses `anonymous` for+the standard `/mcp` path and `oauth` for the `/mcp/oauth` compatibility alias; the `anonymous` value+identifies the route and does not imply that the request bypassed authentication. The enforcement+label reports the mode applied to each request: `/mcp/oauth` and Claude Code plugin requests report+`required` while the server runs in `observe` mode, because those clients always receive the+challenge.#### Signal ownership with an Envoy gatewaydiff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.tsindex 8ece8ee3..ef1b0161 100644--- a/packages/mcp/src/index.ts+++ b/packages/mcp/src/index.ts@@ -16,7 +16,6 @@ import {extractClientInfoFromUserAgent,envelopeClientInfo,} from "./lib/utils.js";-import { isJWT, validateJWT } from "./lib/jwt.js";import express from "express";import { Command } from "commander";import { AsyncLocalStorage } from "async_hooks";@@ -25,7 +24,6 @@ import {SERVER_VERSION,RESOURCE_URL,OAUTH_AUTH_SERVER_URL,- EMA_ISSUER,OPENAI_APPS_CHALLENGE_TOKEN,mcpServerCard,} from "./lib/constants.js";@@ -37,9 +35,23 @@ import {initializeTelemetry,observeAuthentication,observeUpstreamRequest,- recordToolCallOutcome,+ recordAuthenticationEvent,} from "./lib/telemetry-runtime.js";import { mcpBodyErrorHandler } from "./lib/mcp-body-error-handler.js";+import {+ observeCredentialedInitialize,+ recordToolCallTelemetry,+} from "./lib/auth-lifecycle-telemetry.js";+import {+ canonicalMcpEndpoint,+ effectiveMcpAuthMode,+ evaluateMcpAuthentication,+ parseMcpAuthMode,+ protectedResourceMetadata,+ protectedResourceUrl,+ setBearerChallenge,+} from "./lib/mcp-http-auth.js";+import { mcpRouteFromUrl } from "./lib/mcp-route.js";/** Default HTTP server port */const DEFAULT_PORT = 3000;@@ -52,16 +64,6 @@ function getPluginFromRequest(req: express.Request): typeof CLAUDE_CODE_PLUGIN |return req.query.client === CLAUDE_CODE_PLUGIN ? CLAUDE_CODE_PLUGIN : undefined;}-function requiresAuthentication(req: express.Request, plugin?: typeof CLAUDE_CODE_PLUGIN): boolean {- // The MCP routes live on a router mounted at /mcp, so req.path is relative to it.- const isOAuthEndpoint = `${req.baseUrl}${req.path}` === "/mcp/oauth";- // The current official Claude plugin expands an unset API key to an empty header.- const hasEmptyPluginAuthorization =- plugin === CLAUDE_CODE_PLUGIN && req.headers.authorization === "";-- return isOAuthEndpoint || (Boolean(plugin) && !hasEmptyPluginAuthorization);-}-// Parse CLI arguments using commanderconst program = new Command().version(SERVER_VERSION, "-v, --version", "output the current version")@@ -113,8 +115,6 @@ const CLI_PORT = (() => {const requestContext = new AsyncLocalStorage<ClientContext>();-type AuthenticationResult = { accepted: true } | { accepted: false; error: string };-// Global state for stdio mode onlylet stdioApiKey: string | undefined;let stdioClientInfo: { ide?: string; version?: string } | undefined;@@ -279,7 +279,7 @@ IMPORTANT: Do not call this tool more than 3 times per question. If you cannot fif (!searchResponse.results || searchResponse.results.length === 0) {const text = searchResponse.error ?? "No libraries found matching the provided name.";maybeElicitAuthSignIn(server, ctx);- recordToolCallOutcome(searchResponse.error ? "error" : "not_found");+ recordToolCallTelemetry(ctx, searchResponse.error ? "error" : "not_found");return {content: [{@@ -293,7 +293,7 @@ IMPORTANT: Do not call this tool more than 3 times per question. If you cannot fconst resultsText = formatSearchResults(searchResponse);const responseText = `Available Libraries:\n\n${resultsText}`;maybeElicitAuthSignIn(server, ctx);- recordToolCallOutcome("success");+ recordToolCallTelemetry(ctx, "success");return {content: [{@@ -340,7 +340,7 @@ Do not call this tool more than 3 times per question.`,const ctx = getClientContext(toolCtx);const response = await fetchLibraryContext({ query, libraryId }, ctx);maybeElicitAuthSignIn(server, ctx);- recordToolCallOutcome(response.outcome);+ recordToolCallTelemetry(ctx, response.outcome);return {content: [{@@ -383,6 +383,10 @@ async function main() {"Access-Control-Allow-Headers","Content-Type, MCP-Session-Id, MCP-Protocol-Version, Mcp-Method, Mcp-Name, X-Context7-API-Key, Context7-API-Key, X-API-Key, Authorization, If-None-Match");+ // Browser clients can only read these response headers cross-origin when+ // they are exposed; without WWW-Authenticate they cannot start OAuth+ // from the 401 challenge.+ res.setHeader("Access-Control-Expose-Headers", "WWW-Authenticate, MCP-Session-Id");if (req.method === "OPTIONS") {res.sendStatus(200);return;@@ -399,9 +403,9 @@ async function main() {const header = extractHeaderValue(authHeader);if (!header) return undefined;- if (header.startsWith("Bearer ")) {- return header.substring(7).trim();- }+ // Node trims header values, so "Bearer " with an unset key arrives as "Bearer".+ const bearer = /^Bearer(?:\s+(.*))?$/i.exec(header);+ if (bearer) return bearer[1]?.trim() || undefined;return header;};@@ -442,68 +446,54 @@ async function main() {const nodeHandler = toNodeHandler(mcpHandler, {onerror: (error) => console.error("MCP node adapter error:", error),});+ const authMode = parseMcpAuthMode();const handleMcpRequest = async (req: express.Request, res: express.Response) => {try {const plugin = getPluginFromRequest(req);const apiKey = extractApiKey(req);- const baseUrl = new URL(RESOURCE_URL).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"`+ const endpoint = canonicalMcpEndpoint(req);+ const route = mcpRouteFromUrl(endpoint);+ const enforcementMode = effectiveMcpAuthMode(+ authMode,+ endpoint,+ plugin,+ req.headers.authorization+ );+ const authentication = await observeAuthentication({ enforcementMode, route }, () =>+ evaluateMcpAuthentication(apiKey, enforcementMode));- if (requiresAuthentication(req, plugin)) {- const authentication = await observeAuthentication<AuthenticationResult>(async () => {- if (!apiKey) {- return {- outcome: "missing",- value: {- accepted: false,- error: "Authentication required. Please authenticate to use this MCP server.",- },- };- }-- if (isJWT(apiKey)) {- const validationResult = await validateJWT(apiKey);- if (!validationResult.valid) {- return {- outcome: "invalid",- value: {- accepted: false,- error: validationResult.error || "Invalid token. Please re-authenticate.",- },- };- }- }-- return { outcome: "accepted", value: { accepted: true } };+ if (!authentication.allowed) {+ setBearerChallenge(res, endpoint, apiKey ? authentication.error : undefined);+ res.status(401).json({+ jsonrpc: "2.0",+ error: {+ code: -32001,+ message: authentication.error,+ },+ id: null,});-- if (!authentication.accepted) {- res.status(401).json({- jsonrpc: "2.0",- error: {- code: -32001,- message: authentication.error,- },- id: null,- });- return;- }+ return;}const context: ClientContext = {clientIp: req.ip,apiKey,clientInfo: extractClientInfoFromUserAgent(req.headers["user-agent"]),+ mcpAuthMode: enforcementMode,+ mcpEndpoint: endpoint,plugin,transport: "http",};+ observeCredentialedInitialize(res, req.body, {+ enforcementMode,+ method: authentication.method,+ outcome: authentication.outcome,+ route,+ });+await requestContext.run(context, async () => {await nodeHandler(req, res, req.body);});@@ -526,7 +516,7 @@ async function main() {mcpRouter.use(express.json());mcpRouter.use(mcpBodyErrorHandler);mcpRouter.all("/", (req, res) => handleMcpRequest(req, res));- // OAuth-protected endpoint - requires authentication+ // Compatibility alias for clients already configured with /mcp/oauth.mcpRouter.all("/oauth", (req, res) => handleMcpRequest(req, res));// SEP-2127 reserves `{streamable-http-url}/server-card`. Register it@@ -549,18 +539,32 @@ async function main() {app.get("/.well-known/oauth-protected-resource",(_req: express.Request, res: express.Response) => {- res.json({- resource: RESOURCE_URL,- // Each entry is an independent authorization server. Clerk handles- // regular authorization-code flows; Context7 handles only the- // enterprise-managed id-jag exchange.- authorization_servers: Array.from(new Set([OAUTH_AUTH_SERVER_URL, EMA_ISSUER])),- scopes_supported: ["profile", "email"],- bearer_methods_supported: ["header"],+ recordAuthenticationEvent({+ enforcementMode: authMode,+ event: "metadata_requested",+ method: "none",+ route: mcpRouteFromUrl(RESOURCE_URL),});+ res.json(protectedResourceMetadata(RESOURCE_URL));});+ for (const endpoint of ["/mcp", "/mcp/oauth"] as const) {+ app.get(+ `/.well-known/oauth-protected-resource${endpoint}`,+ (_req: express.Request, res: express.Response) => {+ const resource = protectedResourceUrl(endpoint);+ recordAuthenticationEvent({+ enforcementMode: authMode,+ event: "metadata_requested",+ method: "none",+ route: mcpRouteFromUrl(endpoint),+ });+ res.json(protectedResourceMetadata(resource));+ }+ );+ }+app.get("/.well-known/oauth-authorization-server",async (_req: express.Request, res: express.Response) => {diff --git a/packages/mcp/src/lib/auth-lifecycle-telemetry.ts b/packages/mcp/src/lib/auth-lifecycle-telemetry.tsnew file mode 100644index 00000000..fcad5aa7--- /dev/null+++ b/packages/mcp/src/lib/auth-lifecycle-telemetry.ts@@ -0,0 +1,68 @@+import type { Response } from "express";+import { classifyAuthMethod } from "./mcp-http-auth.js";+import { mcpRouteFromUrl, type McpHttpRoute } from "./mcp-route.js";+import type {+ AuthenticationEnforcementMode,+ AuthenticationMethod,+ AuthenticationOutcome,+} from "./telemetry-contracts.js";+import { recordAuthenticationEvent, recordToolCallOutcome } from "./telemetry-runtime.js";+import type { ToolCallOutcome } from "./tool-names.js";+import type { ClientContext } from "./types.js";++interface AuthEventContext {+ enforcementMode: AuthenticationEnforcementMode;+ method: AuthenticationMethod;+ outcome: AuthenticationOutcome;+ route: McpHttpRoute;+}++function containsJsonRpcMethod(body: unknown, method: string): boolean {+ const messages = Array.isArray(body) ? body : [body];+ return messages.some(+ (message) =>+ typeof message === "object" &&+ message !== null &&+ "method" in message &&+ message.method === method+ );+}++export function observeCredentialedInitialize(+ response: Pick<Response, "once" | "statusCode">,+ body: unknown,+ context: AuthEventContext+): void {+ if (context.method === "none" || !containsJsonRpcMethod(body, "initialize")) return;++ response.once("finish", () => {+ recordAuthenticationEvent({+ ...context,+ event:+ response.statusCode >= 200 && response.statusCode < 300+ ? "credentialed_initialize_succeeded"+ : "credentialed_initialize_failed",+ });+ });+}++export function recordToolCallTelemetry(ctx: ClientContext, outcome: ToolCallOutcome): void {+ recordToolCallOutcome(outcome);+ if (+ ctx.transport !== "http" ||+ !ctx.apiKey ||+ !ctx.mcpAuthMode ||+ !ctx.mcpEndpoint ||+ outcome === "error"+ ) {+ return;+ }++ recordAuthenticationEvent({+ enforcementMode: ctx.mcpAuthMode,+ event: "authenticated_tool_call",+ method: classifyAuthMethod(ctx.apiKey),+ outcome: "accepted",+ route: mcpRouteFromUrl(ctx.mcpEndpoint),+ });+}diff --git a/packages/mcp/src/lib/mcp-http-auth.ts b/packages/mcp/src/lib/mcp-http-auth.tsnew file mode 100644index 00000000..d6892291--- /dev/null+++ b/packages/mcp/src/lib/mcp-http-auth.ts@@ -0,0 +1,129 @@+import type { Request, Response } from "express";+import { EMA_ISSUER, OAUTH_AUTH_SERVER_URL, RESOURCE_URL } from "./constants.js";+import { isJWT, validateJWT } from "./jwt.js";+import type { AuthenticationObservation, AuthenticationMethod } from "./telemetry-contracts.js";++export type McpAuthMode = "observe" | "required";+export type McpEndpoint = "/mcp" | "/mcp/oauth";++export type McpAuthDecision = AuthenticationObservation &+ ({ allowed: true } | { allowed: false; error: string });++export function classifyAuthMethod(token: string | undefined): AuthenticationMethod {+ if (!token) return "none";+ if (token.startsWith("oat_")) return "oauth";+ if (isJWT(token)) return "jwt";+ return "api_key";+}++export function parseMcpAuthMode(raw = process.env.MCP_AUTH_ENFORCEMENT): McpAuthMode {+ const value = raw?.trim().toLowerCase();+ if (!value) return "required";+ if (value === "observe" || value === "required") return value;+ throw new Error(`MCP_AUTH_ENFORCEMENT must be "observe" or "required"; received "${raw}"`);+}++/**+ * Clients of `/mcp/oauth` and the Claude Code plugin start OAuth only after a+ * 401, so they keep that challenge in observe mode and observation covers only+ * the plain `/mcp` route. An empty plugin Authorization header comes from older+ * plugin versions that expanded an unset API key; it stays anonymous until+ * enforcement is required.+ */+export function effectiveMcpAuthMode(+ mode: McpAuthMode,+ endpoint: McpEndpoint,+ plugin: string | undefined,+ authorizationHeader: string | undefined+): McpAuthMode {+ if (mode === "required" || endpoint === "/mcp/oauth") return "required";+ return plugin && authorizationHeader !== "" ? "required" : "observe";+}++/**+ * Decide whether the HTTP request may reach the MCP transport. JWTs can be+ * verified at this boundary. Opaque OAuth tokens and API keys are recorded as+ * present, then authoritatively validated by the Context7 API before data is+ * returned.+ */+export async function evaluateMcpAuthentication(+ token: string | undefined,+ mode: McpAuthMode+): Promise<McpAuthDecision> {+ const method = classifyAuthMethod(token);+ if (!token) {+ return mode === "observe"+ ? { allowed: true, method, event: "credential_missing", outcome: "missing" }+ : {+ allowed: false,+ method,+ error: "Authentication required. Please authenticate to use this MCP server.",+ event: "challenge_issued",+ outcome: "missing",+ };+ }++ if (!isJWT(token)) {+ return {+ allowed: true,+ method,+ event: "credential_present",+ outcome: "accepted",+ };+ }++ const validation = await validateJWT(token);+ if (!validation.valid) {+ return {+ allowed: false,+ method,+ error: validation.error || "Invalid token. Please re-authenticate.",+ event: "credential_rejected",+ outcome: "invalid",+ };+ }++ return {+ allowed: true,+ method,+ event: "credential_validated",+ outcome: "accepted",+ };+}++export function canonicalMcpEndpoint(req: Request): McpEndpoint {+ return `${req.baseUrl}${req.path}`.replace(/\/$/, "") === "/mcp/oauth" ? "/mcp/oauth" : "/mcp";+}++export function protectedResourceUrl(endpoint: McpEndpoint): string {+ return new URL(endpoint, new URL(RESOURCE_URL).origin).toString();+}++function protectedResourceMetadataUrl(endpoint: McpEndpoint): string {+ return new URL(`/.well-known/oauth-protected-resource${endpoint}`, RESOURCE_URL).toString();+}++export function setBearerChallenge(+ res: Response,+ endpoint: McpEndpoint,+ errorDescription?: string+): void {+ const parameters = [`resource_metadata="${protectedResourceMetadataUrl(endpoint)}"`];+ if (errorDescription) {+ const description = errorDescription.replace(/["\\]/g, "");+ parameters.unshift(`error="invalid_token"`, `error_description="${description}"`);+ }+ res.set("WWW-Authenticate", `Bearer ${parameters.join(", ")}`);+}++export function protectedResourceMetadata(resource: string) {+ return {+ resource,+ // Each entry is an independent authorization server. Clerk handles+ // regular authorization-code flows; Context7 handles only the+ // enterprise-managed id-jag exchange.+ authorization_servers: Array.from(new Set([OAUTH_AUTH_SERVER_URL, EMA_ISSUER])),+ scopes_supported: ["profile", "email"],+ bearer_methods_supported: ["header"],+ };+}diff --git a/packages/mcp/src/lib/mcp-route.ts b/packages/mcp/src/lib/mcp-route.tsnew file mode 100644index 00000000..6166ef6f--- /dev/null+++ b/packages/mcp/src/lib/mcp-route.ts@@ -0,0 +1,7 @@+export type McpRoute = "anonymous" | "oauth" | "stdio";+export type McpHttpRoute = Exclude<McpRoute, "stdio">;++export function mcpRouteFromUrl(url: string): McpHttpRoute {+ const pathname = new URL(url, "http://localhost").pathname.replace(/\/+$/, "").toLowerCase();+ return pathname === "/mcp/oauth" ? "oauth" : "anonymous";+}diff --git a/packages/mcp/src/lib/mcp-subscription-telemetry.ts b/packages/mcp/src/lib/mcp-subscription-telemetry.tsindex 9d620cd8..055bd34e 100644--- a/packages/mcp/src/lib/mcp-subscription-telemetry.ts+++ b/packages/mcp/src/lib/mcp-subscription-telemetry.ts@@ -14,13 +14,13 @@ import {type TransportSendOptions,} from "@modelcontextprotocol/server";import { metrics, type Attributes } from "@opentelemetry/api";+import { mcpRouteFromUrl, type McpRoute } from "./mcp-route.js";const INSTRUMENTATION_NAME = "io.github.upstash.context7.mcp";const SUBSCRIPTION_DURATION_BUCKETS_SECONDS = [0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 30, 60, 120, 300,];-export type McpRoute = "anonymous" | "oauth" | "stdio";export type SubscriptionOutcome ="cancelled" | "completed" | "connection_closed" | "replaced" | "transport_error";@@ -407,11 +407,6 @@ export class StdioSubscriptionTelemetry {}}-export function mcpRouteFromUrl(url: string): McpRoute {- const pathname = new URL(url).pathname.replace(/\/+$/, "").toLowerCase();- return pathname === "/mcp/oauth" ? "oauth" : "anonymous";-}-interface ModernListenRequest {message: JSONRPCMessage;protocolVersion?: string;diff --git a/packages/mcp/src/lib/mcp-telemetry.ts b/packages/mcp/src/lib/mcp-telemetry.tsindex bbe482e9..38eb3d1b 100644--- a/packages/mcp/src/lib/mcp-telemetry.ts+++ b/packages/mcp/src/lib/mcp-telemetry.ts@@ -36,15 +36,15 @@ import {} from "@opentelemetry/api";import { MCP_TOOL_NAMES, type ToolCallOutcome } from "./tool-names.js";import { runInMcpOperationScope } from "./mcp-operation-scope.js";+import { mcpRouteFromUrl } from "./mcp-route.js";import {StdioSubscriptionTelemetry,instrumentMcpHttpHandler as instrumentHttpSubscriptions,- mcpRouteFromUrl,type SubscriptionEntryOperation,type SubscriptionObservation,} from "./mcp-subscription-telemetry.js";-export { mcpRouteFromUrl } from "./mcp-subscription-telemetry.js";+export { mcpRouteFromUrl } from "./mcp-route.js";const INSTRUMENTATION_NAME = "io.github.upstash.context7.mcp";const MCP_DURATION_BUCKETS_SECONDS = [diff --git a/packages/mcp/src/lib/telemetry-contracts.ts b/packages/mcp/src/lib/telemetry-contracts.tsindex b4950daf..ebad0958 100644--- a/packages/mcp/src/lib/telemetry-contracts.ts+++ b/packages/mcp/src/lib/telemetry-contracts.ts@@ -1,13 +1,49 @@+import type { McpHttpRoute } from "./mcp-route.js";+export type UpstreamOperation = "fetch_context" | "oauth_metadata" | "search_libraries";export type AuthenticationOutcome = "accepted" | "error" | "invalid" | "missing";+export type AuthenticationMethod = "api_key" | "jwt" | "none" | "oauth";+export type AuthenticationDecisionEvent =+ | "challenge_issued"+ | "credential_missing"+ | "credential_present"+ | "credential_rejected"+ | "credential_validated";+export type AuthenticationLifecycleEvent =+ | "authenticated_tool_call"+ | "credentialed_initialize_failed"+ | "credentialed_initialize_succeeded";+export type AuthenticationEvent =+ AuthenticationDecisionEvent | AuthenticationLifecycleEvent | "metadata_requested";+export type AuthenticationEnforcementMode = "observe" | "required";export type UpstreamOutcome ="cancelled" | "http_error" | "network_error" | "response_error" | "success" | "timeout";-export interface ObservedAuthentication<T> {+export interface AuthenticationObservation {+ event: AuthenticationDecisionEvent;+ method: AuthenticationMethod;outcome: AuthenticationOutcome;- value: T;}+export interface AuthenticationObservationOptions {+ enforcementMode: AuthenticationEnforcementMode;+ route: McpHttpRoute;+}++interface AuthenticationEventDimensions extends AuthenticationObservationOptions {+ method: AuthenticationMethod;+}++export type AuthenticationEventObservation =+ | (AuthenticationEventDimensions & {+ event: "metadata_requested";+ outcome?: never;+ })+ | (AuthenticationEventDimensions & {+ event: Exclude<AuthenticationEvent, "metadata_requested">;+ outcome: AuthenticationOutcome;+ });+export interface UpstreamObservationOptions {abortSignal?: AbortSignal;}diff --git a/packages/mcp/src/lib/telemetry-runtime.ts b/packages/mcp/src/lib/telemetry-runtime.tsindex 168d50ae..7b666f78 100644--- a/packages/mcp/src/lib/telemetry-runtime.ts+++ b/packages/mcp/src/lib/telemetry-runtime.ts@@ -7,7 +7,9 @@ import type {Transport,} from "@modelcontextprotocol/server";import type {- ObservedAuthentication,+ AuthenticationEventObservation,+ AuthenticationObservation,+ AuthenticationObservationOptions,UpstreamObservationOptions,UpstreamOperation,} from "./telemetry-contracts.js";@@ -92,11 +94,16 @@ export async function initializeTelemetry(};}-export async function observeAuthentication<T>(- operation: () => Promise<ObservedAuthentication<T>>+export async function observeAuthentication<T extends AuthenticationObservation>(+ options: AuthenticationObservationOptions,+ operation: () => Promise<T>): Promise<T> {- if (TELEMETRY_DISABLED) return (await operation()).value;- return (await loadImplementation()).observeAuthentication(operation);+ if (TELEMETRY_DISABLED) return operation();+ return (await loadImplementation()).observeAuthentication(options, operation);+}++export function recordAuthenticationEvent(observation: AuthenticationEventObservation): void {+ implementation?.recordAuthenticationEvent(observation);}export async function observeUpstreamRequest<T>(@@ -123,7 +130,9 @@ export async function forceFlushTelemetry(): Promise<void> {}export type {- ObservedAuthentication,+ AuthenticationEventObservation,+ AuthenticationObservation,+ AuthenticationObservationOptions,UpstreamObservationOptions,UpstreamOperation,} from "./telemetry-contracts.js";diff --git a/packages/mcp/src/lib/telemetry.ts b/packages/mcp/src/lib/telemetry.tsindex 677b6a0c..8942c10c 100644--- a/packages/mcp/src/lib/telemetry.ts+++ b/packages/mcp/src/lib/telemetry.ts@@ -2,7 +2,9 @@ import { metrics, trace, type Attributes } from "@opentelemetry/api";import { markCurrentMcpOperationError, markCurrentMcpToolOutcome } from "./mcp-operation-scope.js";import type {AuthenticationOutcome,- ObservedAuthentication,+ AuthenticationEventObservation,+ AuthenticationObservation,+ AuthenticationObservationOptions,UpstreamObservationOptions,UpstreamOperation,UpstreamOutcome,@@ -29,7 +31,7 @@ const NETWORK_ERROR_CODES = new Set([export type {AuthenticationOutcome,- ObservedAuthentication,+ AuthenticationObservation,UpstreamObservationOptions,UpstreamOperation,UpstreamOutcome,@@ -52,16 +54,20 @@ function createInstruments() {unit: "{request}",}),authenticationAttempts: meter.createCounter("context7.mcp.authentication.attempts", {- description: "Number of authentication attempts on the OAuth-protected MCP endpoint",+ description: "Number of hosted MCP authentication decisions",unit: "{attempt}",}),+ authenticationEvents: meter.createCounter("context7.mcp.authentication.events", {+ description: "Number of hosted MCP authentication lifecycle events",+ unit: "{event}",+ }),authenticationDuration: meter.createHistogram("context7.mcp.authentication.duration", {- description: "Duration of authentication on the OAuth-protected MCP endpoint",+ description: "Duration of hosted MCP authentication decisions",unit: "s",advice: { explicitBucketBoundaries: DURATION_BUCKETS_SECONDS },}),activeAuthentications: meter.createUpDownCounter("context7.mcp.authentication.active", {- description: "Number of OAuth-protected MCP requests currently authenticating",+ description: "Number of hosted MCP requests currently authenticating",unit: "{request}",}),};@@ -211,12 +217,17 @@ export async function forceFlushTelemetry(): Promise<void> {}}-export async function observeAuthentication<T>(- operation: () => Promise<ObservedAuthentication<T>>+export async function observeAuthentication<T extends AuthenticationObservation>(+ options: AuthenticationObservationOptions,+ operation: () => Promise<T>): Promise<T> {- const { activeAuthentications, authenticationAttempts, authenticationDuration } =- getInstruments();- const activeAttributes: Attributes = { "context7.mcp.route": "oauth" };+ const {+ activeAuthentications,+ authenticationAttempts,+ authenticationDuration,+ authenticationEvents,+ } = getInstruments();+ const activeAttributes: Attributes = { "context7.mcp.route": options.route };const startedAt = performance.now();let outcome: AuthenticationOutcome = "error";activeAuthentications.add(1, activeAttributes);@@ -224,11 +235,36 @@ export async function observeAuthentication<T>(try {const observed = await operation();outcome = observed.outcome;- return observed.value;+ const attributes: Attributes = {+ ...activeAttributes,+ "context7.authentication.enforcement": options.enforcementMode,+ "context7.authentication.event": observed.event,+ "context7.authentication.method": observed.method,+ "context7.authentication.outcome": outcome,+ };+ authenticationEvents.add(1, attributes);+ return observed;} finally {- const attributes = { "context7.authentication.outcome": outcome };+ const attributes: Attributes = {+ ...activeAttributes,+ "context7.authentication.enforcement": options.enforcementMode,+ "context7.authentication.outcome": outcome,+ };activeAuthentications.add(-1, activeAttributes);authenticationAttempts.add(1, attributes);authenticationDuration.record(elapsedSeconds(startedAt), attributes);}}++export function recordAuthenticationEvent(observation: AuthenticationEventObservation): void {+ const attributes: Attributes = {+ "context7.authentication.enforcement": observation.enforcementMode,+ "context7.authentication.event": observation.event,+ "context7.authentication.method": observation.method,+ "context7.mcp.route": observation.route,+ };+ if (observation.outcome) {+ attributes["context7.authentication.outcome"] = observation.outcome;+ }+ getInstruments().authenticationEvents.add(1, attributes);+}diff --git a/packages/mcp/src/lib/types.ts b/packages/mcp/src/lib/types.tsindex 2c569b23..3d85c591 100644--- a/packages/mcp/src/lib/types.ts+++ b/packages/mcp/src/lib/types.ts@@ -43,6 +43,8 @@ export interface ClientContext {version?: string;};plugin?: string;+ mcpEndpoint?: "/mcp" | "/mcp/oauth";+ mcpAuthMode?: "observe" | "required";transport?: "stdio" | "http";sessionId?: string;/** Mutable: set by the upstream API layer when the backend signals thediff --git a/packages/mcp/test/auth-lifecycle-telemetry.test.ts b/packages/mcp/test/auth-lifecycle-telemetry.test.tsnew file mode 100644index 00000000..f6cb6966--- /dev/null+++ b/packages/mcp/test/auth-lifecycle-telemetry.test.ts@@ -0,0 +1,101 @@+import { EventEmitter } from "node:events";+import { afterEach, describe, expect, test, vi } from "vitest";++const telemetry = vi.hoisted(() => ({+ recordAuthenticationEvent: vi.fn(),+ recordToolCallOutcome: vi.fn(),+}));++vi.mock("../src/lib/telemetry-runtime.js", () => telemetry);++import {+ observeCredentialedInitialize,+ recordToolCallTelemetry,+} from "../src/lib/auth-lifecycle-telemetry.js";++afterEach(() => {+ vi.clearAllMocks();+});++describe("MCP authentication lifecycle telemetry", () => {+ test.each([+ [200, "credentialed_initialize_succeeded"],+ [500, "credentialed_initialize_failed"],+ ] as const)("records credentialed initialize completion for status %s", (statusCode, event) => {+ const response = new EventEmitter() as EventEmitter & { statusCode: number };+ response.statusCode = statusCode;++ observeCredentialedInitialize(+ response,+ { jsonrpc: "2.0", method: "initialize", id: 1 },+ {+ enforcementMode: "required",+ method: "oauth",+ outcome: "accepted",+ route: "anonymous",+ }+ );+ response.emit("finish");++ expect(telemetry.recordAuthenticationEvent).toHaveBeenCalledWith({+ enforcementMode: "required",+ event,+ method: "oauth",+ outcome: "accepted",+ route: "anonymous",+ });+ });++ test("ignores unauthenticated initialize and failed tool calls", () => {+ const response = new EventEmitter() as EventEmitter & { statusCode: number };+ response.statusCode = 200;++ observeCredentialedInitialize(+ response,+ { method: "initialize" },+ {+ enforcementMode: "observe",+ method: "none",+ route: "anonymous",+ }+ );+ response.emit("finish");+ recordToolCallTelemetry(+ { apiKey: "oat_example", transport: "http", mcpEndpoint: "/mcp" },+ "error"+ );++ expect(telemetry.recordToolCallOutcome).toHaveBeenCalledWith("error");+ expect(telemetry.recordAuthenticationEvent).not.toHaveBeenCalled();+ });++ test("does not invent missing HTTP telemetry context", () => {+ recordToolCallTelemetry(+ { apiKey: "oat_example", transport: "http", mcpEndpoint: "/mcp" },+ "success"+ );++ expect(telemetry.recordToolCallOutcome).toHaveBeenCalledWith("success");+ expect(telemetry.recordAuthenticationEvent).not.toHaveBeenCalled();+ });++ test("records successful authenticated tool use", () => {+ recordToolCallTelemetry(+ {+ apiKey: "oat_example",+ transport: "http",+ mcpAuthMode: "required",+ mcpEndpoint: "/mcp",+ },+ "success"+ );++ expect(telemetry.recordAuthenticationEvent).toHaveBeenCalledWith({+ enforcementMode: "required",+ event: "authenticated_tool_call",+ method: "oauth",+ outcome: "accepted",+ route: "anonymous",+ });+ });+});diff --git a/packages/mcp/test/auth-telemetry.test.ts b/packages/mcp/test/auth-telemetry.test.tsnew file mode 100644index 00000000..7352b236--- /dev/null+++ b/packages/mcp/test/auth-telemetry.test.ts@@ -0,0 +1,95 @@+import { afterAll, beforeAll, beforeEach, describe, expect, test } from "vitest";+import { metrics } from "@opentelemetry/api";+import {+ AggregationTemporality,+ DataPointType,+ InMemoryMetricExporter,+ MeterProvider,+ PeriodicExportingMetricReader,+} from "@opentelemetry/sdk-metrics";+import {+ forceFlushTelemetry,+ observeAuthentication,+ recordAuthenticationEvent,+} from "../src/lib/telemetry.js";++const exporter = new InMemoryMetricExporter(AggregationTemporality.CUMULATIVE);+const provider = new MeterProvider({+ readers: [+ new PeriodicExportingMetricReader({+ exporter,+ exportIntervalMillis: 60_000,+ }),+ ],+});++beforeAll(() => {+ expect(metrics.setGlobalMeterProvider(provider)).toBe(true);+});++beforeEach(() => {+ exporter.reset();+});++afterAll(async () => {+ await provider.shutdown();+ metrics.disable();+});++function authenticationEvents() {+ const metric = exporter+ .getMetrics()+ .at(-1)+ ?.scopeMetrics.flatMap((scope) => scope.metrics)+ .find((candidate) => candidate.descriptor.name === "context7.mcp.authentication.events");+ if (!metric || metric.dataPointType !== DataPointType.SUM) return [];+ return metric.dataPoints;+}++describe("MCP authentication OpenTelemetry", () => {+ test("records authentication decisions with bounded migration attributes", async () => {+ await expect(+ observeAuthentication({ enforcementMode: "required", route: "anonymous" }, async () => ({+ allowed: false,+ event: "challenge_issued",+ method: "none",+ outcome: "missing",+ }))+ ).resolves.toMatchObject({ allowed: false, event: "challenge_issued" });+ await forceFlushTelemetry();++ expect(authenticationEvents()).toContainEqual(+ expect.objectContaining({+ attributes: {+ "context7.authentication.enforcement": "required",+ "context7.authentication.event": "challenge_issued",+ "context7.authentication.method": "none",+ "context7.authentication.outcome": "missing",+ "context7.mcp.route": "anonymous",+ },+ value: 1,+ })+ );+ });++ test("records lifecycle events on the same meter", async () => {+ recordAuthenticationEvent({+ enforcementMode: "required",+ event: "authenticated_tool_call",+ method: "oauth",+ outcome: "accepted",+ route: "anonymous",+ });+ await forceFlushTelemetry();++ expect(authenticationEvents()).toContainEqual(+ expect.objectContaining({+ attributes: expect.objectContaining({+ "context7.authentication.event": "authenticated_tool_call",+ "context7.authentication.method": "oauth",+ }),+ value: 1,+ })+ );+ });+});diff --git a/packages/mcp/test/integration.test.ts b/packages/mcp/test/integration.test.tsindex 4292d0d0..139fc7e9 100644--- a/packages/mcp/test/integration.test.ts+++ b/packages/mcp/test/integration.test.ts@@ -179,6 +179,7 @@ beforeAll(async () => {OTEL_EXPORTER_PROMETHEUS_HOST: "127.0.0.1",OTEL_EXPORTER_PROMETHEUS_PORT: String(metricsPort),MCP_CLIENT_IP_ASSERTION_KEY: CLIENT_IP_ASSERTION_KEY,+ MCP_AUTH_ENFORCEMENT: "required",};({ child: httpChild, url: httpUrl } = await startHttpChild());}, 120_000);@@ -200,6 +201,7 @@ async function connect(transportKind: "http" | "stdio", era: "modern" | "legacy"// info) is observable; modern clients must beat it via the envelope.requestInit: {headers: {+ Authorization: "Bearer ctx7sk-local-test","user-agent": "ua-fallback/9.9.9","x-forwarded-for": "attacker-selected-bucket, 203.0.113.77",},@@ -222,6 +224,19 @@ describe("OAuth discovery", () => {});});+ test.each([+ ["/mcp", "/.well-known/oauth-protected-resource/mcp"],+ ["/mcp/oauth", "/.well-known/oauth-protected-resource/mcp/oauth"],+ ])("advertises endpoint-specific metadata for %s", async (endpoint, metadataPath) => {+ const response = await fetch(new URL(metadataPath, httpUrl));++ expect(response.status).toBe(200);+ expect(await response.json()).toMatchObject({+ resource: `https://mcp.context7.com${endpoint}`,+ authorization_servers: ["https://clerk.context7.com", "https://context7.com"],+ });+ });+test("serves the SEP-2127 server card at /mcp/server-card", async () => {const response = await fetch(new URL("/mcp/server-card", httpUrl));@@ -361,7 +376,11 @@ describe.each([test("is not reported as a parse error", async () => {const response = await fetch(new URL("/mcp", httpUrl), {method: "POST",- headers: { "Content-Type": "application/json", Accept: "application/json" },+ headers: {+ "Content-Type": "application/json",+ Accept: "application/json",+ Authorization: "Bearer ctx7sk-local-test",+ },body,});@@ -551,7 +570,11 @@ describe("OpenTelemetry metrics", () => {);try {- await client.connect(new StreamableHTTPClientTransport(new URL(disabledServer.url)));+ await client.connect(+ new StreamableHTTPClientTransport(new URL(disabledServer.url), {+ requestInit: { headers: { Authorization: "Bearer ctx7sk-local-test" } },+ })+ );const result = await client.callTool({name: "query-docs",arguments: { libraryId: "/vercel/next.js", query: "disabled telemetry" },@@ -571,6 +594,7 @@ describe("OpenTelemetry metrics", () => {headers: {accept: "application/json, text/event-stream","content-type": "application/json",+ authorization: "Bearer ctx7sk-local-test",},body: JSON.stringify([{ jsonrpc: "2.0", id: 90_001, method: "tools/list", params: {} },@@ -697,11 +721,30 @@ describe("OpenTelemetry metrics", () => {)).toBe(true);expect(exported).toMatch(- /context7_mcp_authentication_attempts_total\{[^}]*context7_authentication_outcome="missing"[^}]*\} 1/+ /context7_mcp_authentication_attempts_total\{[^}]*context7_authentication_outcome="missing"[^}]*\} [1-9][0-9]*/);expect(exported).toMatch(- /context7_mcp_authentication_attempts_total\{[^}]*context7_authentication_outcome="accepted"[^}]*\} 1/+ /context7_mcp_authentication_attempts_total\{[^}]*context7_authentication_outcome="accepted"[^}]*\} [1-9][0-9]*/);+ const authenticationEvents = exported+ .split("\n")+ .filter((line) => line.startsWith("context7_mcp_authentication_events_total{"));+ expect(+ authenticationEvents.some(+ (line) =>+ line.includes('context7_authentication_event="challenge_issued"') &&+ line.includes('context7_authentication_method="none"') &&+ line.includes('context7_mcp_route="oauth"')+ )+ ).toBe(true);+ expect(+ authenticationEvents.some(+ (line) =>+ line.includes('context7_authentication_event="credential_present"') &&+ line.includes('context7_authentication_method="api_key"') &&+ line.includes('context7_mcp_route="oauth"')+ )+ ).toBe(true);expect(exported).toContain("context7_mcp_authentication_duration_count");expect(exported).toContain("context7_mcp_authentication_active");expect(exported).toContain("mcp_server_operation_duration_bucket");@@ -757,29 +800,124 @@ async function postMcp(target: string, headers: Record<string, string> = {}) {},body: JSON.stringify(INITIALIZE),});- return { status: res.status, wwwAuthenticate: res.headers.get("www-authenticate") };+ return {+ status: res.status,+ wwwAuthenticate: res.headers.get("www-authenticate"),+ exposeHeaders: res.headers.get("access-control-expose-headers"),+ };}-describe("plugin authentication", () => {+describe("hosted HTTP authentication", () => {beforeEach(() => {requests.length = 0;});- test("only challenges the supported plugin", async () => {- expect((await postMcp(`${httpUrl}?client=other-plugin`)).status).toBe(200);+ test.each([undefined, "", "other-plugin", "claude-code-plugin"])(+ "challenges unauthenticated clients (%s)",+ async (client) => {+ const target = client ? `${httpUrl}?client=${client}` : httpUrl;+ const res = await postMcp(target, client === "" ? { Authorization: "" } : undefined);- const res = await postMcp(`${httpUrl}?client=claude-code-plugin`);- expect(res.status).toBe(401);- expect(res.wwwAuthenticate).toContain("resource_metadata=");- expect(res.wwwAuthenticate).toContain("/.well-known/oauth-protected-resource");- });+ expect(res.status).toBe(401);+ expect(res.wwwAuthenticate).toContain(+ 'resource_metadata="https://mcp.context7.com/.well-known/oauth-protected-resource/mcp"'+ );+ }+ );- test("allows the Claude Code plugin's empty API key fallback", async () => {- const res = await postMcp(`${httpUrl}?client=claude-code-plugin`, {- Authorization: "",+ // Node trims header values, so an unset `Bearer ${KEY}` arrives as the bare+ // scheme; it must count as a missing credential, whatever its case.+ test.each(["Bearer ", "bearer", "BEARER "])(+ "challenges a Bearer header without a token (%j)",+ async (authorization) => {+ const res = await postMcp(httpUrl, { Authorization: authorization });++ expect(res.status).toBe(401);+ expect(res.wwwAuthenticate).toContain(+ 'resource_metadata="https://mcp.context7.com/.well-known/oauth-protected-resource/mcp"'+ );+ expect(res.wwwAuthenticate).not.toContain("invalid_token");+ }+ );++ test("exposes the challenge headers to browser clients", async () => {+ const challenge = await postMcp(httpUrl);+ expect(challenge.status).toBe(401);+ expect(challenge.exposeHeaders).toBe("WWW-Authenticate, MCP-Session-Id");++ const preflight = await fetch(httpUrl, {+ method: "OPTIONS",+ headers: { Origin: "https://example.test", "Access-Control-Request-Method": "POST" },});+ expect(preflight.status).toBe(200);+ expect(preflight.headers.get("access-control-expose-headers")).toBe(+ "WWW-Authenticate, MCP-Session-Id"+ );+ });++ test("allows an opaque credential for downstream validation", async () => {+ const res = await postMcp(httpUrl, { Authorization: "Bearer ctx7sk-test" });expect(res.status).toBe(200);+ expect(res.wwwAuthenticate).toBeNull();+ });++ test("observe mode measures missing credentials without denying access", async () => {+ const observeServer = await startHttpChild({+ environment: { ...childEnv, MCP_AUTH_ENFORCEMENT: "observe" },+ });+ try {+ const res = await postMcp(observeServer.url);+ expect(res.status).toBe(200);+ expect(res.wwwAuthenticate).toBeNull();++ // A scheme-only Authorization header is a missing credential here too.+ for (const authorization of ["Bearer ", "bearer"]) {+ const emptyBearer = await postMcp(observeServer.url, { Authorization: authorization });+ expect(emptyBearer.status).toBe(200);+ expect(emptyBearer.wwwAuthenticate).toBeNull();+ }+ } finally {+ observeServer.child.kill();+ }+ });++ test("observe mode keeps the challenge for OAuth and plugin clients", async () => {+ const observeServer = await startHttpChild({+ environment: { ...childEnv, MCP_AUTH_ENFORCEMENT: "observe" },+ });+ try {+ const oauthRes = await postMcp(observeServer.url.replace(/\/mcp$/, "/mcp/oauth"));+ expect(oauthRes.status).toBe(401);+ expect(oauthRes.wwwAuthenticate).toContain(+ 'resource_metadata="https://mcp.context7.com/.well-known/oauth-protected-resource/mcp/oauth"'+ );++ const pluginUrl = `${observeServer.url}?client=claude-code-plugin`;+ const pluginRes = await postMcp(pluginUrl);+ expect(pluginRes.status).toBe(401);+ expect(pluginRes.wwwAuthenticate).toContain(+ 'resource_metadata="https://mcp.context7.com/.well-known/oauth-protected-resource/mcp"'+ );+ expect((await postMcp(pluginUrl, { Authorization: "" })).status).toBe(200);+ } finally {+ observeServer.child.kill();+ }+ });++ test("defaults to required mode when the rollout setting is absent", async () => {+ const environment = { ...childEnv };+ delete environment.MCP_AUTH_ENFORCEMENT;+ const defaultServer = await startHttpChild({ environment });+ try {+ const res = await postMcp(defaultServer.url);+ expect(res.status).toBe(401);+ expect(res.wwwAuthenticate).toContain(+ 'resource_metadata="https://mcp.context7.com/.well-known/oauth-protected-resource/mcp"'+ );+ } finally {+ defaultServer.child.kill();+ }});test("keeps the OAuth endpoint protected", async () => {@@ -788,8 +926,13 @@ describe("plugin authentication", () => {Authorization: "",});- expect((await postMcp(oauthUrl)).status).toBe(401);+ const missingCredentialRes = await postMcp(oauthUrl);+ expect(missingCredentialRes.status).toBe(401);+ expect(missingCredentialRes.wwwAuthenticate).toContain(+ 'resource_metadata="https://mcp.context7.com/.well-known/oauth-protected-resource/mcp/oauth"'+ );expect(emptyHeaderRes.status).toBe(401);+ expect((await postMcp(oauthUrl, { Authorization: "Bearer ctx7sk-test" })).status).toBe(200);});test("tracks authenticated plugin requests separately", async () => {diff --git a/packages/mcp/test/mcp-http-auth.test.ts b/packages/mcp/test/mcp-http-auth.test.tsnew file mode 100644index 00000000..c356e906--- /dev/null+++ b/packages/mcp/test/mcp-http-auth.test.ts@@ -0,0 +1,86 @@+import { afterEach, describe, expect, test, vi } from "vitest";++vi.mock("../src/lib/jwt.js", () => ({+ isJWT: (token: string) => token.split(".").length === 3,+ validateJWT: vi.fn(),+}));++import { validateJWT } from "../src/lib/jwt.js";+import {+ classifyAuthMethod,+ effectiveMcpAuthMode,+ evaluateMcpAuthentication,+ parseMcpAuthMode,+} from "../src/lib/mcp-http-auth.js";++afterEach(() => {+ vi.unstubAllEnvs();+ vi.clearAllMocks();+});++describe("MCP HTTP authentication policy", () => {+ test("uses bounded authentication dimensions", () => {+ expect(classifyAuthMethod(undefined)).toBe("none");+ expect(classifyAuthMethod("oat_example")).toBe("oauth");+ expect(classifyAuthMethod("header.payload.signature")).toBe("jwt");+ expect(classifyAuthMethod("ctx7sk_example")).toBe("api_key");+ });++ test("defaults to enforcement and rejects unknown rollout modes", () => {+ vi.stubEnv("MCP_AUTH_ENFORCEMENT", "");+ expect(parseMcpAuthMode()).toBe("required");+ expect(() => parseMcpAuthMode("enforce-ish")).toThrow(/observe.*required/);+ });++ test("keeps the existing challenge for OAuth and plugin clients in observe mode", () => {+ expect(effectiveMcpAuthMode("observe", "/mcp", undefined, undefined)).toBe("observe");+ expect(effectiveMcpAuthMode("observe", "/mcp/oauth", undefined, undefined)).toBe("required");+ expect(effectiveMcpAuthMode("observe", "/mcp", "claude-code-plugin", undefined)).toBe(+ "required"+ );+ expect(effectiveMcpAuthMode("observe", "/mcp", "claude-code-plugin", "")).toBe("observe");+ expect(effectiveMcpAuthMode("required", "/mcp", "claude-code-plugin", "")).toBe("required");+ });++ test("separates observation from enforcement for missing credentials", async () => {+ await expect(evaluateMcpAuthentication(undefined, "observe")).resolves.toMatchObject({+ allowed: true,+ event: "credential_missing",+ outcome: "missing",+ });+ await expect(evaluateMcpAuthentication(undefined, "required")).resolves.toMatchObject({+ allowed: false,+ event: "challenge_issued",+ outcome: "missing",+ });+ });++ test("records opaque credentials as present until the API validates them", async () => {+ await expect(evaluateMcpAuthentication("ctx7sk-example", "required")).resolves.toMatchObject({+ allowed: true,+ method: "api_key",+ event: "credential_present",+ });+ });++ test("distinguishes validated and rejected JWTs", async () => {+ vi.mocked(validateJWT).mockResolvedValueOnce({ valid: true }).mockResolvedValueOnce({+ valid: false,+ error: "Token expired",+ });++ await expect(+ evaluateMcpAuthentication("header.payload.signature", "required")+ ).resolves.toMatchObject({+ allowed: true,+ event: "credential_validated",+ });+ await expect(+ evaluateMcpAuthentication("header.payload.signature", "required")+ ).resolves.toMatchObject({+ allowed: false,+ error: "Token expired",+ event: "credential_rejected",+ });+ });+});diff --git a/packages/mcp/test/telemetry-disabled.test.ts b/packages/mcp/test/telemetry-disabled.test.tsindex f7ab564f..43fea126 100644--- a/packages/mcp/test/telemetry-disabled.test.ts+++ b/packages/mcp/test/telemetry-disabled.test.ts@@ -13,6 +13,7 @@ const {forceFlushTelemetry,initializeTelemetry,observeAuthentication,+ recordAuthenticationEvent,recordToolCallOutcome,observeUpstreamRequest,} = await import("../src/lib/telemetry-runtime.js");@@ -43,6 +44,14 @@ test("OTEL_SDK_DISABLED bypasses all application metric instruments", async () =initializeTelemetry({ allowEmbeddedPrometheus: true, serviceVersion: "test" })).resolves.toBeUndefined();expect(() => recordToolCallOutcome("success")).not.toThrow();+ expect(() =>+ recordAuthenticationEvent({+ enforcementMode: "required",+ event: "challenge_issued",+ method: "none",+ route: "anonymous",+ })+ ).not.toThrow();await expect(observeUpstreamRequest("fetch_context",@@ -51,8 +60,13 @@ test("OTEL_SDK_DISABLED bypasses all application metric instruments", async () =)).resolves.toBe("ok");await expect(- observeAuthentication(async () => ({ outcome: "accepted", value: "auth" }))- ).resolves.toBe("auth");+ observeAuthentication({ enforcementMode: "required", route: "anonymous" }, async () => ({+ allowed: true,+ event: "credential_present",+ method: "oauth",+ outcome: "accepted",+ }))+ ).resolves.toMatchObject({ allowed: true, event: "credential_present" });await forceFlushTelemetry();await provider.forceFlush();diff --git a/packages/mcp/test/telemetry.test.ts b/packages/mcp/test/telemetry.test.tsindex 2c5b3935..7dbc5a8d 100644--- a/packages/mcp/test/telemetry.test.ts+++ b/packages/mcp/test/telemetry.test.ts@@ -68,6 +68,8 @@ describe("MCP telemetry cardinality", () => {expect(mcpRouteFromUrl("https://example.com/mcp/oauth")).toBe("oauth");expect(mcpRouteFromUrl("https://example.com/mcp/oauth/")).toBe("oauth");expect(mcpRouteFromUrl("https://example.com/mcp")).toBe("anonymous");+ expect(mcpRouteFromUrl("/mcp/oauth")).toBe("oauth");+ expect(mcpRouteFromUrl("/mcp")).toBe("anonymous");});test("extracts only SEP-414 trace propagation fields", () => {diff --git a/plugins/copilot/context7/README.md b/plugins/copilot/context7/README.mdindex 3052097e..064c4175 100644--- a/plugins/copilot/context7/README.md+++ b/plugins/copilot/context7/README.md@@ -22,7 +22,7 @@ copilot plugin install context7@context7-marketplace## API Key (Recommended)-Without an API key, the plugin connects anonymously and shares the anonymous rate limits. To use your own plan, create an API key in the [Context7 dashboard](https://context7.com/dashboard) and export it as an environment variable before launching Copilot CLI:+Use an API key so the hosted Context7 server can identify you and apply your plan's limits. Create a free API key in the [Context7 dashboard](https://context7.com/dashboard) and export it as an environment variable before launching Copilot CLI:```bash# e.g. in ~/.zshrc or ~/.bashrc