{"record":{"id":"1fd13b10de6923fb","repo":"mastra-ai/mastra","slug":"validationresult-error-invalid-token","errorCode":null,"errorMessage":"${validationResult.error || 'invalid_token'}","messagePattern":"\\$\\{validationResult\\.error \\|\\| 'invalid_token'\\}","errorType":"http","errorClass":null,"httpStatus":401,"severity":"error","filePath":"packages/mcp/src/server/oauth-middleware.ts","lineNumber":181,"sourceCode":"        '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) {\n        logger?.debug?.(`OAuth middleware: Token validation failed: ${validationResult.error}`);\n        res.writeHead(401, {\n          'Content-Type': 'application/json',\n          'WWW-Authenticate': generateWWWAuthenticateHeader({\n            resourceMetadataUrl,\n            additionalParams: {\n              error: validationResult.error || 'invalid_token',\n              ...(validationResult.errorDescription && {\n                error_description: validationResult.errorDescription,\n              }),\n            },\n          }),\n        });\n        res.end(\n          JSON.stringify({\n            error: validationResult.error || 'invalid_token',\n            error_description: validationResult.errorDescription || 'Token validation failed',\n          }),\n        );\n        return { proceed: false, handled: true, tokenValidation: validationResult };","sourceCodeStart":163,"sourceCodeEnd":199,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/packages/mcp/src/server/oauth-middleware.ts#L163-L199","documentation":"The MCP OAuth middleware validates incoming bearer tokens with the user-supplied `oauth.validateToken` callback. When that callback returns `{ valid: false }`, the middleware responds 401 with a WWW-Authenticate header whose `error` parameter defaults to `invalid_token` if the result supplies no `error` code. This is the library's enforcement point for resource-server token checks per the MCP authorization spec.","triggerScenarios":"A request reaches `createOAuthMiddleware` with a bearer token; `await oauth.validateToken(token, oauth.resource)` returns a result with `valid: false` (e.g. `{ valid: false, error: 'token_expired' }`, or no error field which yields the `invalid_token` default).","commonSituations":"Expired or revoked access tokens, tokens issued for a different resource/audience than `oauth.resource`, custom validators rejecting tokens due to clock skew or missing scopes, and JWTs signed by an untrusted issuer.","solutions":["Have the client obtain a fresh token from the authorization server and retry with the new Authorization header.","Check the `error` code in the WWW-Authenticate response header and the 401 body to see why validateToken rejected the token.","Verify the token's audience/resource claim matches the `resource` configured in the middleware's oauth options.","Review your custom `validateToken` implementation for incorrect verification (wrong issuer, keys, or clock-skew tolerance)."],"exampleFix":"// before: validateToken returns { valid: false } with no error code\nreturn { valid: false };\n// after: return a specific RFC 6750 error code so clients can react\nreturn { valid: false, error: 'invalid_token', errorDescription: 'token signature verification failed' };","handlingStrategy":"fallback","validationCode":"const decoded = decodeJwt(token); if (decoded.exp * 1000 < Date.now()) throw new Error('token expired before request');","typeGuard":"function isInvalidTokenResult(r: unknown): r is { valid: false; error?: string; errorDescription?: string } { return !!r && typeof r === 'object' && (r as any).valid === false; }","tryCatchPattern":"try { const res = await fetch(url, { headers: { Authorization: `Bearer ${token}` } }); if (res.status === 401) { const wwwAuth = res.headers.get('WWW-Authenticate'); const code = /error=\"([^\"]+)\"/.exec(wwwAuth ?? '')?.[1] ?? 'invalid_token'; await refreshTokenAndRetry(); } } catch (e) { logger.error('oauth request failed', e); }","preventionTips":["Refresh tokens proactively before expiry with a clock-skew margin.","Assert the token audience matches the MCP server's configured resource.","Unit-test your validateToken callback against expired/wrong-audience tokens."],"tags":["oauth","authentication","http-401","mcp"],"backgroundTag":"oauth-token-rejected","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}