mastra-ai/mastra · error
Bearer token required
Error message
Bearer token required
What it means
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.
Source
Thrown at packages/mcp/src/server/oauth-middleware.ts:161
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Max-Age': '86400',
});
res.end();
return { proceed: false, handled: true };
}
// Only protect the MCP endpoint
if (!url.pathname.startsWith(mcpPath)) {
return { proceed: true, handled: false };
}
// Extract and validate bearer token
const authHeader = req.headers['authorization'];
const token = extractBearerToken(authHeader as string | undefined);
if (!token) {
logger?.debug?.('OAuth middleware: No bearer token provided');
res.writeHead(401, {
'Content-Type': 'application/json',
'WWW-Authenticate': generateWWWAuthenticateHeader({ resourceMetadataUrl }),
});
res.end(
JSON.stringify({
error: 'unauthorized',
error_description: 'Bearer token required',
}),
);
return { proceed: false, handled: true };
}
// Validate the token
if (oauth.validateToken) {
logger?.debug?.('OAuth middleware: Validating token');
const validationResult = await oauth.validateToken(token, oauth.resource);
if (!validationResult.valid) {View on GitHub (pinned to 75dd419e61)
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
Example fix
// before curl http://localhost:4111/mcp // after curl -H 'Authorization: Bearer eyJhbGci...' http://localhost:4111/mcp
Defensive patterns
Strategy: try-catch
Validate before calling
const auth = headers['authorization'];
if (!auth || !auth.startsWith('Bearer ') || auth.length <= 7) {
throw new Error('Request must include Authorization: Bearer <token>');
} Type guard
function hasBearerToken(headers: Record<string, string | string[] | undefined>): boolean {
const a = headers['authorization'];
return typeof a === 'string' && /^Bearer\s+\S+$/.test(a);
} Try / catch
const res = await fetch(mcpUrl, { headers: { Authorization: `Bearer ${token}` } });
if (res.status === 401) {
const wwwAuth = res.headers.get('www-authenticate');
token = await obtainTokenFromMetadata(wwwAuth); // follow resource_metadata then retry
} Prevention
- 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
When it happens
Trigger: 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.
Common situations: Clients not configured with the access token; curl/testing without auth headers; token retrieval step skipped or failed; proxy stripping the Authorization header.
Related errors
- No OAuth authorization is pending for this server. Call conn
- ${validationResult.error || 'invalid_token'}
- State token has expired
- Redirect URI is required for SSO login
- Token exchange failed: ${error}
AI-assisted analysis of mastra-ai/mastra@75dd419e61 (2026-08-30).
Data as JSON: /api/errors/4c1a4ee5a12f810d.
Report an issue: GitHub.