{"record":{"id":"4c1a4ee5a12f810d","repo":"mastra-ai/mastra","slug":"bearer-token-required","errorCode":null,"errorMessage":"Bearer token required","messagePattern":"Bearer token required","errorType":"http","errorClass":null,"httpStatus":401,"severity":"error","filePath":"packages/mcp/src/server/oauth-middleware.ts","lineNumber":161,"sourceCode":"        'Access-Control-Allow-Headers': 'Content-Type',\n        'Access-Control-Max-Age': '86400',\n      });\n      res.end();\n      return { proceed: false, handled: true };\n    }\n\n    // Only protect the MCP endpoint\n    if (!url.pathname.startsWith(mcpPath)) {\n      return { proceed: true, handled: false };\n    }\n\n    // Extract and validate bearer token\n    const authHeader = req.headers['authorization'];\n    const token = extractBearerToken(authHeader as string | undefined);\n\n    if (!token) {\n      logger?.debug?.('OAuth middleware: No bearer token provided');\n      res.writeHead(401, {\n        'Content-Type': 'application/json',\n        'WWW-Authenticate': generateWWWAuthenticateHeader({ resourceMetadataUrl }),\n      });\n      res.end(\n        JSON.stringify({\n          error: 'unauthorized',\n          error_description: 'Bearer token required',\n        }),\n      );\n      return { proceed: false, handled: true };\n    }\n\n    // Validate the token\n    if (oauth.validateToken) {\n      logger?.debug?.('OAuth middleware: Validating token');\n      const validationResult = await oauth.validateToken(token, oauth.resource);\n\n      if (!validationResult.valid) {","sourceCodeStart":143,"sourceCodeEnd":179,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/packages/mcp/src/server/oauth-middleware.ts#L143-L179","documentation":"The MCP server's OAuth middleware requires every request to carry a valid bearer token in the Authorization header. When extractBearerToken finds no token (missing header, wrong scheme, or malformed value), the middleware logs a debug message, responds 401 with a WWW-Authenticate header pointing at the resource metadata URL, and the 'Bearer token required' error surfaces.","triggerScenarios":"Sending an HTTP request to the OAuth-protected MCP server endpoint without an Authorization header, with a non-Bearer scheme, or with a malformed 'Bearer ' value.","commonSituations":"Clients not configured with the access token; curl/testing without auth headers; token retrieval step skipped or failed; proxy stripping the Authorization header.","solutions":["Fetch a token from the OAuth server and send it as the Authorization header","Ensure the header format is exactly 'Authorization: Bearer <token>'","Confirm intermediaries are not stripping the Authorization header","Complete the OAuth metadata flow (/.well-known/oauth-protected-resource) to obtain a valid token"],"exampleFix":"// before\ncurl http://localhost:4111/mcp\n// after\ncurl -H 'Authorization: Bearer eyJhbGci...' http://localhost:4111/mcp","handlingStrategy":"try-catch","validationCode":"const auth = headers['authorization'];\nif (!auth || !auth.startsWith('Bearer ') || auth.length <= 7) {\n  throw new Error('Request must include Authorization: Bearer <token>');\n}","typeGuard":"function hasBearerToken(headers: Record<string, string | string[] | undefined>): boolean {\n  const a = headers['authorization'];\n  return typeof a === 'string' && /^Bearer\\s+\\S+$/.test(a);\n}","tryCatchPattern":"const res = await fetch(mcpUrl, { headers: { Authorization: `Bearer ${token}` } });\nif (res.status === 401) {\n  const wwwAuth = res.headers.get('www-authenticate');\n  token = await obtainTokenFromMetadata(wwwAuth); // follow resource_metadata then retry\n}","preventionTips":["Always attach Authorization: Bearer <token> when calling protected MCP endpoints","Complete the OAuth discovery flow (/.well-known/oauth-protected-resource) to mint tokens","Refresh tokens before expiry; handle 401 by re-authenticating","Verify proxies do not strip the Authorization header"],"tags":["mcp","oauth","bearer-token","auth","http-401"],"backgroundTag":"missing-bearer-token","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}