Skip to content

Commit 66a7f61

Browse files
committed
Restrict resource subscriptions
- Closes #1307 Signed-off-by: Daniel Garnier-Moiroux <git@garnier.wf>
1 parent 6a28ebb commit 66a7f61

5 files changed

Lines changed: 332 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: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
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 part of {@code honoured} this caller may receive, typically {@code honoured}
22+
* with some fields removed or some list elements left out. The restriction can only
23+
* narrow: the server keeps only the part of the returned filter that it honours, so it
24+
* cannot grant notifications the client didn't request or the server cannot deliver.
25+
* Anything returned beyond {@code honoured} is ignored and logged as a warning. An empty
26+
* {@code Mono} honours nothing.
27+
* <p>
28+
* The restriction runs once, when the stream opens, and the filter it leaves is
29+
* acknowledged to the client and applies for the whole life of the stream. A change in
30+
* what the caller may receive, such as a revoked permission, isn't applied to streams
31+
* that are already open: it takes effect on the caller's next
32+
* {@code subscriptions/listen}. When the server honours nothing of the request, the
33+
* restriction isn't called: the stream opens with an empty acknowledgement and delivers
34+
* nothing, so there is nothing to narrow or refuse.
35+
* <p>
36+
* To refuse the request altogether, return {@link Mono#error} or throw an
37+
* {@link McpException}; it is answered with its error, before any stream opens. The spec
38+
* defines no permission error code, so use for example
39+
* {@code new McpException(ErrorCodes.INVALID_REQUEST, "Not permitted")}, with the same
40+
* message whichever subscription is denied, so that the error does not tell the caller
41+
* which URI it may not access. Any other exception is answered as an internal error.
42+
* <p>
43+
* The restriction runs while the request is being handled, so it must not block the
44+
* calling thread. Run blocking work, such as a permission lookup, on a scheduler that
45+
* allows it, except where the request is already handled on a thread that may block:
46+
* <pre>{@code
47+
* (ctx, requested, honoured) -> {
48+
* Mono<SubscriptionFilter> restricted = Mono.fromCallable(() -> {
49+
* Principal principal = (Principal) ctx.transportContext().get("principal");
50+
* List<String> allowed = honoured.resourceSubscriptionsOrEmpty()
51+
* .stream()
52+
* .filter(uri -> permissions.canWatch(principal, uri)) // blocking
53+
* .toList();
54+
* return honoured.with(SubscriptionFilter.RESOURCE_SUBSCRIPTIONS,
55+
* allowed.isEmpty() ? null : allowed);
56+
* });
57+
* return ctx.isBlocking() ? restricted : restricted.subscribeOn(Schedulers.boundedElastic());
58+
* }
59+
* }</pre>
60+
*
61+
* @author Daniel Garnier-Moiroux
62+
*/
63+
@FunctionalInterface
64+
public interface SubscriptionRestriction {
65+
66+
/**
67+
* The subscriptions this caller may receive.
68+
* @param ctx the {@code subscriptions/listen} request, including the transport
69+
* context that identifies the caller
70+
* @param requested the filter the client sent
71+
* @param honoured the part of {@code requested} the server and its features agree to
72+
* honour
73+
* @return the subscriptions this caller may receive, of which the server keeps the
74+
* part it honours
75+
*/
76+
Mono<SubscriptionFilter> restrict(McpRequestContext ctx, SubscriptionFilter requested, SubscriptionFilter honoured);
77+
78+
}

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

Lines changed: 59 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,54 @@ 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. Not
203+
* called when nothing is honoured: it could only narrow to nothing, and may do costly
204+
* work such as a permission lookup.
205+
*/
206+
private Mono<SubscriptionFilter> restricted(McpRequestContext ctx, SubscriptionFilter requested,
207+
SubscriptionFilter honoured) {
208+
if (honoured.isEmpty()) {
209+
return Mono.just(SubscriptionFilter.EMPTY);
210+
}
211+
return Mono.defer(() -> this.restriction.restrict(ctx, requested, honoured))
212+
.defaultIfEmpty(SubscriptionFilter.EMPTY)
213+
.map(restricted -> intersection(honoured, restricted));
214+
}
215+
216+
/**
217+
* The part of {@code restricted} that {@code honoured} covers: the restriction may
218+
* only narrow, so that the stream never acknowledges a notification the client didn't
219+
* request or that the server can't deliver. A list keeps the elements of
220+
* {@code honoured}'s list that {@code restricted}'s list contains, and any other
221+
* value, flags included, is kept if {@code restricted} has the same value.
222+
*/
223+
private static SubscriptionFilter intersection(SubscriptionFilter honoured, SubscriptionFilter restricted) {
224+
if (honoured == restricted) {
225+
return restricted;
226+
}
227+
SubscriptionFilter widened = restricted.missingFrom(honoured);
228+
if (!widened.isEmpty()) {
229+
logger.warn("Ignoring subscriptions the restriction added beyond what the server honours: {}", widened);
230+
}
231+
Map<String, Object> kept = new LinkedHashMap<>();
232+
honoured.fields().forEach((field, value) -> {
233+
Object agreed = restricted.get(field);
234+
if (value instanceof List<?> elements) {
235+
List<?> agreedElements = agreed instanceof List<?> list ? list : List.of();
236+
List<?> both = elements.stream().filter(agreedElements::contains).toList();
237+
if (!both.isEmpty()) {
238+
kept.put(field, both);
239+
}
240+
}
241+
else if (value.equals(agreed)) {
242+
kept.put(field, value);
243+
}
244+
});
245+
return SubscriptionFilter.of(kept);
246+
}
247+
192248
/**
193249
* The params of the notification for {@code change}, with the stream's {@code _meta},
194250
* 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)