-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Add filtering for MCP tool list #1108
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| /* | ||
| * Copyright 2026-2026 the original author or authors. | ||
| */ | ||
|
|
||
| package io.modelcontextprotocol.server; | ||
|
|
||
| import java.util.List; | ||
|
|
||
| import io.modelcontextprotocol.common.McpTransportContext; | ||
| import io.modelcontextprotocol.spec.McpSchema.Tool; | ||
| import io.modelcontextprotocol.util.Assert; | ||
| import reactor.core.publisher.Flux; | ||
| import reactor.core.publisher.Mono; | ||
| import reactor.core.scheduler.Schedulers; | ||
|
|
||
| /** | ||
| * Decide per request whether a primitive is advertised in the corresponding listing, such | ||
| * as {@code tools/list}. | ||
| * <p> | ||
| * A primitive hidden by this filter is omitted from listings ONLY. It remains reachable | ||
| * through its own endpoint: a hidden tool called by name still executes. Permissions MUST | ||
| * be enforced in the primitive's handler. | ||
| * | ||
| * @author Daniel Garnier-Moiroux | ||
| * @see McpSyncListFilter | ||
| * @see McpTransportContextExtractor | ||
| */ | ||
| @FunctionalInterface | ||
| public interface McpAsyncListFilter<T> { | ||
|
|
||
| /** | ||
| * Whether the given primitive is visible to the caller of the current request. | ||
| * @param transportContext transport context containing, for example, HTTP headers or | ||
| * a resolved principal. Should never be {@code null}, but may | ||
| * {@link McpTransportContext#EMPTY} for transports that carry no per-request | ||
| * metadata, such as STDIO. | ||
| * @param primitive the primitive that is a candidate for inclusion in the listing, | ||
| * such as {@link Tool}. | ||
| * @return a publisher emitting {@code true} to include the primitive in the listing, | ||
| * {@code false} to omit it. Completing empty omits the primitive; erroring fails the | ||
| * listing request. | ||
| */ | ||
| Mono<Boolean> isVisible(McpTransportContext transportContext, T primitive); | ||
|
|
||
| /** | ||
| * Convert a potentially blocking, synchronous filter into an asynchronous one, | ||
| * offloading it to prevent accidental blocking of a non-blocking transport. | ||
| * @param filter the synchronous filter. MUST NOT be null. | ||
| * @param immediateExecution When true, do not offload work asynchronously. Do NOT set | ||
| * to true when the filter performs blocking I/O. | ||
| */ | ||
| static <T> McpAsyncListFilter<T> fromSync(McpSyncListFilter<T> filter, boolean immediateExecution) { | ||
| Assert.notNull(filter, "filter must not be null"); | ||
| return (transportContext, primitive) -> { | ||
| var visible = Mono.fromCallable(() -> filter.isVisible(transportContext, primitive)); | ||
| return immediateExecution ? visible : visible.subscribeOn(Schedulers.boundedElastic()); | ||
| }; | ||
| } | ||
|
|
||
| /** | ||
| * Combine multiple filters in a single AND-filter. An empty or {@code null} list | ||
| * makes everything visible, keeping listing on a single code path when nothing is | ||
| * configured. | ||
| * @param filters the filters to combine. May be {@code null} or empty, but MUST NOT | ||
| * contain {@code null} elements. | ||
| */ | ||
| static <T> McpAsyncListFilter<T> and(List<McpAsyncListFilter<T>> filters) { | ||
| Assert.noNullElements(filters, "filters must not contain null elements"); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this assert can go after the if (filters == null || filters.isEmpty()) check. |
||
| if (filters == null || filters.isEmpty()) { | ||
| return (transportContext, primitive) -> Mono.just(Boolean.TRUE); | ||
| } | ||
| if (filters.size() == 1) { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. With 1 filter, Mono.empty() stays empty; with 2+, empty is coerced to false: (e.g..defaultIfEmpty(Boolean.FALSE)). Not sure what downstream implications this might have. It will be cleaner to either remove the if (filters.size() == 1) optimization or use the same defaultIfEmpty strategy |
||
| return filters.get(0); | ||
| } | ||
| List<McpAsyncListFilter<T>> snapshot = List.copyOf(filters); | ||
| return (transportContext, primitive) -> Flux.fromIterable(snapshot) | ||
| .concatMap(filter -> filter.isVisible(transportContext, primitive).defaultIfEmpty(Boolean.FALSE)) | ||
| .all(Boolean.TRUE::equals); | ||
| } | ||
|
|
||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -118,6 +118,8 @@ public class McpAsyncServer { | |
|
|
||
| private final ConcurrentHashMap<String, Set<String>> resourceSubscriptions = new ConcurrentHashMap<>(); | ||
|
|
||
| private final McpAsyncListFilter<McpSchema.Tool> toolFilter; | ||
|
|
||
| private List<String> protocolVersions; | ||
|
|
||
| private McpUriTemplateManagerFactory uriTemplateManagerFactory = new DefaultMcpUriTemplateManagerFactory(); | ||
|
|
@@ -146,6 +148,7 @@ public class McpAsyncServer { | |
| this.uriTemplateManagerFactory = uriTemplateManagerFactory; | ||
| this.jsonSchemaValidator = jsonSchemaValidator; | ||
| this.validateToolInputs = validateToolInputs; | ||
| this.toolFilter = McpAsyncListFilter.and(features.toolFilters()); | ||
|
|
||
| Map<String, McpRequestHandler<?>> requestHandlers = prepareRequestHandlers(); | ||
| Map<String, McpNotificationHandler> notificationHandlers = prepareNotificationHandlers(features); | ||
|
|
@@ -177,6 +180,7 @@ public class McpAsyncServer { | |
| this.uriTemplateManagerFactory = uriTemplateManagerFactory; | ||
| this.jsonSchemaValidator = jsonSchemaValidator; | ||
| this.validateToolInputs = validateToolInputs; | ||
| this.toolFilter = McpAsyncListFilter.and(features.toolFilters()); | ||
|
|
||
| Map<String, McpRequestHandler<?>> requestHandlers = prepareRequestHandlers(); | ||
| Map<String, McpNotificationHandler> notificationHandlers = prepareNotificationHandlers(features); | ||
|
|
@@ -537,9 +541,13 @@ public Mono<Void> notifyToolsListChanged() { | |
|
|
||
| private McpRequestHandler<McpSchema.ListToolsResult> toolsListRequestHandler() { | ||
| return (exchange, params) -> { | ||
| List<Tool> tools = this.tools.stream().map(McpServerFeatures.AsyncToolSpecification::tool).toList(); | ||
|
|
||
| return Mono.just(McpSchema.ListToolsResult.builder(tools).build()); | ||
| // TODO: Implement pagination. Cursors must be computed over the filtered | ||
| // view, otherwise page offsets leak the number of hidden tools. | ||
| return Flux.fromIterable(this.tools) | ||
| .map(McpServerFeatures.AsyncToolSpecification::tool) | ||
| .filterWhen(tool -> this.toolFilter.isVisible(exchange.transportContext(), tool)) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The filterWhen doesn't catch any Mono.error or exceptions thrown in the filters and this error is propagated through the McpServerSession as McpError back to the MCP client. Not sure if it is safe to let the clients see those type of filter errors? |
||
| .collectList() | ||
| .map(tools -> McpSchema.ListToolsResult.builder(tools).build()); | ||
| }; | ||
| } | ||
|
|
||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I guess this is from the transport while the addToolFilter is from the server builder. Snippet gives the wrong impression that they belong to a common builder.
AI suggested a re-write like:
Sync filters also run on a shared scheduler thread — not the request thread — unless
immediateExecution(true)is set, so thread-bound request state (Spring Security'sSecurityContextHolder, MDC, customThreadLocalholders) is not visible inside the filter.For both reasons, resolve per-request state once in the transport's
contextExtractor,which does run on the request thread, and read only the extracted context in the filter: