Skip to content

Fix Streamable HTTP WebClient GET SSE handling #318

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

Merged
merged 1 commit into from
Jun 16, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -125,13 +125,14 @@ public Mono<Void> connect(Function<Mono<McpSchema.JSONRPCMessage>, Mono<McpSchem
}

private DefaultMcpTransportSession createTransportSession() {
Supplier<Publisher<Void>> onClose = () -> {
DefaultMcpTransportSession transportSession = this.activeSession.get();
return transportSession.sessionId().isEmpty() ? Mono.empty()
: webClient.delete().uri(this.endpoint).headers(httpHeaders -> {
httpHeaders.add("mcp-session-id", transportSession.sessionId().get());
}).retrieve().toBodilessEntity().doOnError(e -> logger.info("Got response {}", e)).then();
};
Function<String, Publisher<Void>> onClose = sessionId -> sessionId == null ? Mono.empty()
: webClient.delete().uri(this.endpoint).headers(httpHeaders -> {
httpHeaders.add("mcp-session-id", sessionId);
})
.retrieve()
.toBodilessEntity()
.doOnError(e -> logger.warn("Got error when closing transport", e))
.then();
return new DefaultMcpTransportSession(onClose);
}

Expand Down Expand Up @@ -192,6 +193,7 @@ private Mono<Disposable> reconnect(McpTransportStream<Disposable> stream) {
})
.exchangeToFlux(response -> {
if (isEventStream(response)) {
logger.debug("Established SSE stream via GET");
return eventStream(stream, response);
}
else if (isNotAllowed(response)) {
Expand All @@ -208,6 +210,7 @@ else if (isNotFound(response)) {
}).flux();
}
})
.flatMap(jsonrpcMessage -> this.handler.get().apply(Mono.just(jsonrpcMessage)))
.onErrorComplete(t -> {
this.handleException(t);
return true;
Expand Down Expand Up @@ -274,6 +277,7 @@ public Mono<Void> sendMessage(McpSchema.JSONRPCMessage message) {
else {
MediaType mediaType = contentType.get();
if (mediaType.isCompatibleWith(MediaType.TEXT_EVENT_STREAM)) {
logger.debug("Established SSE stream via POST");
// communicate to caller that the message was delivered
sink.success();
// starting a stream
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
import io.modelcontextprotocol.spec.McpSchema.ClientCapabilities;
import io.modelcontextprotocol.spec.McpSchema.CreateMessageRequest;
import io.modelcontextprotocol.spec.McpSchema.CreateMessageResult;
import io.modelcontextprotocol.spec.McpSchema.ElicitRequest;
import io.modelcontextprotocol.spec.McpSchema.ElicitResult;
import io.modelcontextprotocol.spec.McpSchema.GetPromptRequest;
import io.modelcontextprotocol.spec.McpSchema.Prompt;
import io.modelcontextprotocol.spec.McpSchema.Resource;
Expand Down Expand Up @@ -77,7 +79,9 @@ McpAsyncClient client(McpClientTransport transport, Function<McpClient.AsyncSpec
McpClient.AsyncSpec builder = McpClient.async(transport)
.requestTimeout(getRequestTimeout())
.initializationTimeout(getInitializationTimeout())
.capabilities(ClientCapabilities.builder().roots(true).build());
.sampling(req -> Mono.just(new CreateMessageResult(McpSchema.Role.USER,
new McpSchema.TextContent("Oh, hi!"), "modelId", CreateMessageResult.StopReason.END_TURN)))
.capabilities(ClientCapabilities.builder().roots(true).sampling().build());
builder = customizer.apply(builder);
client.set(builder.build());
}).doesNotThrowAnyException();
Expand Down Expand Up @@ -189,6 +193,22 @@ void testCallTool() {
});
}

@Test
void testSampling() {
withClient(createMcpTransport(), mcpAsyncClient -> {
CallToolRequest callToolRequest = new CallToolRequest("sampleLLM",
Map.of("prompt", "Hello MCP Spring AI!"));
StepVerifier.create(mcpAsyncClient.initialize().then(mcpAsyncClient.callTool(callToolRequest)))
.consumeNextWith(callToolResult -> {
assertThat(callToolResult).isNotNull().satisfies(result -> {
assertThat(result.content()).isNotNull();
assertThat(result.isError()).isNull();
});
})
.verifyComplete();
});
}

@Test
void testCallToolWithInvalidTool() {
withClient(createMcpTransport(), mcpAsyncClient -> {
Expand Down Expand Up @@ -424,6 +444,20 @@ void testInitializeWithSamplingCapability() {
});
}

@Test
void testInitializeWithElicitationCapability() {
Copy link
Member Author

Choose a reason for hiding this comment

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

Added this when synchronizing between mcp/src/test and mcp-test/src/main (the files should have the same contents) but the elicitation was not synchronized properly.

ClientCapabilities capabilities = ClientCapabilities.builder().elicitation().build();
ElicitResult elicitResult = ElicitResult.builder()
.message(ElicitResult.Action.ACCEPT)
.content(Map.of("foo", "bar"))
.build();
withClient(createMcpTransport(),
builder -> builder.capabilities(capabilities).elicitation(request -> Mono.just(elicitResult)),
client -> {
StepVerifier.create(client.initialize()).expectNextMatches(Objects::nonNull).verifyComplete();
});
}

@Test
void testInitializeWithAllCapabilities() {
var capabilities = ClientCapabilities.builder()
Expand All @@ -435,7 +469,11 @@ void testInitializeWithAllCapabilities() {
Function<CreateMessageRequest, Mono<CreateMessageResult>> samplingHandler = request -> Mono
.just(CreateMessageResult.builder().message("test").model("test-model").build());

withClient(createMcpTransport(), builder -> builder.capabilities(capabilities).sampling(samplingHandler),
Function<ElicitRequest, Mono<ElicitResult>> elicitationHandler = request -> Mono
.just(ElicitResult.builder().message(ElicitResult.Action.ACCEPT).content(Map.of("foo", "bar")).build());

withClient(createMcpTransport(),
builder -> builder.capabilities(capabilities).sampling(samplingHandler).elicitation(elicitationHandler),
client ->

StepVerifier.create(client.initialize()).assertNext(result -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
import java.util.function.Function;

/**
* Default implementation of {@link McpTransportSession} which manages the open
Expand All @@ -29,9 +29,9 @@ public class DefaultMcpTransportSession implements McpTransportSession<Disposabl

private final AtomicReference<String> sessionId = new AtomicReference<>();

private final Supplier<Publisher<Void>> onClose;
private final Function<String, Publisher<Void>> onClose;

public DefaultMcpTransportSession(Supplier<Publisher<Void>> onClose) {
public DefaultMcpTransportSession(Function<String, Publisher<Void>> onClose) {
this.onClose = onClose;
}

Expand Down Expand Up @@ -73,7 +73,8 @@ public void close() {

@Override
public Mono<Void> closeGracefully() {
return Mono.from(this.onClose.get()).then(Mono.fromRunnable(this.openConnections::dispose));
return Mono.from(this.onClose.apply(this.sessionId.get()))
.then(Mono.fromRunnable(this.openConnections::dispose));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,9 @@ McpAsyncClient client(McpClientTransport transport, Function<McpClient.AsyncSpec
McpClient.AsyncSpec builder = McpClient.async(transport)
.requestTimeout(getRequestTimeout())
.initializationTimeout(getInitializationTimeout())
.capabilities(ClientCapabilities.builder().roots(true).build());
.sampling(req -> Mono.just(new CreateMessageResult(McpSchema.Role.USER,
new McpSchema.TextContent("Oh, hi!"), "modelId", CreateMessageResult.StopReason.END_TURN)))
.capabilities(ClientCapabilities.builder().roots(true).sampling().build());
builder = customizer.apply(builder);
client.set(builder.build());
}).doesNotThrowAnyException();
Expand Down Expand Up @@ -192,6 +194,22 @@ void testCallTool() {
});
}

@Test
void testSampling() {
withClient(createMcpTransport(), mcpAsyncClient -> {
CallToolRequest callToolRequest = new CallToolRequest("sampleLLM",
Map.of("prompt", "Hello MCP Spring AI!"));
StepVerifier.create(mcpAsyncClient.initialize().then(mcpAsyncClient.callTool(callToolRequest)))
.consumeNextWith(callToolResult -> {
assertThat(callToolResult).isNotNull().satisfies(result -> {
assertThat(result.content()).isNotNull();
assertThat(result.isError()).isNull();
});
})
.verifyComplete();
});
}

@Test
void testCallToolWithInvalidTool() {
withClient(createMcpTransport(), mcpAsyncClient -> {
Expand Down