Skip to content

feat: implement MCP protocol version header support #404

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 2 commits into from
Jul 30, 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 @@ -23,6 +23,7 @@

import io.modelcontextprotocol.spec.DefaultMcpTransportSession;
import io.modelcontextprotocol.spec.DefaultMcpTransportStream;
import io.modelcontextprotocol.spec.HttpHeaders;
import io.modelcontextprotocol.spec.McpClientTransport;
import io.modelcontextprotocol.spec.McpError;
import io.modelcontextprotocol.spec.McpSchema;
Expand Down Expand Up @@ -66,6 +67,8 @@ public class WebClientStreamableHttpTransport implements McpClientTransport {

private static final Logger logger = LoggerFactory.getLogger(WebClientStreamableHttpTransport.class);

private static final String MCP_PROTOCOL_VERSION = "2025-03-26";

private static final String DEFAULT_ENDPOINT = "/mcp";

/**
Expand Down Expand Up @@ -103,6 +106,11 @@ private WebClientStreamableHttpTransport(ObjectMapper objectMapper, WebClient.Bu
this.activeSession.set(createTransportSession());
}

@Override
public String protocolVersion() {
return MCP_PROTOCOL_VERSION;
}

/**
* Create a stateful builder for creating {@link WebClientStreamableHttpTransport}
* instances.
Expand All @@ -128,12 +136,20 @@ public Mono<Void> connect(Function<Mono<McpSchema.JSONRPCMessage>, Mono<McpSchem

private DefaultMcpTransportSession createTransportSession() {
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().onErrorComplete(e -> {
logger.warn("Got error when closing transport", e);
return true;
}).then();
: webClient.delete()
.uri(this.endpoint)
.header(HttpHeaders.PROTOCOL_VERSION, MCP_PROTOCOL_VERSION)
.headers(httpHeaders -> {
httpHeaders.add(HttpHeaders.MCP_SESSION_ID, sessionId);
httpHeaders.add(HttpHeaders.PROTOCOL_VERSION, MCP_PROTOCOL_VERSION);
})
.retrieve()
.toBodilessEntity()
.onErrorComplete(e -> {
logger.warn("Got error when closing transport", e);
return true;
})
.then();
return new DefaultMcpTransportSession(onClose);
}

Expand Down Expand Up @@ -186,10 +202,11 @@ private Mono<Disposable> reconnect(McpTransportStream<Disposable> stream) {
Disposable connection = webClient.get()
.uri(this.endpoint)
.accept(MediaType.TEXT_EVENT_STREAM)
.header(HttpHeaders.PROTOCOL_VERSION, MCP_PROTOCOL_VERSION)
.headers(httpHeaders -> {
transportSession.sessionId().ifPresent(id -> httpHeaders.add("mcp-session-id", id));
transportSession.sessionId().ifPresent(id -> httpHeaders.add(HttpHeaders.MCP_SESSION_ID, id));
if (stream != null) {
stream.lastId().ifPresent(id -> httpHeaders.add("last-event-id", id));
stream.lastId().ifPresent(id -> httpHeaders.add(HttpHeaders.LAST_EVENT_ID, id));
}
})
.exchangeToFlux(response -> {
Expand Down Expand Up @@ -246,13 +263,14 @@ public Mono<Void> sendMessage(McpSchema.JSONRPCMessage message) {
Disposable connection = webClient.post()
.uri(this.endpoint)
.accept(MediaType.APPLICATION_JSON, MediaType.TEXT_EVENT_STREAM)
.header(HttpHeaders.PROTOCOL_VERSION, MCP_PROTOCOL_VERSION)
.headers(httpHeaders -> {
transportSession.sessionId().ifPresent(id -> httpHeaders.add("mcp-session-id", id));
transportSession.sessionId().ifPresent(id -> httpHeaders.add(HttpHeaders.MCP_SESSION_ID, id));
})
.bodyValue(message)
.exchangeToFlux(response -> {
if (transportSession
.markInitialized(response.headers().asHttpHeaders().getFirst("mcp-session-id"))) {
.markInitialized(response.headers().asHttpHeaders().getFirst(HttpHeaders.MCP_SESSION_ID))) {
// Once we have a session, we try to open an async stream for
// the server to send notifications and requests out-of-band.
reconnect(null).contextWrite(sink.contextView()).subscribe();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import io.modelcontextprotocol.spec.HttpHeaders;
import io.modelcontextprotocol.spec.McpClientTransport;
import io.modelcontextprotocol.spec.McpError;
import io.modelcontextprotocol.spec.McpSchema;
Expand Down Expand Up @@ -62,6 +64,8 @@ public class WebFluxSseClientTransport implements McpClientTransport {

private static final Logger logger = LoggerFactory.getLogger(WebFluxSseClientTransport.class);

private static final String MCP_PROTOCOL_VERSION = "2024-11-05";

/**
* Event type for JSON-RPC messages received through the SSE connection. The server
* sends messages with this event type to transmit JSON-RPC protocol data.
Expand Down Expand Up @@ -166,6 +170,11 @@ public WebFluxSseClientTransport(WebClient.Builder webClientBuilder, ObjectMappe
this.sseEndpoint = sseEndpoint;
}

@Override
public String protocolVersion() {
return MCP_PROTOCOL_VERSION;
}

/**
* Establishes a connection to the MCP server using Server-Sent Events (SSE). This
* method initiates the SSE connection and sets up the message processing pipeline.
Expand Down Expand Up @@ -250,6 +259,7 @@ public Mono<Void> sendMessage(JSONRPCMessage message) {
return webClient.post()
.uri(messageEndpointUri)
.contentType(MediaType.APPLICATION_JSON)
.header(HttpHeaders.PROTOCOL_VERSION, MCP_PROTOCOL_VERSION)
.bodyValue(jsonText)
.retrieve()
.toBodilessEntity()
Expand Down Expand Up @@ -282,6 +292,7 @@ protected Flux<ServerSentEvent<String>> eventStream() {// @formatter:off
.get()
.uri(this.sseEndpoint)
.accept(MediaType.TEXT_EVENT_STREAM)
.header(HttpHeaders.PROTOCOL_VERSION, MCP_PROTOCOL_VERSION)
.retrieve()
.bodyToFlux(SSE_TYPE)
.retryWhen(Retry.from(retrySignal -> retrySignal.handle(inboundRetryHandler)));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,8 @@ public class WebFluxSseServerTransportProvider implements McpServerTransportProv
*/
public static final String ENDPOINT_EVENT_TYPE = "endpoint";

private static final String MCP_PROTOCOL_VERSION = "2025-06-18";

/**
* Default SSE endpoint path as specified by the MCP transport specification.
*/
Expand Down Expand Up @@ -212,6 +214,11 @@ public WebFluxSseServerTransportProvider(ObjectMapper objectMapper, String baseU
}
}

@Override
public String protocolVersion() {
return "2024-11-05";
}

@Override
public void setSessionFactory(McpServerSession.Factory sessionFactory) {
this.sessionFactory = sessionFactory;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@

import java.io.IOException;
import java.util.List;
import java.util.function.Function;

/**
* Implementation of a WebFlux based {@link McpStatelessServerTransport}.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,11 @@ private WebFluxStreamableServerTransportProvider(ObjectMapper objectMapper, Stri

}

@Override
public String protocolVersion() {
return "2025-03-26";
}

@Override
public void setSessionFactory(McpStreamableServerSession.Factory sessionFactory) {
this.sessionFactory = sessionFactory;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,11 @@ public WebMvcSseServerTransportProvider(ObjectMapper objectMapper, String baseUr
}
}

@Override
public String protocolVersion() {
return "2024-11-05";
}

@Override
public void setSessionFactory(McpServerSession.Factory sessionFactory) {
this.sessionFactory = sessionFactory;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,11 @@ private WebMvcStreamableServerTransportProvider(ObjectMapper objectMapper, Strin
}
}

@Override
public String protocolVersion() {
return "2025-03-26";
}

@Override
public void setSessionFactory(McpStreamableServerSession.Factory sessionFactory) {
this.sessionFactory = sessionFactory;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,15 @@ static class TestConfig {
@Bean
public WebMvcSseServerTransportProvider webMvcSseServerTransportProvider() {

return new WebMvcSseServerTransportProvider(new ObjectMapper(), CUSTOM_CONTEXT_PATH, MESSAGE_ENDPOINT,
WebMvcSseServerTransportProvider.DEFAULT_SSE_ENDPOINT);
return WebMvcSseServerTransportProvider.builder()
.objectMapper(new ObjectMapper())
.baseUrl(CUSTOM_CONTEXT_PATH)
.messageEndpoint(MESSAGE_ENDPOINT)
.sseEndpoint(WebMvcSseServerTransportProvider.DEFAULT_SSE_ENDPOINT)
.build();
// return new WebMvcSseServerTransportProvider(new ObjectMapper(),
// CUSTOM_CONTEXT_PATH, MESSAGE_ENDPOINT,
// WebMvcSseServerTransportProvider.DEFAULT_SSE_ENDPOINT);
}

@Bean
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -272,9 +272,8 @@ public class McpAsyncClient {
asyncProgressNotificationHandler(progressConsumersFinal));

this.initializer = new LifecycleInitializer(clientCapabilities, clientInfo,
List.of(McpSchema.LATEST_PROTOCOL_VERSION), initializationTimeout,
ctx -> new McpClientSession(requestTimeout, transport, requestHandlers, notificationHandlers,
con -> con.contextWrite(ctx)));
List.of(transport.protocolVersion()), initializationTimeout, ctx -> new McpClientSession(requestTimeout,
transport, requestHandlers, notificationHandlers, con -> con.contextWrite(ctx)));
this.transport.setExceptionHandler(this.initializer::handleException);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@
*/
public class HttpClientSseClientTransport implements McpClientTransport {

private static final String MCP_PROTOCOL_VERSION = "2024-11-05";

private static final String MCP_PROTOCOL_VERSION_HEADER_NAME = "MCP-Protocol-Version";

private static final Logger logger = LoggerFactory.getLogger(HttpClientSseClientTransport.class);

/** SSE event type for JSON-RPC messages */
Expand Down Expand Up @@ -211,6 +215,11 @@ public HttpClientSseClientTransport(HttpClient.Builder clientBuilder, HttpReques
this.httpRequestCustomizer = httpRequestCustomizer;
}

@Override
public String protocolVersion() {
return MCP_PROTOCOL_VERSION;
}

/**
* Creates a new builder for {@link HttpClientSseClientTransport}.
* @param baseUri the base URI of the MCP server
Expand Down Expand Up @@ -391,6 +400,7 @@ public Mono<Void> connect(Function<Mono<JSONRPCMessage>, Mono<JSONRPCMessage>> h
.uri(uri)
.header("Accept", "text/event-stream")
.header("Cache-Control", "no-cache")
.header(MCP_PROTOCOL_VERSION_HEADER_NAME, MCP_PROTOCOL_VERSION)
.GET();
return Mono.from(this.httpRequestCustomizer.customize(builder, "GET", uri, null));
}).flatMap(requestBuilder -> Mono.create(sink -> {
Expand Down Expand Up @@ -516,7 +526,10 @@ private Mono<String> serializeMessage(final JSONRPCMessage message) {
private Mono<HttpResponse<String>> sendHttpPost(final String endpoint, final String body) {
final URI requestUri = Utils.resolveUri(baseUri, endpoint);
return Mono.defer(() -> {
var builder = this.requestBuilder.copy().uri(requestUri).POST(HttpRequest.BodyPublishers.ofString(body));
var builder = this.requestBuilder.copy()
.uri(requestUri)
.header(MCP_PROTOCOL_VERSION_HEADER_NAME, MCP_PROTOCOL_VERSION)
.POST(HttpRequest.BodyPublishers.ofString(body));
return Mono.from(this.httpRequestCustomizer.customize(builder, "POST", requestUri, body));
}).flatMap(customizedBuilder -> {
var request = customizedBuilder.build();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import io.modelcontextprotocol.client.transport.ResponseSubscribers.ResponseEvent;
import io.modelcontextprotocol.spec.DefaultMcpTransportSession;
import io.modelcontextprotocol.spec.DefaultMcpTransportStream;
import io.modelcontextprotocol.spec.HttpHeaders;
import io.modelcontextprotocol.spec.McpClientTransport;
import io.modelcontextprotocol.spec.McpError;
import io.modelcontextprotocol.spec.McpSchema;
Expand Down Expand Up @@ -72,6 +73,8 @@ public class HttpClientStreamableHttpTransport implements McpClientTransport {

private static final Logger logger = LoggerFactory.getLogger(HttpClientStreamableHttpTransport.class);

private static final String MCP_PROTOCOL_VERSION = "2025-03-26";

private static final String DEFAULT_ENDPOINT = "/mcp";

/**
Expand Down Expand Up @@ -131,6 +134,11 @@ private HttpClientStreamableHttpTransport(ObjectMapper objectMapper, HttpClient
this.httpRequestCustomizer = httpRequestCustomizer;
}

@Override
public String protocolVersion() {
return MCP_PROTOCOL_VERSION;
}

public static Builder builder(String baseUri) {
return new Builder(baseUri);
}
Expand All @@ -157,12 +165,14 @@ private DefaultMcpTransportSession createTransportSession() {
}

private Publisher<Void> createDelete(String sessionId) {

var uri = Utils.resolveUri(this.baseUri, this.endpoint);
return Mono.defer(() -> {
var builder = this.requestBuilder.copy()
.uri(uri)
.header("Cache-Control", "no-cache")
.header("mcp-session-id", sessionId)
.header(HttpHeaders.MCP_SESSION_ID, sessionId)
.header(HttpHeaders.PROTOCOL_VERSION, MCP_PROTOCOL_VERSION)
.DELETE();
return Mono.from(this.httpRequestCustomizer.customize(builder, "DELETE", uri, null));
}).flatMap(requestBuilder -> {
Expand Down Expand Up @@ -221,16 +231,18 @@ private Mono<Disposable> reconnect(McpTransportStream<Disposable> stream) {
HttpRequest.Builder requestBuilder = this.requestBuilder.copy();

if (transportSession != null && transportSession.sessionId().isPresent()) {
requestBuilder = requestBuilder.header("mcp-session-id", transportSession.sessionId().get());
requestBuilder = requestBuilder.header(HttpHeaders.MCP_SESSION_ID,
transportSession.sessionId().get());
}

if (stream != null && stream.lastId().isPresent()) {
requestBuilder = requestBuilder.header("last-event-id", stream.lastId().get());
requestBuilder = requestBuilder.header(HttpHeaders.LAST_EVENT_ID, stream.lastId().get());
}

var builder = requestBuilder.uri(uri)
.header("Accept", TEXT_EVENT_STREAM)
.header("Cache-Control", "no-cache")
.header(HttpHeaders.PROTOCOL_VERSION, MCP_PROTOCOL_VERSION)
.GET();
return Mono.from(this.httpRequestCustomizer.customize(builder, "GET", uri, null));
})
Expand Down Expand Up @@ -377,13 +389,15 @@ public Mono<Void> sendMessage(McpSchema.JSONRPCMessage sentMessage) {
HttpRequest.Builder requestBuilder = this.requestBuilder.copy();

if (transportSession != null && transportSession.sessionId().isPresent()) {
requestBuilder = requestBuilder.header("mcp-session-id", transportSession.sessionId().get());
requestBuilder = requestBuilder.header(HttpHeaders.MCP_SESSION_ID,
transportSession.sessionId().get());
}

var builder = requestBuilder.uri(uri)
.header("Accept", APPLICATION_JSON + ", " + TEXT_EVENT_STREAM)
.header("Content-Type", APPLICATION_JSON)
.header("Cache-Control", "no-cache")
.header(HttpHeaders.PROTOCOL_VERSION, MCP_PROTOCOL_VERSION)
.POST(HttpRequest.BodyPublishers.ofString(jsonBody));
return Mono.from(this.httpRequestCustomizer.customize(builder, "GET", uri, jsonBody));
}).flatMapMany(requestBuilder -> Flux.<ResponseEvent>create(responseEventSink -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ public class McpAsyncServer {

private final ConcurrentHashMap<McpSchema.CompleteReference, McpServerFeatures.AsyncCompletionSpecification> completions = new ConcurrentHashMap<>();

private List<String> protocolVersions = List.of(McpSchema.LATEST_PROTOCOL_VERSION);
private List<String> protocolVersions;

private McpUriTemplateManagerFactory uriTemplateManagerFactory = new DeafaultMcpUriTemplateManagerFactory();

Expand Down Expand Up @@ -145,6 +145,8 @@ public class McpAsyncServer {
Map<String, McpRequestHandler<?>> requestHandlers = prepareRequestHandlers();
Map<String, McpNotificationHandler> notificationHandlers = prepareNotificationHandlers(features);

this.protocolVersions = List.of(mcpTransportProvider.protocolVersion());

mcpTransportProvider.setSessionFactory(transport -> new McpServerSession(UUID.randomUUID().toString(),
requestTimeout, transport, this::asyncInitializeRequestHandler, requestHandlers, notificationHandlers));
}
Expand All @@ -168,6 +170,8 @@ public class McpAsyncServer {
Map<String, McpRequestHandler<?>> requestHandlers = prepareRequestHandlers();
Map<String, McpNotificationHandler> notificationHandlers = prepareNotificationHandlers(features);

this.protocolVersions = List.of(mcpTransportProvider.protocolVersion());

mcpTransportProvider.setSessionFactory(new DefaultMcpStreamableServerSessionFactory(requestTimeout,
this::asyncInitializeRequestHandler, requestHandlers, notificationHandlers));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public class McpStatelessAsyncServer {

private final ConcurrentHashMap<McpSchema.CompleteReference, McpStatelessServerFeatures.AsyncCompletionSpecification> completions = new ConcurrentHashMap<>();

private List<String> protocolVersions = List.of(McpSchema.LATEST_PROTOCOL_VERSION);
private List<String> protocolVersions;

private McpUriTemplateManagerFactory uriTemplateManagerFactory = new DeafaultMcpUriTemplateManagerFactory();

Expand Down Expand Up @@ -118,6 +118,8 @@ public class McpStatelessAsyncServer {
requestHandlers.put(McpSchema.METHOD_COMPLETION_COMPLETE, completionCompleteRequestHandler());
}

this.protocolVersions = List.of(mcpTransport.protocolVersion());

McpStatelessServerHandler handler = new DefaultMcpStatelessServerHandler(requestHandlers, Map.of());
mcpTransport.setMcpHandler(handler);
}
Expand Down
Loading