Skip to content
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 @@ -453,7 +453,7 @@ private Mono<ServerResponse> handleMessage(ServerRequest request) {
// return ServerResponse.ok().build();
return ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR)
.bodyValue(McpError.builder(McpSchema.ErrorCodes.INTERNAL_ERROR)
.message(error.getMessage())
.message("Internal server error. Check server logs for details.")
.build());
});
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/*
* Copyright 2023-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.ai.mcp.server.webflux.transport;

import java.util.Map;

import io.modelcontextprotocol.spec.McpServerSession;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.reactive.server.WebTestClient;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
* Unit tests for {@link WebFluxSseServerTransportProvider}.
*
* @author Dimitar Proynov
*/
class WebFluxSseServerTransportProviderTests {

private static final String TOOL_CALL_REQUEST = """
{"jsonrpc":"2.0","id":"1","method":"tools/call","params":{"name":"read","arguments":{}}}""";

@Test
@SuppressWarnings("unchecked")
void internalErrorResponseDoesNotLeakExceptionMessageToClient() {
String sensitiveDetail = "/opt/app/config/prod-secrets.yaml (No such file or directory)";

// A registered handler throws an exception whose message embeds sensitive
// internal detail that must not reach the remote client.
McpServerSession session = mock(McpServerSession.class);
when(session.handle(any())).thenReturn(Mono.error(new RuntimeException(sensitiveDetail)));

WebFluxSseServerTransportProvider provider = WebFluxSseServerTransportProvider.builder().build();
Map<String, McpServerSession> sessions = (Map<String, McpServerSession>) ReflectionTestUtils.getField(provider,
"sessions");
sessions.put("test-session", session);

WebTestClient client = WebTestClient.bindToRouterFunction(provider.getRouterFunction()).build();

client.post()
.uri(uriBuilder -> uriBuilder.path("/mcp/message").queryParam("sessionId", "test-session").build())
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(TOOL_CALL_REQUEST)
.exchange()
.expectStatus()
.isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR)
.expectBody(String.class)
.value(body -> assertThat(body).contains("Internal server error. Check server logs for details.")
.doesNotContain(sensitiveDetail));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -439,7 +439,9 @@ private ServerResponse handleMessage(ServerRequest request) {
logger.error("Error handling message: " + e.getMessage());
}
return ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(McpError.builder(McpSchema.ErrorCodes.INTERNAL_ERROR).message(e.getMessage()).build());
.body(McpError.builder(McpSchema.ErrorCodes.INTERNAL_ERROR)
.message("Internal server error. Check server logs for details.")
.build());
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ private ServerResponse handlePost(ServerRequest request) {
}
return ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(McpError.builder(McpSchema.ErrorCodes.INTERNAL_ERROR)
.message("Failed to handle request: " + e.getMessage())
.message("Failed to handle request. Check server logs for details.")
.build());
}
}
Expand All @@ -185,7 +185,7 @@ else if (message instanceof McpSchema.JSONRPCNotification jsonrpcNotification) {
}
return ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(McpError.builder(McpSchema.ErrorCodes.INTERNAL_ERROR)
.message("Failed to handle notification: " + e.getMessage())
.message("Failed to handle notification. Check server logs for details.")
.build());
}
}
Expand All @@ -209,7 +209,7 @@ else if (message instanceof McpSchema.JSONRPCNotification jsonrpcNotification) {
}
return ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(McpError.builder(McpSchema.ErrorCodes.INTERNAL_ERROR)
.message("Unexpected error: " + e.getMessage())
.message("Internal server error. Check server logs for details.")
.build());
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -437,7 +437,9 @@ private ServerResponse handlePost(ServerRequest request) {
logger.error("Failed to initialize session: " + e.getMessage());
}
return ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(McpError.builder(McpSchema.ErrorCodes.INTERNAL_ERROR).message(e.getMessage()).build());
.body(McpError.builder(McpSchema.ErrorCodes.INTERNAL_ERROR)
.message("Internal server error. Check server logs for details.")
.build());
}
}

Expand Down Expand Up @@ -520,7 +522,9 @@ else if (message instanceof McpSchema.JSONRPCRequest jsonrpcRequest) {
logger.error("Error handling message: " + e.getMessage());
}
return ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(McpError.builder(McpSchema.ErrorCodes.INTERNAL_ERROR).message(e.getMessage()).build());
.body(McpError.builder(McpSchema.ErrorCodes.INTERNAL_ERROR)
.message("Internal server error. Check server logs for details.")
.build());
}
}

Expand Down Expand Up @@ -570,7 +574,9 @@ private ServerResponse handleDelete(ServerRequest request) {
logger.error("Failed to delete session " + sessionId + ": " + e.getMessage());
}
return ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(McpError.builder(McpSchema.ErrorCodes.INTERNAL_ERROR).message(e.getMessage()).build());
.body(McpError.builder(McpSchema.ErrorCodes.INTERNAL_ERROR)
.message("Internal server error. Check server logs for details.")
.build());
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/*
* Copyright 2023-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.ai.mcp.server.webmvc.transport;

import java.util.Map;

import io.modelcontextprotocol.spec.McpServerSession;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.test.web.servlet.client.MockMvcWebTestClient;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
* Unit tests for {@link WebMvcSseServerTransportProvider}.
*
* @author Dimitar Proynov
*/
class WebMvcSseServerTransportProviderTests {

private static final String TOOL_CALL_REQUEST = """
{"jsonrpc":"2.0","id":"1","method":"tools/call","params":{"name":"read","arguments":{}}}""";

@Test
@SuppressWarnings("unchecked")
void internalErrorResponseDoesNotLeakExceptionMessageToClient() {
String sensitiveDetail = "/opt/app/config/prod-secrets.yaml (No such file or directory)";

// A registered handler throws an exception whose message embeds sensitive
// internal detail that must not reach the remote client.
McpServerSession session = mock(McpServerSession.class);
when(session.handle(any())).thenReturn(Mono.error(new RuntimeException(sensitiveDetail)));

WebMvcSseServerTransportProvider provider = WebMvcSseServerTransportProvider.builder().build();
Map<String, McpServerSession> sessions = (Map<String, McpServerSession>) ReflectionTestUtils.getField(provider,
"sessions");
sessions.put("test-session", session);

WebTestClient client = MockMvcWebTestClient.bindToRouterFunction(provider.getRouterFunction()).build();

client.post()
.uri(uriBuilder -> uriBuilder.path("/mcp/message").queryParam("sessionId", "test-session").build())
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(TOOL_CALL_REQUEST)
.exchange()
.expectStatus()
.isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR)
.expectBody(String.class)
.value(body -> assertThat(body).contains("Internal server error. Check server logs for details.")
.doesNotContain(sensitiveDetail));
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/*
* Copyright 2023-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.ai.mcp.server.webmvc.transport;

import io.modelcontextprotocol.server.McpStatelessServerHandler;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.test.web.servlet.client.MockMvcWebTestClient;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
* Unit tests for {@link WebMvcStatelessServerTransport}.
*
* @author Dimitar Proynov
*/
class WebMvcStatelessServerTransportTests {

private static final String SENSITIVE_DETAIL = "/opt/app/config/prod-secrets.yaml (No such file or directory)";

private static final String REQUEST = """
{"jsonrpc":"2.0","id":"1","method":"tools/call","params":{"name":"read","arguments":{}}}""";

private static final String NOTIFICATION = """
{"jsonrpc":"2.0","method":"notifications/progress","params":{}}""";

@Test
void requestErrorResponseDoesNotLeakExceptionMessageToClient() {
McpStatelessServerHandler handler = mock(McpStatelessServerHandler.class);
when(handler.handleRequest(any(), any())).thenReturn(Mono.error(new RuntimeException(SENSITIVE_DETAIL)));

testMessageDoesntRevealDetails(handler, REQUEST, "Failed to handle request. Check server logs for details.");
}

@Test
void notificationErrorResponseDoesNotLeakExceptionMessageToClient() {
McpStatelessServerHandler handler = mock(McpStatelessServerHandler.class);
when(handler.handleNotification(any(), any())).thenReturn(Mono.error(new RuntimeException(SENSITIVE_DETAIL)));

testMessageDoesntRevealDetails(handler, NOTIFICATION,
"Failed to handle notification. Check server logs for details.");
}

private void testMessageDoesntRevealDetails(McpStatelessServerHandler handler, String body,
String expectedMessage) {
WebMvcStatelessServerTransport transport = WebMvcStatelessServerTransport.builder().build();
transport.setMcpHandler(handler);

WebTestClient client = MockMvcWebTestClient.bindToRouterFunction(transport.getRouterFunction()).build();

client.post()
.uri("/mcp")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON, MediaType.TEXT_EVENT_STREAM)
.bodyValue(body)
.exchange()
.expectStatus()
.isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR)
.expectBody(String.class)
.value(response -> assertThat(response).contains(expectedMessage).doesNotContain(SENSITIVE_DETAIL));
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
* Copyright 2023-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.ai.mcp.server.webmvc.transport;

import io.modelcontextprotocol.spec.McpStreamableServerSession;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.test.web.servlet.client.MockMvcWebTestClient;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
* Unit tests for {@link WebMvcStreamableServerTransportProvider}.
*
* @author Dimitar Proynov
*/
class WebMvcStreamableServerTransportProviderTests {

private static final String INITIALIZE_REQUEST = """
{"jsonrpc":"2.0","id":"1","method":"initialize","params":{"protocolVersion":"2024-11-05",\
"capabilities":{},"clientInfo":{"name":"test-client","version":"1.0.0"}}}""";

@Test
void internalErrorResponseDoesNotLeakExceptionMessageToClient() {
String sensitiveDetail = "/opt/app/config/prod-secrets.yaml (No such file or directory)";

WebMvcStreamableServerTransportProvider provider = WebMvcStreamableServerTransportProvider.builder().build();
provider.setSessionFactory(initializeRequest -> {
McpStreamableServerSession session = mock(McpStreamableServerSession.class);
when(session.getId()).thenReturn("test-session");
// The session initialization fails with an exception whose message embeds
// sensitive internal detail that must not reach the remote client.
return new McpStreamableServerSession.McpStreamableServerSessionInit(session,
Mono.error(new RuntimeException(sensitiveDetail)));
});

WebTestClient client = MockMvcWebTestClient.bindToRouterFunction(provider.getRouterFunction()).build();

client.post()
.uri("/mcp")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON, MediaType.TEXT_EVENT_STREAM)
.bodyValue(INITIALIZE_REQUEST)
.exchange()
.expectStatus()
.isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR)
.expectBody(String.class)
.value(body -> assertThat(body).contains("Internal server error. Check server logs for details.")
.doesNotContain(sensitiveDetail));
}

}
Loading