MCP server - Support OAuth scopes
Expected Behavior
I want to build an MCP server that uses OAuth for authorization and requires different OAuth scopes for diffferent tools and resources. According to the MCP spec, an MCP server should respond with something like this if a required scope is missing:
HTTP/1.1 403 Forbidden
WWW-Authenticate: Bearer error="insufficient_scope",
scope="files:write",
resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource",
error_description="File write permission required for this operation"
Current Behavior
I managed to protect the whole /mcp endpoint with OAuth2 using spring-security-oauth2-resource-server, but I am struggling to enforce scopes on tools/resources.
I tried throwing an OAuth2AuthenticationException which should get handled by spring-security-oauth2-resource-server and create a HTTP 403 response with the correct WWW-Authenticate header.
@Component
public class EchoTools {
@McpTool(name = "echo", description = "Echo the input string")
public String echo(@McpToolParam(description = "input string", required = true) String str ) {
if (SecurityContextHolder.getContext().getAuthentication().getAuthorities().stream().map(GrantedAuthority::getAuthority).noneMatch("SCOPE_echo"::equals)) {
throw new OAuth2AuthenticationException(BearerTokenErrors.insufficientScope("missing scope", "echo"));
}
return "echo: " + str;
}
}
Unfortunately in spring-ai 2.0.0 this exception gets caught by SyncMcpToolMethodCallback and the MCP server responds with a JSON-RCP error instead:
{
"jsonrpc": "2.0",
"id": 6,
"result": {
"content": [
{
"type": "text",
"text": "Error invoking method: echo\nmissing scope"
}
],
"isError": true
}
}
I also tried 2.0.1-SNAPSHOT because the exception handling was changed a bit in https://github.com/spring-projects/spring-ai/pull/6534, but OAuth2AuthenticationException is still converted to a JSON-RPC error because it is a RuntimeException.
I would like to explore this issue. From the current behavior, OAuth2AuthenticationException is being caught inside SyncMcpToolMethodCallback and converted into a JSON-RPC error response before Spring Security's authentication exception handling can generate the expected HTTP 403 response.
A possible approach could be introducing an authorization layer before MCP tool invocation to validate required scopes, instead of handling scopes inside every @McpTool method.
I would like to investigate whether MCP tool metadata can be extended to support required OAuth scopes and enforce them centrally.
i can pick this up and update SyncMcpToolMethodCallback to rethrow AuthenticationException and AccessDeniedException instead of catching them as runtime exceptions. letting them bubble up to the spring security filter chain will allow BearerTokenAuthenticationEntryPoint to render the correct 403 response with the missing scope headers.
I guess it is not that easy. I built a local version that rethrows the Exception in SyncMcpToolMethodCallback, but it then gets intercepted and wrapped into a JSON-RPC error by the onErrorResume handler in McpStreamableServerSession.
return requestHandler
.handle(new McpAsyncServerExchange(this.id, stream, clientCapabilities.get(), clientInfo.get(),
transportContext, this.jsonSchemaValidator), jsonrpcRequest.params())
.map(result -> McpSchema.JSONRPCResponse.result(jsonrpcRequest.id(), result))
.onErrorResume(e -> {
McpSchema.JSONRPCResponse.JSONRPCError jsonRpcError = (e instanceof McpError mcpError
&& mcpError.getJsonRpcError() != null) ? mcpError.getJsonRpcError()
: new McpSchema.JSONRPCResponse.JSONRPCError(McpSchema.ErrorCodes.INTERNAL_ERROR,
e.getMessage(), McpError.aggregateExceptionMessages(e));
var errorResponse = McpSchema.JSONRPCResponse.error(jsonrpcRequest.id(), jsonRpcError);
return Mono.just(errorResponse);
})
https://github.com/modelcontextprotocol/java-sdk/blob/fd004989b9484c9b81be6b03463396797b354804/mcp-core/src/main/java/io/modelcontextprotocol/spec/McpStreamableServerSession.java#L230
I managed to implement scope validation in my MCP server by adding a custom HandlerFilterFunction to the webMvcStreamableServerRouterFunction:
@Component
public class McpOauthScopeHandlerFilterFunction implements HandlerFilterFunction<ServerResponse, ServerResponse> {
private final Map<String, List<String>> toolScopes;
private final McpJsonMapper jsonMapper;
public McpOauthScopeHandlerFilterFunction(
@Qualifier("mcpToolScopes") Map<String, List<String>> toolScopes,
@Qualifier("mcpServerJsonMapper") JsonMapper jsonMapper
) {
this.toolScopes = toolScopes;
this.jsonMapper = new JacksonMcpJsonMapper(jsonMapper);
}
@Override
public ServerResponse filter(ServerRequest request, HandlerFunction<ServerResponse> next) throws Exception {
if (request.method() != HttpMethod.POST) {
return next.handle(request);
}
final var body = request.body(String.class);
final var message = McpSchema.deserializeJsonRpcMessage(this.jsonMapper, body);
if (message instanceof McpSchema.JSONRPCRequest jsonrpcRequest && McpSchema.METHOD_TOOLS_CALL.equals(jsonrpcRequest.method())) {
final var callToolRequest = this.jsonMapper.convertValue(jsonrpcRequest.params(), McpSchema.CallToolRequest.class);
assertScopes(toolScopes.getOrDefault(callToolRequest.name(), List.of()));
}
return next.handle(ServerRequest.from(request).body(body).build());
}
private void assertScopes(List<String> requiredScopes) {
final var givenAuthorities = Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
.map(Authentication::getAuthorities)
.map(Collection::stream)
.orElse(Stream.empty())
.map(GrantedAuthority::getAuthority)
.filter(Objects::nonNull)
.collect(Collectors.toUnmodifiableSet());
final var areRequiredScopesPresent = requiredScopes.stream().map(scope -> "SCOPE_" + scope).allMatch(givenAuthorities::contains);
if (!areRequiredScopesPresent) {
throw new OAuth2AuthenticationException(BearerTokenErrors.insufficientScope("missing scope(s)", String.join(" ", requiredScopes)));
}
}
}
@Bean(name = "webMvcStreamableServerRouterFunction")
public RouterFunction<ServerResponse> webMvcStreamableServerRouterFunction(
WebMvcStreamableServerTransportProvider webMvcProvider,
McpOauthScopeHandlerFilterFunction mcpOauthScopeHandlerFilterFunction
) {
return webMvcProvider.getRouterFunction().filter(mcpOauthScopeHandlerFilterFunction);
}
mcpToolScopes holds a list of required oauth scopes for each tool.
I also added a custom @McpRequiredOauthScopes annotation that is used to create the mcpToolScopes map:
@Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface McpRequiredOauthScopes {
String[] value() default {};
}
@Bean(name = "mcpToolScopes")
public Map<String, List<String>> mcpToolScopes(McpServerAnnotationScannerAutoConfiguration.ServerMcpAnnotatedBeans beansWithMcpMethodAnnotations) {
Function<Method, String> getName = method -> method.getAnnotation(McpTool.class).name();
Function<Method, List<String>> getScopes = method -> List.of(method.getAnnotation(McpRequiredOauthScopes.class).value());
return beansWithMcpMethodAnnotations.getBeansByAnnotation(McpTool.class).stream()
.flatMap(bean -> Arrays.stream(AnnotationProviderUtil.beanMethods(bean)))
.filter(method -> method.isAnnotationPresent(McpTool.class))
.filter(method -> method.isAnnotationPresent(McpRequiredOauthScopes.class))
.collect(Collectors.toUnmodifiableMap(getName, getScopes));
}
It then can be used like this:
@Component
public class EchoTools {
@McpRequiredOauthScopes({"foo", "bar"})
@McpTool(name = "echo", description = "Echo the input string")
public String echo(@McpToolParam(description = "input string", required = true) String str ) {
return "echo: " + str;
}
}
This can easily be expanded to support oauth scopes on resources too.