{"record":{"id":"7369e2f32df038b1","repo":"upstash/context7","slug":"32001","errorCode":"-32001","errorMessage":"Authentication required. Please authenticate to use this MCP server.","messagePattern":"Authentication required\\. Please authenticate to use this MCP server\\.","errorType":"http","errorClass":null,"httpStatus":401,"severity":"error","filePath":"packages/mcp/src/index.ts","lineNumber":424,"sourceCode":"    const handleMcpRequest = async (req: express.Request, res: express.Response) => {\n      try {\n        const plugin = getPluginFromRequest(req);\n        const apiKey = extractApiKey(req);\n        const baseUrl = new URL(RESOURCE_URL).origin;\n\n        // OAuth discovery info header, used by MCP clients to discover the authorization server\n        // TODO: @modelcontextprotocol/server now ships canonical OAuth helpers\n        // (bearerAuthChallengeResponse, buildOAuthProtectedResourceMetadata,\n        // oauthMetadataResponse) — replace this hand-rolled header and the\n        // /.well-known/oauth-protected-resource route with them.\n        res.set(\n          \"WWW-Authenticate\",\n          `Bearer resource_metadata=\"${baseUrl}/.well-known/oauth-protected-resource\"`\n        );\n\n        if (requiresAuthentication(req, plugin)) {\n          if (!apiKey) {\n            return res.status(401).json({\n              jsonrpc: \"2.0\",\n              error: {\n                code: -32001,\n                message: \"Authentication required. Please authenticate to use this MCP server.\",\n              },\n              id: null,\n            });\n          }\n\n          if (isJWT(apiKey)) {\n            const validationResult = await validateJWT(apiKey);\n            if (!validationResult.valid) {\n              return res.status(401).json({\n                jsonrpc: \"2.0\",\n                error: {\n                  code: -32001,\n                  message: validationResult.error || \"Invalid token. Please re-authenticate.\",\n                },","sourceCodeStart":406,"sourceCodeEnd":442,"githubUrl":"https://github.com/upstash/context7/blob/80e681a507c5287bc12e483367c40754e29461b9/packages/mcp/src/index.ts#L406-L442","documentation":"The OAuth-protected `/mcp/oauth` route sets `requireAuth`; `extractApiKey` reads the `Authorization: Bearer` and `x_api_key` headers. When neither is present the server replies HTTP 401 with JSON-RPC error code -32001 and a `WWW-Authenticate: Bearer resource_metadata=...` header pointing MCP clients at `/.well-known/oauth-protected-resource` for OAuth discovery.","triggerScenarios":"POSTing a JSON-RPC message to `/mcp/oauth` with no Authorization header; a proxy stripping auth headers; putting the token in a custom header the server doesn't read.","commonSituations":"MCP client configured without OAuth/bearer credentials; testing with curl and forgetting `-H 'Authorization: Bearer ...'`; actually wanting anonymous access but targeting the wrong endpoint.","solutions":["For anonymous use, point the client at `/mcp` (no auth required)","Add `Authorization: Bearer <token>` (or `x_api_key`) to the client config for `/mcp/oauth`","Run `context7 login` and let the MCP client complete OAuth via the WWW-Authenticate discovery header","Check that no intermediary strips the Authorization header"],"exampleFix":"# before\ncurl -X POST https://mcp.context7.com/mcp/oauth -d '{\"jsonrpc\":\"2.0\",...}'\n\n# after\ncurl -X POST https://mcp.context7.com/mcp/oauth \\\n  -H 'Authorization: Bearer ctx7sk-...' \\\n  -H 'Content-Type: application/json' \\\n  -d '{\"jsonrpc\":\"2.0\",...}'","handlingStrategy":"validation","validationCode":"// Client-side: ensure a token exists before using the protected endpoint\nconst token = process.env.CONTEXT7_API_KEY;\nconst url = token ? 'https://mcp.context7.com/mcp/oauth' : 'https://mcp.context7.com/mcp';","typeGuard":"function hasBearerOrApiKey(headers: Record<string, string>): boolean {\n  const auth = headers['authorization'] ?? headers['Authorization'];\n  return Boolean(auth?.startsWith('Bearer ')) || Boolean(headers['x_api_key']);\n}","tryCatchPattern":"const res = await fetch(mcpUrl, { method: 'POST', headers, body });\nif (res.status === 401) {\n  const err = await res.json();\n  if (err?.error?.code === -32001) {\n    // follow WWW-Authenticate resource_metadata to run OAuth discovery\n    throw new Error('no credentials — run the OAuth flow or use the anonymous /mcp endpoint');\n  }\n}","preventionTips":["Configure the MCP client with Authorization: Bearer or x_api_key before first connect","Use /mcp for anonymous access instead of /mcp/oauth","Ensure no proxy strips the Authorization header en route"],"tags":["mcp","authentication","http","json-rpc"],"backgroundTag":"missing-authorization-header","analyzedSha":"80e681a507c5287bc12e483367c40754e29461b9","analyzedAt":"2026-09-08T05:18:41.043Z","contentChangedAt":"2026-09-08T05:18:41.043Z","schemaVersion":2},"datasetVersion":"2026-09-14T00:17:10.932Z"}