Context7 Platform -- Up-to-date docs for AI agents
CTX7-3073: expired oauth 401 (#3329)
Ramazan Onur Acar126379b7fae7
diff --git a/.changeset/quick-owls-refresh.md b/.changeset/quick-owls-refresh.mdnew file mode 100644index 00000000..2cbcfc3d--- /dev/null+++ b/.changeset/quick-owls-refresh.md@@ -0,0 +1,5 @@+---+"@upstash/context7-mcp": patch+---++Answer an expired or revoked OAuth access token (`oat_…`) on the hosted HTTP transport with an HTTP 401 and a `WWW-Authenticate: Bearer error="invalid_token"` challenge, so MCP clients refresh the token instead of showing a tool error. The server checks the token against the Context7 API before serving the request, caches the verdict in memory per token hash for about a minute on each replica, and fails open when the check is unavailable. Set `MCP_OAUTH_TOKEN_VALIDATION=off` to disable the check. When the Context7 API still rejects an OAuth token on a tool call, the tool text now says the sign-in expired instead of describing API keys.diff --git a/docs/resources/developer.mdx b/docs/resources/developer.mdxindex d1e449f3..475b2747 100644--- a/docs/resources/developer.mdx+++ b/docs/resources/developer.mdx@@ -51,6 +51,8 @@ node packages/mcp/dist/index.js --transport http --port 8080HTTP 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`.+Opaque OAuth access tokens (`oat_…`) are checked against the Context7 API before each request is served (one check per token per minute on each replica; the cache is in memory). An expired or revoked token gets an HTTP 401 with a `WWW-Authenticate` challenge so MCP clients refresh it. Set `MCP_OAUTH_TOKEN_VALIDATION=off` to skip that check and forward the token unchecked.+Stdio transport with API key:```bashdiff --git a/packages/mcp/README.md b/packages/mcp/README.mdindex 335e5c1b..210d5815 100644--- a/packages/mcp/README.md+++ b/packages/mcp/README.md@@ -1444,6 +1444,8 @@ bun run dist/index.js --transport http --port 8080HTTP 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`.+Opaque OAuth access tokens (`oat_…`) are checked against the Context7 API before each request is served (one check per token per minute on each replica; the cache is in memory). An expired or revoked token gets an HTTP 401 with a `WWW-Authenticate` challenge so MCP clients refresh it. Set `MCP_OAUTH_TOKEN_VALIDATION=off` to skip that check and forward the token unchecked.+Another example with stdio transport:```bashdiff --git a/packages/mcp/src/lib/api.ts b/packages/mcp/src/lib/api.tsindex 2416a2fd..90a68079 100644--- a/packages/mcp/src/lib/api.ts+++ b/packages/mcp/src/lib/api.ts@@ -5,6 +5,11 @@ import { CONTEXT7_API_BASE_URL } from "./constants.js";import { readFileSync } from "fs";import tls from "tls";import { observeUpstreamRequest } from "./telemetry-runtime.js";+import {+ INVALID_OAUTH_TOKEN_ERROR_CODE,+ isOpaqueOAuthToken,+ rememberInvalidOpaqueOAuthToken,+} from "./oauth-token-validation.js";/*** Ceiling on a single Context7 API call. Without a signal a stalled backend@@ -14,24 +19,43 @@ import { observeUpstreamRequest } from "./telemetry-runtime.js";*/const API_TIMEOUT_MS = 60_000;+const EXPIRED_SIGN_IN_MESSAGE =+ "Your Context7 sign-in expired. Retry the request so your MCP client can refresh the sign-in.";+/*** Parses error response from the Context7 API* Extracts the server's error message, falling back to status-based messages if parsing fails* @param response The fetch Response object- * @param apiKey Optional API key (used for fallback messages)+ * @param context Client context (transport and credential shape pick the message)* @returns Error message string*/-async function parseErrorResponse(response: Response, apiKey?: string): Promise<string> {+async function parseErrorResponse(response: Response, context: ClientContext): Promise<string> {+ const { apiKey } = context;+ let json: { error?: string; message?: string } | undefined;try {- const json = (await response.json()) as { message?: string };- if (json.message) {- return json.message;- }+ json = (await response.json()) as { error?: string; message?: string };} catch {// JSON parsing failed, fall through to default}const status = response.status;+ // On the hosted transport the auth gate answers the next request with an HTTP+ // 401 so the client refreshes its sign-in; the tool text should say so rather+ // than talk about API keys. stdio keeps the API's own message: there is no+ // HTTP status to act on and the credential there is a configured key.+ if (+ status === 401 &&+ context.transport === "http" &&+ isOpaqueOAuthToken(apiKey) &&+ (json?.error === INVALID_OAUTH_TOKEN_ERROR_CODE || json?.error === undefined)+ ) {+ rememberInvalidOpaqueOAuthToken(apiKey);+ return EXPIRED_SIGN_IN_MESSAGE;+ }+ if (json?.message) {+ return json.message;+ }+if (status === 429) {return apiKey? "Rate limited or quota exceeded. Upgrade your plan at https://context7.com/plans for higher limits."@@ -135,7 +159,7 @@ export async function searchLibraries(async (response) => {readPromptSignal(response, context);if (!response.ok) {- const errorMessage = await parseErrorResponse(response, context.apiKey);+ const errorMessage = await parseErrorResponse(response, context);console.error(errorMessage);return { results: [], error: errorMessage };}@@ -175,7 +199,7 @@ export async function fetchLibraryContext(async (response) => {readPromptSignal(response, context);if (!response.ok) {- const errorMessage = await parseErrorResponse(response, context.apiKey);+ const errorMessage = await parseErrorResponse(response, context);console.error(errorMessage);return { data: errorMessage, outcome: "error" };}diff --git a/packages/mcp/src/lib/mcp-http-auth.ts b/packages/mcp/src/lib/mcp-http-auth.tsindex d6892291..d9e57327 100644--- a/packages/mcp/src/lib/mcp-http-auth.ts+++ b/packages/mcp/src/lib/mcp-http-auth.ts@@ -1,6 +1,12 @@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 {+ EXPIRED_OAUTH_TOKEN_ERROR,+ isOpaqueOAuthToken,+ isOpaqueOAuthTokenValidationEnabled,+ validateOpaqueOAuthToken,+} from "./oauth-token-validation.js";import type { AuthenticationObservation, AuthenticationMethod } from "./telemetry-contracts.js";export type McpAuthMode = "observe" | "required";@@ -11,7 +17,7 @@ export type McpAuthDecision = AuthenticationObservation &export function classifyAuthMethod(token: string | undefined): AuthenticationMethod {if (!token) return "none";- if (token.startsWith("oat_")) return "oauth";+ if (isOpaqueOAuthToken(token)) return "oauth";if (isJWT(token)) return "jwt";return "api_key";}@@ -41,8 +47,10 @@ export function effectiveMcpAuthMode(}/**- * 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+ * Decide whether the HTTP request may reach the MCP transport. JWTs are+ * verified at this boundary. Opaque OAuth tokens are checked against the+ * Context7 API (cached per token) so an expired sign-in gets the HTTP 401 that+ * makes MCP clients refresh it; the check fails open. API keys are recorded as* present, then authoritatively validated by the Context7 API before data is* returned.*/@@ -63,6 +71,22 @@ export async function evaluateMcpAuthentication(};}+ if (isOpaqueOAuthToken(token) && isOpaqueOAuthTokenValidationEnabled()) {+ const verdict = await validateOpaqueOAuthToken(token);+ if (verdict === "invalid") {+ return {+ allowed: false,+ method,+ error: EXPIRED_OAUTH_TOKEN_ERROR,+ event: "credential_rejected",+ outcome: "expired",+ };+ }+ return verdict === "valid"+ ? { allowed: true, method, event: "credential_validated", outcome: "accepted" }+ : { allowed: true, method, event: "credential_present", outcome: "unverified" };+ }+if (!isJWT(token)) {return {allowed: true,diff --git a/packages/mcp/src/lib/oauth-token-validation.ts b/packages/mcp/src/lib/oauth-token-validation.tsnew file mode 100644index 00000000..36533542--- /dev/null+++ b/packages/mcp/src/lib/oauth-token-validation.ts@@ -0,0 +1,173 @@+import { createHash } from "node:crypto";+import { CONTEXT7_API_BASE_URL, SERVER_VERSION } from "./constants.js";+import { observeUpstreamRequest } from "./telemetry-runtime.js";++/**+ * Opaque Clerk OAuth access tokens (`oat_…`) cannot be verified locally the way+ * JWTs can. MCP clients only refresh a token after an HTTP 401, and a tool+ * result is always HTTP 200, so an expired token forwarded to the Context7 API+ * leaves a signed-in client stuck with text errors. The hosted server therefore+ * asks the Context7 API whether the token is still accepted before the request+ * reaches the MCP transport, and answers 401 when it is not.+ */++export type OpaqueOAuthTokenVerdict = "valid" | "invalid" | "unavailable";++export const EXPIRED_OAUTH_TOKEN_ERROR = "The access token expired or is invalid";++/** Response body `error` code the Context7 API uses for a rejected `oat_` bearer. */+export const INVALID_OAUTH_TOKEN_ERROR_CODE = "invalid_oauth_token";++const AUTH_CHECK_PATH = "/v2/auth/check";+const AUTH_CHECK_TIMEOUT_MS = 5_000;+const VALID_TTL_MS = 60_000;+const INVALID_TTL_MS = 30_000;+// A short negative cache keeps an outage from adding the check's latency to+// every request while still retrying soon after the API recovers.+const UNAVAILABLE_TTL_MS = 10_000;+const MAX_CACHE_ENTRIES = 10_000;++interface CachedVerdict {+ verdict: OpaqueOAuthTokenVerdict;+ expiresAt: number;+}++// Keyed by the SHA-256 of the token so a heap dump or a debug print of the+// cache never exposes a usable credential. Map insertion order doubles as the+// eviction order once the cache is full.+const verdicts = new Map<string, CachedVerdict>();+const inFlight = new Map<string, Promise<OpaqueOAuthTokenVerdict>>();++export function isOpaqueOAuthToken(token: string | undefined): token is string {+ return typeof token === "string" && token.startsWith("oat_");+}++/**+ * `MCP_OAUTH_TOKEN_VALIDATION=off` is the rollback switch: opaque OAuth tokens+ * then pass through to the Context7 API exactly as before.+ */+export function isOpaqueOAuthTokenValidationEnabled(+ raw = process.env.MCP_OAUTH_TOKEN_VALIDATION+): boolean {+ const value = raw?.trim().toLowerCase();+ return !(value === "off" || value === "false" || value === "0");+}++function cacheKey(token: string): string {+ return createHash("sha256").update(token).digest("hex");+}++function ttlFor(verdict: OpaqueOAuthTokenVerdict): number {+ if (verdict === "valid") return VALID_TTL_MS;+ if (verdict === "invalid") return INVALID_TTL_MS;+ return UNAVAILABLE_TTL_MS;+}++function remember(key: string, verdict: OpaqueOAuthTokenVerdict, now: number): void {+ verdicts.delete(key);+ while (verdicts.size >= MAX_CACHE_ENTRIES) {+ const oldest = verdicts.keys().next().value;+ if (oldest === undefined) break;+ verdicts.delete(oldest);+ }+ verdicts.set(key, { verdict, expiresAt: now + ttlFor(verdict) });+}++function recall(key: string, now: number): OpaqueOAuthTokenVerdict | undefined {+ const cached = verdicts.get(key);+ if (!cached) return undefined;+ if (cached.expiresAt <= now) {+ verdicts.delete(key);+ return undefined;+ }+ return cached.verdict;+}++async function readErrorCode(response: Response): Promise<string | undefined> {+ try {+ const body = (await response.json()) as { error?: unknown };+ return typeof body.error === "string" ? body.error : undefined;+ } catch {+ return undefined;+ }+}++async function requestVerdict(token: string): Promise<OpaqueOAuthTokenVerdict> {+ const abortSignal = AbortSignal.timeout(AUTH_CHECK_TIMEOUT_MS);+ try {+ return await observeUpstreamRequest(+ "auth_check",+ () =>+ fetch(`${CONTEXT7_API_BASE_URL}${AUTH_CHECK_PATH}`, {+ headers: {+ Authorization: `Bearer ${token}`,+ "X-Context7-Source": "mcp-server",+ "X-Context7-Server-Version": SERVER_VERSION,+ "X-Context7-Transport": "http",+ },+ signal: abortSignal,+ }),+ async (response) => {+ if (response.ok) return "valid";+ // Only the API's explicit rejection of the OAuth token counts; any other+ // status (404 before the endpoint ships, 429, 5xx) fails open.+ if (response.status === 401) {+ const code = await readErrorCode(response);+ if (code === INVALID_OAUTH_TOKEN_ERROR_CODE) return "invalid";+ }+ console.error(`[Context7] OAuth token check unavailable (status ${response.status})`);+ return "unavailable";+ },+ { abortSignal }+ );+ } catch (error) {+ const reason = error instanceof Error ? error.name : "unknown error";+ console.error(`[Context7] OAuth token check failed (${reason})`);+ return "unavailable";+ }+}++/**+ * Validate an opaque OAuth token against the Context7 API. Verdicts are cached+ * token hash in process memory, so each replica checks a token at most about+ * once a minute, and concurrent requests carrying the same token share one check.+ */+export async function validateOpaqueOAuthToken(+ token: string,+ now = Date.now()+): Promise<OpaqueOAuthTokenVerdict> {+ const key = cacheKey(token);+ const cached = recall(key, now);+ if (cached) return cached;++ const pending = inFlight.get(key);+ if (pending) return pending;++ // The TTL counts from when the check started, so a slow check never extends+ // the window during which a stale verdict is served.+ const check = requestVerdict(token)+ .then((verdict) => {+ remember(key, verdict, now);+ return verdict;+ })+ .finally(() => {+ inFlight.delete(key);+ });+ inFlight.set(key, check);+ return check;+}++/**+ * The Context7 API rejected the token on a data request. Remember that so the+ * next MCP request gets the 401 immediately instead of waiting for the cached+ * positive verdict to expire.+ */+export function rememberInvalidOpaqueOAuthToken(token: string, now = Date.now()): void {+ remember(cacheKey(token), "invalid", now);+}++/** Test hook: drop every cached verdict and in-flight check. */+export function resetOpaqueOAuthTokenValidation(): void {+ verdicts.clear();+ inFlight.clear();+}diff --git a/packages/mcp/src/lib/telemetry-contracts.ts b/packages/mcp/src/lib/telemetry-contracts.tsindex ebad0958..91a33e09 100644--- a/packages/mcp/src/lib/telemetry-contracts.ts+++ b/packages/mcp/src/lib/telemetry-contracts.ts@@ -1,7 +1,12 @@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 UpstreamOperation =+ "auth_check" | "fetch_context" | "oauth_metadata" | "search_libraries";+// `expired`: the Context7 API rejected an opaque OAuth token, so the client was+// challenged to refresh. `unverified`: the token check was unavailable and the+// request was forwarded unchecked (fail open).+export type AuthenticationOutcome =+ "accepted" | "error" | "expired" | "invalid" | "missing" | "unverified";export type AuthenticationMethod = "api_key" | "jwt" | "none" | "oauth";export type AuthenticationDecisionEvent =| "challenge_issued"diff --git a/packages/mcp/test/integration.test.ts b/packages/mcp/test/integration.test.tsindex 139fc7e9..af4f0327 100644--- a/packages/mcp/test/integration.test.ts+++ b/packages/mcp/test/integration.test.ts@@ -26,6 +26,15 @@ const NO_RESULTS_QUERY = "force-no-results";const UPSTREAM_ERROR_QUERY = "force-upstream-error";const INVALID_JSON_QUERY = "force-invalid-json";const CLIENT_IP_ASSERTION_KEY = "0123456789abcdef".repeat(4);+const INVALID_OAUTH_TOKEN_BODY = {+ error: "invalid_oauth_token",+ message: "Invalid or expired OAuth token. Please re-authenticate to obtain a new token.",+};+const INVALID_API_KEY_BODY = {+ error: "invalid_api_key",+ message:+ "Invalid API key. Please check your API key. API keys should start with 'ctx7sk' prefix.",+};function decryptClientIpAssertion(value: string): string {const [version, timestamp, nonceHex, ciphertextAndTagHex] = value.split(":");@@ -83,6 +92,35 @@ function startStubApi(): Promise<string> {const url = new URL(req.url!, "http://stub.local");const apiPath = url.pathname.replace(/^\/api/, "");requests.push({ path: apiPath, query: url.searchParams, headers: req.headers });+ const bearer = /^Bearer (.+)$/.exec(req.headers.authorization ?? "")?.[1] ?? "";+ if (apiPath === "/v2/auth/check") {+ // Mirrors context7app: the middleware answers invalid_oauth_token for a+ // rejected oat_ bearer, the handler answers 204 for an accepted one.+ if (bearer.startsWith("oat_outage")) {+ res.statusCode = 503;+ res.end();+ } else if (bearer.startsWith("oat_") && !bearer.startsWith("oat_valid")) {+ res.statusCode = 401;+ res.setHeader("Content-Type", "application/json");+ res.end(JSON.stringify(INVALID_OAUTH_TOKEN_BODY));+ } else {+ res.statusCode = 204;+ res.end();+ }+ return;+ }+ if (apiPath === "/v2/context" && bearer.startsWith("oat_") && !bearer.startsWith("oat_valid")) {+ res.statusCode = 401;+ res.setHeader("Content-Type", "application/json");+ res.end(JSON.stringify(INVALID_OAUTH_TOKEN_BODY));+ return;+ }+ if (apiPath === "/v2/context" && bearer.startsWith("ctx7sk-invalid")) {+ res.statusCode = 401;+ res.setHeader("Content-Type", "application/json");+ res.end(JSON.stringify(INVALID_API_KEY_BODY));+ return;+ }if (apiPath === "/v2/libs/search") {res.setHeader("Content-Type", "application/json");if (url.searchParams.get("query") === INVALID_JSON_QUERY) {@@ -804,9 +842,33 @@ async function postMcp(target: string, headers: Record<string, string> = {}) {status: res.status,wwwAuthenticate: res.headers.get("www-authenticate"),exposeHeaders: res.headers.get("access-control-expose-headers"),+ body: await res.text(),};}+async function callQueryDocs(target: string, headers: Record<string, string>): Promise<string> {+ const client = new Client(+ { name: "test-harness", version: "1.0.0" },+ { versionNegotiation: { mode: { pin: "2026-07-28" } } }+ );+ await client.connect(+ new StreamableHTTPClientTransport(new URL(target), { requestInit: { headers } })+ );+ try {+ const result = await client.callTool({+ name: "query-docs",+ arguments: { libraryId: "/vercel/next.js", query: "app router" },+ });+ return (result.content as { type: string; text: string }[])[0].text;+ } finally {+ await client.close();+ }+}++function authChecks(): RecordedRequest[] {+ return requests.filter((request) => request.path === "/v2/auth/check");+}+describe("hosted HTTP authentication", () => {beforeEach(() => {requests.length = 0;@@ -961,3 +1023,159 @@ describe("hosted HTTP authentication", () => {expect(apiCall?.headers["x-context7-plugin"]).toBe("claude-code-plugin");});});++// Clerk OAuth access tokens are opaque and expire after 24 hours. MCP clients+// refresh them only on an HTTP 401 (Claude Code 2.1.286 and Cursor 3.23.12+// refresh silently on a 401, verified 2026-10-06 with a local proxy), so the+// gate asks the Context7 API about the token before the request reaches the+// transport instead of letting a tool result carry the rejection.+describe("expired OAuth access tokens", () => {+ beforeEach(() => {+ requests.length = 0;+ });++ const EXPIRED_CHALLENGE =+ 'Bearer error="invalid_token", error_description="The access token expired or is invalid", resource_metadata="https://mcp.context7.com/.well-known/oauth-protected-resource/mcp';++ test.each([+ ["/mcp", ""],+ ["/mcp/oauth", "/oauth"],+ ["the plugin route", "?client=claude-code-plugin"],+ ])("challenges an expired token on %s", async (_label, suffix) => {+ const res = await postMcp(`${httpUrl}${suffix}`, {+ Authorization: `Bearer oat_expired-${suffix.length}`,+ });++ expect(res.status).toBe(401);+ expect(res.wwwAuthenticate).toBe(+ `${EXPIRED_CHALLENGE}${suffix.startsWith("/oauth") ? "/oauth" : ""}"`+ );+ expect(JSON.parse(res.body)).toEqual({+ jsonrpc: "2.0",+ error: { code: -32001, message: "The access token expired or is invalid" },+ id: null,+ });+ expect(authChecks()).toHaveLength(1);+ expect(authChecks()[0].headers.authorization).toBe(`Bearer oat_expired-${suffix.length}`);+ expect(authChecks()[0].headers["x-context7-source"]).toBe("mcp-server");+ });++ test("challenges an expired token in observe mode too", async () => {+ const observeServer = await startHttpChild({+ environment: { ...childEnv, MCP_AUTH_ENFORCEMENT: "observe" },+ });+ try {+ const res = await postMcp(observeServer.url, { Authorization: "Bearer oat_expired-observe" });+ expect(res.status).toBe(401);+ expect(res.wwwAuthenticate).toContain('error="invalid_token"');+ } finally {+ observeServer.child.kill();+ }+ });++ test("passes a valid token through and serves the request", async () => {+ const res = await postMcp(httpUrl, { Authorization: "Bearer oat_valid-pass" });++ expect(res.status).toBe(200);+ expect(res.wwwAuthenticate).toBeNull();+ expect(authChecks()).toHaveLength(1);+ });++ test("checks each token at most once per cache window", async () => {+ for (let attempt = 0; attempt < 3; attempt += 1) {+ expect((await postMcp(httpUrl, { Authorization: "Bearer oat_valid-cached" })).status).toBe(+ 200+ );+ }+ for (let attempt = 0; attempt < 3; attempt += 1) {+ expect((await postMcp(httpUrl, { Authorization: "Bearer oat_expired-cached" })).status).toBe(+ 401+ );+ }++ expect(authChecks().map((request) => request.headers.authorization)).toEqual([+ "Bearer oat_valid-cached",+ "Bearer oat_expired-cached",+ ]);+ });++ test("fails open when the check is unavailable and then trusts the API's rejection", async () => {+ const headers = { Authorization: "Bearer oat_outage-open" };+ const first = await postMcp(httpUrl, headers);+ expect(first.status).toBe(200);+ expect(first.wwwAuthenticate).toBeNull();++ // The forwarded request is rejected by the API: the tool text explains the+ // sign-in expired and the gate answers the next request with the 401.+ const text = await callQueryDocs(httpUrl, headers);+ expect(text).toBe(+ "Your Context7 sign-in expired. Retry the request so your MCP client can refresh the sign-in."+ );+ expect(requests.filter((request) => request.path === "/v2/context")).toHaveLength(1);++ const next = await postMcp(httpUrl, headers);+ expect(next.status).toBe(401);+ expect(next.wwwAuthenticate).toContain('error="invalid_token"');+ });++ test("leaves API keys and anonymous clients unchanged", async () => {+ const text = await callQueryDocs(httpUrl, { Authorization: "Bearer ctx7sk-invalid-key" });+ expect(text).toBe(INVALID_API_KEY_BODY.message);++ expect((await postMcp(httpUrl)).status).toBe(401);+ expect(authChecks()).toHaveLength(0);+ });++ test("does not check tokens when validation is switched off", async () => {+ const offServer = await startHttpChild({+ environment: { ...childEnv, MCP_OAUTH_TOKEN_VALIDATION: "off" },+ });+ try {+ const res = await postMcp(offServer.url, { Authorization: "Bearer oat_expired-off" });+ expect(res.status).toBe(200);+ expect(authChecks()).toHaveLength(0);+ } finally {+ offServer.child.kill();+ }+ });++ test("keeps the API's own message on stdio", async () => {+ const client = new Client({ name: "test-harness", version: "1.0.0" });+ await client.connect(+ new StdioClientTransport({+ command: process.execPath,+ args: [DIST],+ env: { ...childEnv, CONTEXT7_API_KEY: "oat_expired-stdio" },+ })+ );+ try {+ const result = await client.callTool({+ name: "query-docs",+ arguments: { libraryId: "/vercel/next.js", query: "app router" },+ });+ expect(result.content).toMatchObject([+ { type: "text", text: INVALID_OAUTH_TOKEN_BODY.message },+ ]);+ } finally {+ await client.close();+ }+ expect(authChecks()).toHaveLength(0);+ });++ test("counts expired tokens in the authentication metrics", async () => {+ await postMcp(httpUrl, { Authorization: "Bearer oat_expired-metrics" });++ let exported = "";+ for (let attempt = 0; attempt < 30; attempt += 1) {+ exported = await (await fetch(metricsUrl)).text();+ if (exported.includes('context7_authentication_outcome="expired"')) break;+ await new Promise((resolve) => setTimeout(resolve, 100));+ }+ expect(exported).toMatch(+ /context7_mcp_authentication_events_total\{[^}]*context7_authentication_event="credential_rejected"[^}]*context7_authentication_method="oauth"[^}]*context7_authentication_outcome="expired"[^}]*\} [1-9]/+ );+ expect(exported).toMatch(+ /context7_mcp_upstream_requests_total\{[^}]*context7_upstream_operation="auth_check"[^}]*\} [1-9]/+ );+ });+});diff --git a/packages/mcp/test/mcp-http-auth.test.ts b/packages/mcp/test/mcp-http-auth.test.tsindex c356e906..83ebadbc 100644--- a/packages/mcp/test/mcp-http-auth.test.ts+++ b/packages/mcp/test/mcp-http-auth.test.ts@@ -5,7 +5,13 @@ vi.mock("../src/lib/jwt.js", () => ({validateJWT: vi.fn(),}));+vi.mock("../src/lib/oauth-token-validation.js", async (importOriginal) => ({+ ...(await importOriginal<typeof import("../src/lib/oauth-token-validation.js")>()),+ validateOpaqueOAuthToken: vi.fn(),+}));+import { validateJWT } from "../src/lib/jwt.js";+import { validateOpaqueOAuthToken } from "../src/lib/oauth-token-validation.js";import {classifyAuthMethod,effectiveMcpAuthMode,@@ -63,6 +69,62 @@ describe("MCP HTTP authentication policy", () => {});});+ test("challenges an expired opaque OAuth token in both modes", async () => {+ vi.mocked(validateOpaqueOAuthToken).mockResolvedValue("invalid");++ for (const mode of ["observe", "required"] as const) {+ await expect(evaluateMcpAuthentication("oat_expired", mode)).resolves.toEqual({+ allowed: false,+ method: "oauth",+ error: "The access token expired or is invalid",+ event: "credential_rejected",+ outcome: "expired",+ });+ }+ expect(validateOpaqueOAuthToken).toHaveBeenCalledWith("oat_expired");+ });++ test("passes a valid opaque OAuth token through and fails open when unchecked", async () => {+ vi.mocked(validateOpaqueOAuthToken)+ .mockResolvedValueOnce("valid")+ .mockResolvedValueOnce("unavailable");++ await expect(evaluateMcpAuthentication("oat_valid", "required")).resolves.toMatchObject({+ allowed: true,+ method: "oauth",+ event: "credential_validated",+ outcome: "accepted",+ });+ await expect(evaluateMcpAuthentication("oat_outage", "required")).resolves.toMatchObject({+ allowed: true,+ method: "oauth",+ event: "credential_present",+ outcome: "unverified",+ });+ });++ test("skips the opaque OAuth token check when validation is switched off", async () => {+ vi.stubEnv("MCP_OAUTH_TOKEN_VALIDATION", "off");++ await expect(evaluateMcpAuthentication("oat_expired", "required")).resolves.toMatchObject({+ allowed: true,+ method: "oauth",+ event: "credential_present",+ outcome: "accepted",+ });+ expect(validateOpaqueOAuthToken).not.toHaveBeenCalled();+ });++ test("leaves API keys to the Context7 API", async () => {+ await expect(evaluateMcpAuthentication("ctx7sk-invalid", "required")).resolves.toMatchObject({+ allowed: true,+ method: "api_key",+ event: "credential_present",+ outcome: "accepted",+ });+ expect(validateOpaqueOAuthToken).not.toHaveBeenCalled();+ });+test("distinguishes validated and rejected JWTs", async () => {vi.mocked(validateJWT).mockResolvedValueOnce({ valid: true }).mockResolvedValueOnce({valid: false,diff --git a/packages/mcp/test/oauth-token-validation.test.ts b/packages/mcp/test/oauth-token-validation.test.tsnew file mode 100644index 00000000..5347cb52--- /dev/null+++ b/packages/mcp/test/oauth-token-validation.test.ts@@ -0,0 +1,169 @@+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import {+ isOpaqueOAuthToken,+ isOpaqueOAuthTokenValidationEnabled,+ rememberInvalidOpaqueOAuthToken,+ resetOpaqueOAuthTokenValidation,+ validateOpaqueOAuthToken,+} from "../src/lib/oauth-token-validation.js";++const fetchMock = vi.fn<typeof fetch>();++function jsonResponse(status: number, body: unknown): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { "content-type": "application/json" },+ });+}++const rejected = () =>+ jsonResponse(401, {+ error: "invalid_oauth_token",+ message: "Invalid or expired OAuth token. Please re-authenticate to obtain a new token.",+ });++beforeEach(() => {+ resetOpaqueOAuthTokenValidation();+ fetchMock.mockReset();+ vi.stubGlobal("fetch", fetchMock);+ vi.spyOn(console, "error").mockImplementation(() => {});+});++afterEach(() => {+ vi.unstubAllGlobals();+ vi.unstubAllEnvs();+ vi.restoreAllMocks();+});++describe("opaque OAuth token validation", () => {+ test("recognises Clerk opaque tokens and the rollback switch", () => {+ expect(isOpaqueOAuthToken("oat_abc")).toBe(true);+ expect(isOpaqueOAuthToken("ctx7sk-abc")).toBe(false);+ expect(isOpaqueOAuthToken("a.b.c")).toBe(false);+ expect(isOpaqueOAuthToken(undefined)).toBe(false);++ expect(isOpaqueOAuthTokenValidationEnabled(undefined)).toBe(true);+ expect(isOpaqueOAuthTokenValidationEnabled("on")).toBe(true);+ expect(isOpaqueOAuthTokenValidationEnabled("off")).toBe(false);+ expect(isOpaqueOAuthTokenValidationEnabled(" OFF ")).toBe(false);+ expect(isOpaqueOAuthTokenValidationEnabled("0")).toBe(false);+ });++ test("asks the Context7 API with the bearer and accepts a 2xx", async () => {+ fetchMock.mockResolvedValueOnce(new Response(null, { status: 204 }));++ await expect(validateOpaqueOAuthToken("oat_valid")).resolves.toBe("valid");++ expect(fetchMock).toHaveBeenCalledTimes(1);+ const [url, init] = fetchMock.mock.calls[0];+ expect(String(url)).toMatch(/\/v2\/auth\/check$/);+ expect((init?.headers as Record<string, string>).Authorization).toBe("Bearer oat_valid");+ });++ test("treats the API's invalid_oauth_token rejection as expired", async () => {+ fetchMock.mockResolvedValueOnce(rejected());++ await expect(validateOpaqueOAuthToken("oat_expired")).resolves.toBe("invalid");+ });++ test.each([+ ["a 401 with another error code", () => jsonResponse(401, { error: "unauthorized" })],+ ["a 404 before the endpoint is deployed", () => new Response(null, { status: 404 })],+ ["a 429", () => jsonResponse(429, { error: "Too Many Requests" })],+ ["a 503", () => new Response(null, { status: 503 })],+ ])("fails open on %s", async (_label, response) => {+ fetchMock.mockResolvedValueOnce(response());++ await expect(validateOpaqueOAuthToken("oat_outage")).resolves.toBe("unavailable");+ });++ test("fails open when the check errors or times out", async () => {+ fetchMock.mockRejectedValueOnce(new DOMException("The operation was aborted", "TimeoutError"));+ await expect(validateOpaqueOAuthToken("oat_timeout")).resolves.toBe("unavailable");++ fetchMock.mockRejectedValueOnce(new TypeError("fetch failed"));+ await expect(validateOpaqueOAuthToken("oat_network")).resolves.toBe("unavailable");+ });++ test("never logs the token", async () => {+ fetchMock.mockRejectedValueOnce(new TypeError("fetch failed oat_secret-token"));+ await validateOpaqueOAuthToken("oat_secret-token");+ fetchMock.mockResolvedValueOnce(new Response(null, { status: 503 }));+ await validateOpaqueOAuthToken("oat_other-secret");++ const logged = vi.mocked(console.error).mock.calls.flat().map(String).join("\n");+ expect(logged).not.toContain("oat_");+ });++ test("caches a valid verdict for a minute and an invalid one for 30 seconds", async () => {+ const start = 1_000_000;+ fetchMock.mockResolvedValueOnce(new Response(null, { status: 204 }));+ await expect(validateOpaqueOAuthToken("oat_valid", start)).resolves.toBe("valid");+ await expect(validateOpaqueOAuthToken("oat_valid", start + 59_000)).resolves.toBe("valid");+ expect(fetchMock).toHaveBeenCalledTimes(1);++ fetchMock.mockResolvedValueOnce(rejected());+ await expect(validateOpaqueOAuthToken("oat_expired", start)).resolves.toBe("invalid");+ await expect(validateOpaqueOAuthToken("oat_expired", start + 29_000)).resolves.toBe("invalid");+ expect(fetchMock).toHaveBeenCalledTimes(2);++ // Each verdict is re-checked once its own TTL lapses.+ fetchMock.mockResolvedValueOnce(rejected());+ await expect(validateOpaqueOAuthToken("oat_expired", start + 31_000)).resolves.toBe("invalid");+ fetchMock.mockResolvedValueOnce(new Response(null, { status: 204 }));+ await expect(validateOpaqueOAuthToken("oat_valid", start + 61_000)).resolves.toBe("valid");+ expect(fetchMock).toHaveBeenCalledTimes(4);+ });++ test("retries an unavailable verdict after a short hold", async () => {+ const start = 2_000_000;+ fetchMock.mockResolvedValueOnce(new Response(null, { status: 503 }));+ await expect(validateOpaqueOAuthToken("oat_outage", start)).resolves.toBe("unavailable");+ await expect(validateOpaqueOAuthToken("oat_outage", start + 5_000)).resolves.toBe(+ "unavailable"+ );+ expect(fetchMock).toHaveBeenCalledTimes(1);++ fetchMock.mockResolvedValueOnce(new Response(null, { status: 204 }));+ await expect(validateOpaqueOAuthToken("oat_outage", start + 11_000)).resolves.toBe("valid");+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });++ test("coalesces concurrent checks for the same token", async () => {+ let release!: (response: Response) => void;+ fetchMock.mockReturnValueOnce(new Promise<Response>((resolve) => (release = resolve)));++ const first = validateOpaqueOAuthToken("oat_burst");+ const second = validateOpaqueOAuthToken("oat_burst");+ release(new Response(null, { status: 204 }));++ await expect(Promise.all([first, second])).resolves.toEqual(["valid", "valid"]);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ test("a data-request rejection overrides a cached positive verdict", async () => {+ const start = 3_000_000;+ fetchMock.mockResolvedValueOnce(new Response(null, { status: 204 }));+ await expect(validateOpaqueOAuthToken("oat_revoked", start)).resolves.toBe("valid");++ rememberInvalidOpaqueOAuthToken("oat_revoked", start + 1_000);++ await expect(validateOpaqueOAuthToken("oat_revoked", start + 2_000)).resolves.toBe("invalid");+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ test("bounds the cache size", async () => {+ const start = 4_000_000;+ for (let index = 0; index < 10_001; index += 1) {+ fetchMock.mockResolvedValueOnce(new Response(null, { status: 204 }));+ await validateOpaqueOAuthToken(`oat_${index}`, start);+ }+ expect(fetchMock).toHaveBeenCalledTimes(10_001);++ // The oldest entry was evicted; the newest survives.+ fetchMock.mockResolvedValueOnce(new Response(null, { status: 204 }));+ await validateOpaqueOAuthToken("oat_0", start + 1);+ await validateOpaqueOAuthToken("oat_10000", start + 1);+ expect(fetchMock).toHaveBeenCalledTimes(10_002);+ });+});