Skip to content

Commit ad4779e

Browse files
committed
Restrict resource subscriptions
- Closes #1307 Signed-off-by: Daniel Garnier-Moiroux <git@garnier.wf>
1 parent 9142ebe commit ad4779e

5 files changed

Lines changed: 297 additions & 9 deletions

File tree

‎mcp-core/src/main/java/io/modelcontextprotocol/modern/server/McpServer.java‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -382,6 +382,8 @@ public static final class Builder {
382382

383383
private McpChangePublisher changePublisher;
384384

385+
private SubscriptionRestriction subscriptionRestriction = (ctx, requested, honoured) -> Mono.just(honoured);
386+
385387
private Builder() {
386388
}
387389

@@ -428,6 +430,20 @@ public Builder subscriptions(McpChangePublisher publisher) {
428430
return this;
429431
}
430432

433+
/**
434+
* Narrows, per request, the notifications {@code subscriptions/listen} agrees to
435+
* honour, for example to keep a caller from watching another principal's
436+
* resources. Only applies when {@link #subscriptions} is registered. Defaults to
437+
* honouring everything the server supports.
438+
* <p>
439+
* The restriction can only narrow the default honoured subscriptions.
440+
*/
441+
public Builder restrictSubscriptions(SubscriptionRestriction restriction) {
442+
Assert.notNull(restriction, "restriction must not be null");
443+
this.subscriptionRestriction = restriction;
444+
return this;
445+
}
446+
431447
/**
432448
* The codec used to seal/open MRTR {@code requestState}. Defaults to
433449
* {@link HmacRequestStateCodec#builder()}{@code .build()}.
@@ -479,7 +495,7 @@ public McpServer build() {
479495
SubscriptionsFeature subscriptionsFeature = null;
480496
if (this.changePublisher != null) {
481497
subscriptionsFeature = new SubscriptionsFeature(this.changePublisher, mapper, allFeatures,
482-
capabilitiesBuilder.hasTools(), capabilitiesBuilder.hasPrompts(),
498+
this.subscriptionRestriction, capabilitiesBuilder.hasTools(), capabilitiesBuilder.hasPrompts(),
483499
capabilitiesBuilder.hasResources(), capabilitiesBuilder.hasResourcesSubscribe());
484500
subscriptionsFeature.capabilities(capabilitiesBuilder);
485501
allFeatures.add(subscriptionsFeature);
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/*
2+
* Copyright 2026-2026 the original author or authors.
3+
*/
4+
5+
package io.modelcontextprotocol.modern.server;
6+
7+
import io.modelcontextprotocol.modern.McpException;
8+
import io.modelcontextprotocol.modern.McpSchema.SubscriptionFilter;
9+
import reactor.core.publisher.Mono;
10+
11+
/**
12+
* Narrows, per {@code subscriptions/listen} request, the notifications the server agrees
13+
* to honour, for example to keep a caller from watching resources that belong to another
14+
* principal. Registered through {@link McpServer.Builder#restrictSubscriptions}.
15+
* <p>
16+
* Change notifications are server-wide: a {@code notifications/resources/updated} for a
17+
* URI reaches every stream whose acknowledged filter contains that URI, whoever opened
18+
* it. Without a restriction, any caller may subscribe to any URI and learn when that
19+
* resource changes, though not its content.
20+
* <p>
21+
* Return the subscriptions this caller may receive: either a narrowed {@code honoured},
22+
* or everything the caller is allowed, whatever it requested. The server only keeps the
23+
* part of the returned filter that it honours, so the restriction cannot grant
24+
* notifications the client didn't request or the server cannot deliver. An empty
25+
* {@code Mono} honours nothing.
26+
* <p>
27+
* To refuse the request altogether, return {@link Mono#error} or throw an
28+
* {@link McpException}; it is answered with its error, before any stream opens. The spec
29+
* defines no permission error code, so use for example
30+
* {@code new McpException(ErrorCodes.INVALID_REQUEST, "Not permitted")}, with the same
31+
* message whichever subscription is denied, so that the error does not tell the caller
32+
* which URI it may not access. Any other exception is answered as an internal error.
33+
* <p>
34+
* The restriction runs while the request is being handled, so it must not block the
35+
* calling thread. Run blocking work, such as a permission lookup, on a scheduler that
36+
* allows it, except where the request is already handled on a thread that may block:
37+
* <pre>{@code
38+
* (ctx, requested, honoured) -> {
39+
* Mono<SubscriptionFilter> restricted = Mono.fromCallable(() -> {
40+
* Principal principal = (Principal) ctx.transportContext().get("principal");
41+
* List<String> allowed = honoured.resourceSubscriptionsOrEmpty()
42+
* .stream()
43+
* .filter(uri -> permissions.canWatch(principal, uri)) // blocking
44+
* .toList();
45+
* return honoured.with(SubscriptionFilter.RESOURCE_SUBSCRIPTIONS,
46+
* allowed.isEmpty() ? null : allowed);
47+
* });
48+
* return ctx.isBlocking() ? restricted : restricted.subscribeOn(Schedulers.boundedElastic());
49+
* }
50+
* }</pre>
51+
*
52+
* @author Daniel Garnier-Moiroux
53+
*/
54+
@FunctionalInterface
55+
public interface SubscriptionRestriction {
56+
57+
/**
58+
* The subscriptions this caller may receive.
59+
* @param ctx the {@code subscriptions/listen} request, including the transport
60+
* context that identifies the caller
61+
* @param requested the filter the client sent
62+
* @param honoured the part of {@code requested} the server and its features agree to
63+
* honour
64+
* @return the subscriptions this caller may receive, of which the server keeps the
65+
* part it honours
66+
*/
67+
Mono<SubscriptionFilter> restrict(McpRequestContext ctx, SubscriptionFilter requested, SubscriptionFilter honoured);
68+
69+
}

‎mcp-core/src/main/java/io/modelcontextprotocol/modern/server/SubscriptionsFeature.java‎

Lines changed: 52 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,8 @@
3434
* requested filter, then forwards the changes from a {@link McpChangePublisher} that the
3535
* honoured filter covers. The core fields are honoured for the primitives the server has;
3636
* other features honour the fields they define through
37-
* {@link McpFeature#honouredSubscriptions}.
37+
* {@link McpFeature#honouredSubscriptions}. A {@link SubscriptionRestriction} then
38+
* narrows the result per request.
3839
*
3940
* @author Dariusz Jędrzejczyk
4041
*/
@@ -55,6 +56,8 @@ final class SubscriptionsFeature implements McpFeature {
5556

5657
private final List<McpFeature> features;
5758

59+
private final SubscriptionRestriction restriction;
60+
5861
private final boolean hasTools;
5962

6063
private final boolean hasPrompts;
@@ -67,13 +70,17 @@ final class SubscriptionsFeature implements McpFeature {
6770

6871
/**
6972
* @param features the server's other features, asked for the fields they honour
73+
* @param restriction narrows what the server and its features honour, per request
7074
*/
7175
SubscriptionsFeature(McpChangePublisher publisher, McpJsonMapper jsonMapper, List<McpFeature> features,
72-
boolean hasTools, boolean hasPrompts, boolean hasResources, boolean hasResourcesSubscribe) {
76+
SubscriptionRestriction restriction, boolean hasTools, boolean hasPrompts, boolean hasResources,
77+
boolean hasResourcesSubscribe) {
7378
Assert.notNull(publisher, "publisher must not be null");
79+
Assert.notNull(restriction, "restriction must not be null");
7480
this.publisher = publisher;
7581
this.jsonMapper = jsonMapper;
7682
this.features = List.copyOf(features);
83+
this.restriction = restriction;
7784
this.hasTools = hasTools;
7885
this.hasPrompts = hasPrompts;
7986
this.hasResources = hasResources;
@@ -114,7 +121,8 @@ public Mono<McpAsyncResponse<Result>> handle(McpRequestContext ctx, Object param
114121
catch (McpException ex) {
115122
return Mono.error(ex);
116123
}
117-
return Mono.just(McpAsyncResponse.streaming(notifier -> listen(ctx, honoured, notifier)));
124+
return restricted(ctx, requested, honoured)
125+
.map(agreed -> McpAsyncResponse.streaming(notifier -> listen(ctx, agreed, notifier)));
118126
}
119127

120128
@Override
@@ -189,6 +197,47 @@ private SubscriptionFilter honoured(McpRequestContext ctx, SubscriptionFilter re
189197
return SubscriptionFilter.of(honoured);
190198
}
191199

200+
/**
201+
* What the restriction leaves of {@code honoured}. Deferred so that a restriction
202+
* throwing instead of returning an error {@code Mono} still rejects the request.
203+
*/
204+
private Mono<SubscriptionFilter> restricted(McpRequestContext ctx, SubscriptionFilter requested,
205+
SubscriptionFilter honoured) {
206+
return Mono.defer(() -> this.restriction.restrict(ctx, requested, honoured))
207+
.defaultIfEmpty(SubscriptionFilter.EMPTY)
208+
.map(restricted -> intersection(honoured, restricted));
209+
}
210+
211+
/**
212+
* The part of {@code restricted} that {@code honoured} covers: the restriction may
213+
* only narrow, so that the stream never acknowledges a notification the client didn't
214+
* request or that the server can't deliver. A flag is kept if both set it to
215+
* {@code true}, a list keeps the elements of {@code honoured}'s list that
216+
* {@code restricted}'s list contains, and any other value is kept if both have it.
217+
*/
218+
private static SubscriptionFilter intersection(SubscriptionFilter honoured, SubscriptionFilter restricted) {
219+
SubscriptionFilter widened = restricted.missingFrom(honoured);
220+
if (!widened.isEmpty()) {
221+
logger.warn("Ignoring subscriptions the restriction added beyond what the server honours: {}", widened);
222+
}
223+
Map<String, Object> kept = new LinkedHashMap<>();
224+
honoured.fields().forEach((field, value) -> {
225+
Object agreed = restricted.get(field);
226+
if (value instanceof List<?> elements) {
227+
List<?> agreedElements = agreed instanceof List<?> list ? list : List.of();
228+
List<?> both = elements.stream().filter(agreedElements::contains).toList();
229+
if (!both.isEmpty()) {
230+
kept.put(field, both);
231+
}
232+
}
233+
else if (value.equals(agreed)) {
234+
// Covers flags too: honoured only ever sets them to true.
235+
kept.put(field, value);
236+
}
237+
});
238+
return SubscriptionFilter.of(kept);
239+
}
240+
192241
/**
193242
* The params of the notification for {@code change}, with the stream's {@code _meta},
194243
* or {@code null} if they aren't an object.

‎mcp-core/src/main/java/io/modelcontextprotocol/modern/server/feature/McpChangeFeed.java‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,11 @@
1212
/**
1313
* An {@link McpChangeBroadcaster} and the {@link McpChangePublisher} its changes reach. A
1414
* change broadcast while no listen stream is active is dropped.
15+
* <p>
16+
* Changes are typically consumed in an
17+
* {@link io.modelcontextprotocol.modern.server.McpServer}, and broadcast to clients. They
18+
* are filtered by client request and further restricted through
19+
* {@link io.modelcontextprotocol.modern.server.SubscriptionRestriction}.
1520
*
1621
* @author Dariusz Jędrzejczyk
1722
*/

0 commit comments

Comments
 (0)