Skip to content

Commit d3e5aed

Browse files
author
Tarun Agarwal
committed
Add request-scoped notifier factory to modern server
Allow applications to wrap the default async notifier using the request context. Preserve permissive defaults and apply customization to sync and async streaming handlers. Report factory failures through the existing streaming error path.
1 parent 2aab403 commit d3e5aed

4 files changed

Lines changed: 187 additions & 9 deletions

File tree

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@
88

99
/**
1010
* Emits request-scoped notifications from inside the body of a streaming
11-
* {@link McpAsyncResponse}.
11+
* {@link McpAsyncResponse}. Customize notification policy through
12+
* {@link McpServer.Builder#notifierFactory}.
1213
*
1314
* @author Dariusz Jędrzejczyk
1415
*/

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

Lines changed: 35 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
import java.util.Map;
1313
import java.util.Optional;
1414
import java.util.Set;
15+
import java.util.function.BiFunction;
1516

1617
import io.modelcontextprotocol.common.McpTransportContext;
1718
import io.modelcontextprotocol.json.McpJsonDefaults;
@@ -72,16 +73,20 @@ public final class McpServer implements McpRequestManager {
7273

7374
private final SubscriptionsFeature subscriptionsFeature;
7475

76+
private final BiFunction<McpRequestContext, McpAsyncNotifier, McpAsyncNotifier> notifierFactory;
77+
7578
private McpServer(Implementation serverInfo, List<String> supportedVersions, McpJsonMapper jsonMapper,
7679
Map<String, McpFeature> features, Set<String> inputRequiredMethods, RequestStateCodec requestStateCodec,
77-
SubscriptionsFeature subscriptionsFeature) {
80+
SubscriptionsFeature subscriptionsFeature,
81+
BiFunction<McpRequestContext, McpAsyncNotifier, McpAsyncNotifier> notifierFactory) {
7882
this.serverInfo = serverInfo;
7983
this.supportedVersions = supportedVersions;
8084
this.jsonMapper = jsonMapper;
8185
this.features = features;
8286
this.inputRequiredMethods = inputRequiredMethods;
8387
this.requestStateCodec = requestStateCodec;
8488
this.subscriptionsFeature = subscriptionsFeature;
89+
this.notifierFactory = notifierFactory;
8590
}
8691

8792
public static Builder builder() {
@@ -218,8 +223,11 @@ private Flux<JSONRPCMessage> stream(McpRequestContext ctx, McpAsyncResponse.Body
218223
// Deferred: the body must not run before the transport has started the stream.
219224
return Flux.defer(() -> {
220225
Sinks.Many<JSONRPCNotification> sink = Sinks.many().unicast().onBackpressureBuffer();
221-
DefaultAsyncNotifier notifier = new DefaultAsyncNotifier(ctx, sink);
222-
Mono<JSONRPCMessage> terminal = Mono.defer(() -> body.run(notifier))
226+
Mono<JSONRPCMessage> terminal = Mono.defer(() -> {
227+
McpAsyncNotifier notifier = this.notifierFactory.apply(ctx, new DefaultAsyncNotifier(ctx, sink));
228+
Assert.notNull(notifier, "notifierFactory must not return null");
229+
return body.run(notifier);
230+
})
223231
.map(result -> (JSONRPCMessage) resultResponse(ctx, result))
224232
.switchIfEmpty(Mono.fromSupplier(() -> bug(ctx, "Streaming body completed without a result")))
225233
// The stream has already started, so a failure can only be reported
@@ -346,6 +354,9 @@ public static final class Builder {
346354

347355
private McpChangePublisher changePublisher;
348356

357+
private BiFunction<McpRequestContext, McpAsyncNotifier, McpAsyncNotifier> notifierFactory = (ctx,
358+
notifier) -> notifier;
359+
349360
private Builder() {
350361
}
351362

@@ -392,6 +403,26 @@ public Builder subscriptions(McpChangePublisher publisher) {
392403
return this;
393404
}
394405

406+
/**
407+
* Customizes the notifier passed to streaming bodies, including sync handlers and
408+
* {@code subscriptions/listen}. The factory receives the request context and the
409+
* default notifier, which it may wrap to filter or reject notifications. By
410+
* default, the supplied notifier is used unchanged; no additional notification
411+
* policy is enforced.
412+
* <p>
413+
* Invoked once per stream subscription, before the body runs. The factory must be
414+
* thread-safe and return a non-null notifier. Factory failures are reported as
415+
* errors in the stream, whose HTTP status has already been committed.
416+
* @param notifierFactory the factory receiving the context and default notifier
417+
* @return this builder
418+
*/
419+
public Builder notifierFactory(
420+
BiFunction<McpRequestContext, McpAsyncNotifier, McpAsyncNotifier> notifierFactory) {
421+
Assert.notNull(notifierFactory, "notifierFactory must not be null");
422+
this.notifierFactory = notifierFactory;
423+
return this;
424+
}
425+
395426
/**
396427
* The codec used to seal/open MRTR {@code requestState}. Defaults to
397428
* {@link HmacRequestStateCodec#builder()}{@code .build()}.
@@ -459,7 +490,7 @@ public McpServer build() {
459490
: HmacRequestStateCodec.builder().jsonMapper(mapper).build();
460491

461492
return new McpServer(this.serverInfo, this.supportedVersions, mapper, Map.copyOf(byMethod),
462-
Set.copyOf(inputRequiredMethods), codec, subscriptionsFeature);
493+
Set.copyOf(inputRequiredMethods), codec, subscriptionsFeature, this.notifierFactory);
463494
}
464495

465496
}

‎mcp-core/src/test/java/io/modelcontextprotocol/modern/server/McpServerTests.java‎

Lines changed: 122 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import java.util.Map;
1010
import java.util.Set;
1111
import java.util.concurrent.atomic.AtomicBoolean;
12+
import java.util.concurrent.atomic.AtomicInteger;
1213
import java.util.function.BiFunction;
1314

1415
import io.modelcontextprotocol.modern.JsonRpc.JSONRPCNotification;
@@ -26,6 +27,8 @@
2627
import io.modelcontextprotocol.modern.McpSchema.TextContent;
2728
import io.modelcontextprotocol.spec.json.gson.GsonMcpJsonMapper;
2829
import org.junit.jupiter.api.Test;
30+
import org.junit.jupiter.params.ParameterizedTest;
31+
import org.junit.jupiter.params.provider.ValueSource;
2932
import reactor.core.publisher.Mono;
3033
import reactor.test.StepVerifier;
3134

@@ -297,10 +300,11 @@ void streamingBodyRunsOnlyOnceTheStreamIsSubscribed() {
297300

298301
@Test
299302
void streamingBodyNotificationsPrecedeTheResult() {
300-
McpServer server = baseBuilder().feature(feature("tools/call",
301-
(ctx, params) -> Mono.just(McpAsyncResponse.streaming(notifier -> notifier.progress(1.0, 2.0, "half")
302-
.then(notifier.progress(2.0, 2.0, "done"))
303-
.thenReturn(ok())))))
303+
McpServer server = baseBuilder().feature(feature("tools/call", (ctx, params) -> Mono
304+
.just(McpAsyncResponse.streaming(notifier -> notifier.progress(1.0, 2.0, "half")
305+
.then(notifier.progress(2.0, 2.0, "done"))
306+
.then(notifier.notify(McpSchema.METHOD_NOTIFICATION_MESSAGE, Map.of("level", "info", "data", "hello")))
307+
.thenReturn(ok())))))
304308
.build();
305309

306310
McpTransportResponse invocation = invoke(server, request("tools/call", meta(MetaKeys.PROGRESS_TOKEN, "tok-1")))
@@ -309,6 +313,8 @@ void streamingBodyNotificationsPrecedeTheResult() {
309313
StepVerifier.create(((McpTransportResponse.Streaming) invocation).messages())
310314
.expectNextMatches(msg -> msg instanceof JSONRPCNotification)
311315
.expectNextMatches(msg -> msg instanceof JSONRPCNotification)
316+
.expectNextMatches(msg -> msg instanceof JSONRPCNotification notification
317+
&& notification.method().equals(McpSchema.METHOD_NOTIFICATION_MESSAGE))
312318
.expectNextMatches(msg -> msg instanceof JSONRPCResponse)
313319
.verifyComplete();
314320
}
@@ -328,6 +334,118 @@ void progressIsSuppressedWithoutProgressToken() {
328334
.verifyComplete();
329335
}
330336

337+
@Test
338+
void notifierFactoryFiltersUsingEachRequestsContextAndPreservesProgress() {
339+
AtomicInteger created = new AtomicInteger();
340+
McpServer server = baseBuilder().notifierFactory((ctx, delegate) -> {
341+
created.incrementAndGet();
342+
return new McpAsyncNotifier() {
343+
@Override
344+
public Mono<Void> progress(double progress, Double total, String message) {
345+
return delegate.progress(progress, total, message);
346+
}
347+
348+
@Override
349+
public Mono<Void> notify(String method, Object params) {
350+
if (McpSchema.METHOD_NOTIFICATION_MESSAGE.equals(method)
351+
&& !ctx.meta().containsKey(MetaKeys.LOG_LEVEL)) {
352+
return Mono.empty();
353+
}
354+
return delegate.notify(method, params);
355+
}
356+
};
357+
})
358+
.feature(feature("tools/call",
359+
(ctx, params) -> Mono.just(McpAsyncResponse.streaming(notifier -> notifier
360+
.notify(McpSchema.METHOD_NOTIFICATION_MESSAGE, Map.of("level", "info", "data", "hello"))
361+
.then(notifier.progress(1.0, 1.0, "done"))
362+
.thenReturn(ok())))))
363+
.build();
364+
365+
var quiet = (McpTransportResponse.Streaming) invoke(server,
366+
request("tools/call", meta(MetaKeys.PROGRESS_TOKEN, "quiet")))
367+
.block();
368+
var logging = (McpTransportResponse.Streaming) invoke(server, new JSONRPCRequest("tools/call", 2,
369+
Map.of("_meta", meta(MetaKeys.PROGRESS_TOKEN, "logging", MetaKeys.LOG_LEVEL, "info"))))
370+
.block();
371+
372+
assertThat(created).hasValue(0);
373+
StepVerifier.create(quiet.messages())
374+
.expectNextMatches(msg -> msg instanceof JSONRPCNotification notification
375+
&& notification.method().equals(McpSchema.METHOD_NOTIFICATION_PROGRESS))
376+
.expectNextMatches(msg -> msg instanceof JSONRPCResponse response && response.error() == null)
377+
.verifyComplete();
378+
StepVerifier.create(logging.messages())
379+
.expectNextMatches(msg -> msg instanceof JSONRPCNotification notification
380+
&& notification.method().equals(McpSchema.METHOD_NOTIFICATION_MESSAGE))
381+
.expectNextMatches(msg -> msg instanceof JSONRPCNotification notification
382+
&& notification.method().equals(McpSchema.METHOD_NOTIFICATION_PROGRESS))
383+
.expectNextMatches(msg -> msg instanceof JSONRPCResponse response && response.error() == null)
384+
.verifyComplete();
385+
assertThat(created).hasValue(2);
386+
}
387+
388+
@ParameterizedTest
389+
@ValueSource(booleans = { false, true })
390+
void invalidNotifierFactoryIsAnInternalErrorInStream(boolean returnsNull) {
391+
AtomicBoolean ran = new AtomicBoolean();
392+
McpServer server = baseBuilder().notifierFactory((ctx, delegate) -> {
393+
if (returnsNull) {
394+
return null;
395+
}
396+
throw new IllegalStateException("factory failed");
397+
}).feature(feature("tools/call", (ctx, params) -> Mono.just(McpAsyncResponse.streaming(notifier -> {
398+
ran.set(true);
399+
return Mono.just(ok());
400+
})))).build();
401+
402+
var invocation = (McpTransportResponse.Streaming) invoke(server, request("tools/call", meta())).block();
403+
404+
StepVerifier.create(invocation.messages())
405+
.expectNextMatches(msg -> msg instanceof JSONRPCResponse response
406+
&& response.error().code() == ErrorCodes.INTERNAL_ERROR)
407+
.verifyComplete();
408+
assertThat(ran).isFalse();
409+
}
410+
411+
@Test
412+
void notifierFactoryCanRejectANotificationWithAnMcpError() {
413+
McpServer server = baseBuilder().notifierFactory((ctx, delegate) -> new McpAsyncNotifier() {
414+
@Override
415+
public Mono<Void> progress(double progress, Double total, String message) {
416+
return delegate.progress(progress, total, message);
417+
}
418+
419+
@Override
420+
public Mono<Void> notify(String method, Object params) {
421+
return Mono.error(McpException.invalidParams("Notification not allowed"));
422+
}
423+
})
424+
.feature(feature("tools/call",
425+
(ctx, params) -> Mono.just(McpAsyncResponse
426+
.streaming(notifier -> notifier.notify("extension/forbidden", Map.of()).thenReturn(ok())))))
427+
.build();
428+
429+
var invocation = (McpTransportResponse.Streaming) invoke(server, request("tools/call", meta())).block();
430+
431+
StepVerifier.create(invocation.messages())
432+
.expectNextMatches(msg -> msg instanceof JSONRPCResponse response
433+
&& response.error().code() == ErrorCodes.INVALID_PARAMS
434+
&& response.error().message().equals("Notification not allowed"))
435+
.verifyComplete();
436+
}
437+
438+
@Test
439+
void notifierFactoryIsNotInvokedForSingleResults() {
440+
McpServer server = baseBuilder().notifierFactory((ctx, delegate) -> {
441+
throw new IllegalStateException("No notifier needed");
442+
}).feature(echoFeature("tools/call")).build();
443+
444+
StepVerifier.create(respond(server, request("tools/call", meta())))
445+
.assertNext(response -> assertThat(response.error()).isNull())
446+
.verifyComplete();
447+
}
448+
331449
@Test
332450
void streamingBodyExceptionIsAnInternalErrorInStream() {
333451
McpServer server = baseBuilder()

‎mcp-core/src/test/java/io/modelcontextprotocol/modern/server/feature/ToolsFeatureTests.java‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
import io.modelcontextprotocol.modern.server.McpTransportResponse;
3535
import io.modelcontextprotocol.modern.server.McpRequestContext;
3636
import io.modelcontextprotocol.modern.server.McpAsyncResponse;
37+
import io.modelcontextprotocol.modern.server.McpAsyncNotifier;
3738
import io.modelcontextprotocol.modern.server.McpServer;
3839
import io.modelcontextprotocol.modern.server.McpSyncResponse;
3940
import io.modelcontextprotocol.modern.server.ModernTestFixtures;
@@ -322,6 +323,33 @@ void blockingCallerRunsSyncStreamingHandlerOnItsOwnThreadAndReceivesNotification
322323
assertThat(greetingText(delivered.get(1))).isEqualTo("hello alice");
323324
}
324325

326+
@Test
327+
void notifierFactoryCustomizesSyncStreamingHandlers() {
328+
AtomicReference<String> handlerThread = new AtomicReference<>();
329+
List<JSONRPCMessage> delivered = new CopyOnWriteArrayList<>();
330+
McpServer server = baseBuilder().notifierFactory((ctx, delegate) -> new McpAsyncNotifier() {
331+
@Override
332+
public Mono<Void> progress(double progress, Double total, String message) {
333+
return delegate.notify("extension/progress", Map.of("requestId", ctx.requestId()));
334+
}
335+
336+
@Override
337+
public Mono<Void> notify(String method, Object params) {
338+
return delegate.notify(method, params);
339+
}
340+
}).feature(tools(streamingGreetingRepo(ctx -> "alice", handlerThread, delivered, new AtomicInteger()))).build();
341+
342+
callStreaming(server.handleBlocking(McpTransportContext.EMPTY, callEcho()), delivered);
343+
344+
assertThat(handlerThread.get()).isEqualTo(Thread.currentThread().getName());
345+
assertThat(delivered).hasSize(2);
346+
assertThat(delivered.get(0)).isInstanceOfSatisfying(JSONRPCNotification.class, notification -> {
347+
assertThat(notification.method()).isEqualTo("extension/progress");
348+
assertThat(notification.params()).isEqualTo(Map.of("requestId", callEcho().id()));
349+
});
350+
assertThat(greetingText(delivered.get(1))).isEqualTo("hello alice");
351+
}
352+
325353
@Test
326354
@SuppressWarnings("unchecked")
327355
void blockingCallerRunsSyncListOnItsOwnThread() {

0 commit comments

Comments
 (0)