Skip to content

Add filtering for MCP tool list - #1108

Open
Kehrlann wants to merge 1 commit into
mainfrom
dgarnier/tool-filters
Open

Add filtering for MCP tool list#1108
Kehrlann wants to merge 1 commit into
mainfrom
dgarnier/tool-filters

Conversation

@Kehrlann

Copy link
Copy Markdown
Contributor

Context

The SDK lacks capabilities for dynamically returning tools, resources, prompts, etc (see #578).

A full implementation in the current state (2.x, 2025-11-25) spec would be complex, as it'd need to target [sync | async] x [stateful | stateless] = 4 variants. We'd need to address the bridges between sync and async, make it coexist with current server's tool management (array list of tools, .addTool method).

We are currently focusing on the implementation of the 2026-07-28 spec, which will bring an entirely new, breaking API. It would be a perfect opportunity to bring in repositories as described in #578 .

In the meantime, we recognize users have been asking for capabilities for a long time. The majority of the asks are centered around filtering the list of tools (#997 , #525, examples in #593, #746, #608, etc). While we recognize there are other asks (dynamic tool generation, other primitives than tools), we think they'd be better addressed by a full #578 implementation. In the meantime, we decided exposing filter capabilities for tools, in this PR.

Scope

This PR is focused on tool list filtering only, while opening the door for filtering other resources if necessary. It addresses filtering in every variant mentioned above.

⚠️⚠️ The filtering only applies to tools listing. It does NOT apply to tool calling, as this can already be achieved in the tool handler. Similarly, it does NOT apply to notifications/tools/list_changed notifications, as these notifications are session-scoped, and not request-scoped. It is recommended that you DO NOT use notifications when using filters.

Closes #997
Closes #525 (with caveats, the main discussion is in #578)
Closes #593 (with caveats, the main discussion is in #578)

Signed-off-by: Daniel Garnier-Moiroux <git@garnier.wf>
@Kehrlann
Kehrlann force-pushed the dgarnier/tool-filters branch from 08b9fdd to 836277b Compare August 27, 2026 13:41

@tzolov tzolov left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @Kehrlann,
please check my comments

* @return This builder instance for method chaining
* @see #addToolFilter(McpAsyncListFilter)
*/
public AsyncSpecification<S> toolFilters(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not convinced about the practicality of such flexibility. It exposes the builder's internal mutable list. Perhaps a plain toolFilters(List<McpSyncListFilter<Tool>>), or deferring the method until demand appears, would be the safer?

* @return This builder instance for method chaining
* @see #addToolFilter(McpSyncListFilter)
*/
public SyncSpecification<S> toolFilters(Consumer<List<McpSyncListFilter<McpSchema.Tool>>> toolFiltersConsumer) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same like the AsyncSpecification.toolFilters

* @return This builder instance for method chaining
* @see #addToolFilter(McpAsyncListFilter)
*/
public StatelessAsyncSpecification toolFilters(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same like the AsyncSpecification.toolFilters

* @return This builder instance for method chaining
* @see #addToolFilter(McpSyncListFilter)
*/
public StatelessSyncSpecification toolFilters(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same like the AsyncSpecification.toolFilters

* contain {@code null} elements.
*/
static <T> McpAsyncListFilter<T> and(List<McpAsyncListFilter<T>> filters) {
Assert.noNullElements(filters, "filters must not contain null elements");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this assert can go after the if (filters == null || filters.isEmpty()) check.

// 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))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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?

Comment thread docs/server.md

```java
// one authorization lookup, shared by every tool tested in this request
.contextExtractor(request -> McpTransportContext.create(

Copy link
Copy Markdown
Contributor

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's
SecurityContextHolder, MDC, custom ThreadLocal holders) 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:

```java
// transport builder: one authorization lookup, on the request thread,
// shared by every tool tested in this request
var transportProvider = HttpServletStreamableServerTransportProvider.builder()
    .contextExtractor(request -> McpTransportContext.create(
            Map.of("perms", introspect(request.getHeader("Authorization")))))
    // ...
    .build();

// server builder: the filter reads only the extracted context
McpServer.sync(transportProvider)
    .addToolFilter((context, tool) ->
            ((Set<String>) context.get("perms")).contains(tool.name()))
    .build();
```

* <p>
* A hidden tool is omitted from listings only. It remains callable by name, so
* enforce permissions in the tool's call handler. Tools are NOT hidden from
* {@code notifications/tools/list_changed}, as it is a per-client context rather

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stateless servers don't support notifications

* <p>
* A hidden tool is omitted from listings only. It remains callable by name, so
* enforce permissions in the tool's call handler. Tools are NOT hidden from
* {@code notifications/tools/list_changed}, as it is a per-client context rather

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no notifications support for the stateless servers

* 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.
*

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add "Unless immediateExecution is enabled, this filter runs on a shared scheduler thread, not the request thread. Thread-bound request state (SecurityContextHolder, MDC, custom ThreadLocal holders) is not visible here — resolve it in your transport's contextExtractor and read it from the transportContext parameter."
The same warning on the sync builders' addToolFilter.
(AI suggestion)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/server enhancement New feature or request

Projects

None yet

2 participants