Skip to content

Rework MCP error handling #422

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

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
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 @@ -26,6 +26,7 @@
import io.modelcontextprotocol.spec.McpClientTransport;
import io.modelcontextprotocol.spec.McpError;
import io.modelcontextprotocol.spec.McpSchema;
import io.modelcontextprotocol.spec.McpTransportException;
import io.modelcontextprotocol.spec.McpTransportSession;
import io.modelcontextprotocol.spec.McpTransportSessionNotFoundException;
import io.modelcontextprotocol.spec.McpTransportStream;
Expand Down Expand Up @@ -428,11 +429,11 @@ private Tuple2<Optional<String>, Iterable<McpSchema.JSONRPCMessage>> parse(Serve
return Tuples.of(Optional.ofNullable(event.id()), List.of(message));
}
catch (IOException ioException) {
throw new McpError("Error parsing JSON-RPC message: " + event.data());
throw new McpTransportException("Error parsing JSON-RPC message: " + event.data(), ioException);
}
}
else {
throw new McpError("Received unrecognized SSE event type: " + event.event());
throw new McpTransportException("Received unrecognized SSE event type: " + event.event());
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,12 @@

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

import io.modelcontextprotocol.spec.McpClientInternalException;
import io.modelcontextprotocol.spec.McpClientTransport;
import io.modelcontextprotocol.spec.McpError;
import io.modelcontextprotocol.spec.McpSchema;
import io.modelcontextprotocol.spec.McpTransportException;
import io.modelcontextprotocol.spec.McpSchema.JSONRPCMessage;
import io.modelcontextprotocol.util.Assert;
import org.slf4j.Logger;
Expand Down Expand Up @@ -197,13 +200,14 @@ public Mono<Void> connect(Function<Mono<JSONRPCMessage>, Mono<JSONRPCMessage>> h
this.inboundSubscription = events.concatMap(event -> Mono.just(event).<JSONRPCMessage>handle((e, s) -> {
if (ENDPOINT_EVENT_TYPE.equals(event.event())) {
String messageEndpointUri = event.data();
if (messageEndpointSink.tryEmitValue(messageEndpointUri).isSuccess()) {
var emitResult = messageEndpointSink.tryEmitValue(messageEndpointUri);
if (emitResult.isSuccess()) {
s.complete();
}
else {
// TODO: clarify with the spec if multiple events can be
// received
s.error(new McpError("Failed to handle SSE endpoint event"));
s.error(new McpClientInternalException("Failed to handle SSE endpoint event"));
}
}
else if (MESSAGE_EVENT_TYPE.equals(event.event())) {
Expand All @@ -216,7 +220,7 @@ else if (MESSAGE_EVENT_TYPE.equals(event.event())) {
}
}
else {
s.error(new McpError("Received unrecognized SSE event type: " + event.event()));
s.error(new McpTransportException("Received unrecognized SSE event type: " + event.event()));
}
}).transform(handler)).subscribe();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,12 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import io.modelcontextprotocol.spec.McpError;
import io.modelcontextprotocol.spec.McpSchema;
import io.modelcontextprotocol.spec.McpSchema.ErrorCodes;
import io.modelcontextprotocol.spec.McpSchema.JSONRPCResponse.JSONRPCError;
import io.modelcontextprotocol.spec.McpServerSession;
import io.modelcontextprotocol.spec.McpServerTransport;
import io.modelcontextprotocol.spec.McpServerTransportProvider;
import io.modelcontextprotocol.spec.McpTransportException;
import io.modelcontextprotocol.util.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand Down Expand Up @@ -300,31 +303,29 @@ private Mono<ServerResponse> handleMessage(ServerRequest request) {
}

if (request.queryParam("sessionId").isEmpty()) {
return ServerResponse.badRequest().bodyValue(new McpError("Session ID missing in message endpoint"));
return ServerResponse.badRequest()
.bodyValue(McpError.builder(ErrorCodes.INVALID_REQUEST).message("Missing session ID param").build());
}

McpServerSession session = sessions.get(request.queryParam("sessionId").get());
String sessionId = request.queryParam("sessionId").get();
McpServerSession session = sessions.get(sessionId);

if (session == null) {
return ServerResponse.status(HttpStatus.NOT_FOUND)
.bodyValue(new McpError("Session not found: " + request.queryParam("sessionId").get()));
.bodyValue(McpError.builder(ErrorCodes.INVALID_REQUEST)
.message("SessionId not found")
.data("Empty sessionId: " + sessionId)
.build());
}

return request.bodyToMono(String.class).flatMap(body -> {
try {
McpSchema.JSONRPCMessage message = McpSchema.deserializeJsonRpcMessage(objectMapper, body);
return session.handle(message).flatMap(response -> ServerResponse.ok().build()).onErrorResume(error -> {
logger.error("Error processing message: {}", error.getMessage());
// TODO: instead of signalling the error, just respond with 200 OK
// - the error is signalled on the SSE connection
// return ServerResponse.ok().build();
return ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR)
.bodyValue(new McpError(error.getMessage()));
});
return session.handle(message).flatMap(response -> ServerResponse.ok().build());
}
catch (IllegalArgumentException | IOException e) {
logger.error("Failed to deserialize message: {}", e.getMessage());
return ServerResponse.badRequest().bodyValue(new McpError("Invalid message format"));
return ServerResponse.badRequest().bodyValue(new McpTransportException("Invalid message format", e));
}
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,11 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import io.modelcontextprotocol.spec.McpError;
import io.modelcontextprotocol.spec.McpSchema;
import io.modelcontextprotocol.spec.McpSchema.ErrorCodes;
import io.modelcontextprotocol.spec.McpSchema.JSONRPCResponse.JSONRPCError;
import io.modelcontextprotocol.spec.McpServerTransport;
import io.modelcontextprotocol.spec.McpServerTransportProvider;
import io.modelcontextprotocol.spec.McpTransportException;
import io.modelcontextprotocol.spec.McpServerSession;
import io.modelcontextprotocol.util.Assert;
import org.slf4j.Logger;
Expand Down Expand Up @@ -300,14 +303,19 @@ private ServerResponse handleMessage(ServerRequest request) {
}

if (request.param("sessionId").isEmpty()) {
return ServerResponse.badRequest().body(new McpError("Session ID missing in message endpoint"));
return ServerResponse.badRequest()
.body(McpError.builder(ErrorCodes.INVALID_REQUEST).message("Missing session ID param").build());
}

String sessionId = request.param("sessionId").get();
McpServerSession session = sessions.get(sessionId);

if (session == null) {
return ServerResponse.status(HttpStatus.NOT_FOUND).body(new McpError("Session not found: " + sessionId));
return ServerResponse.status(HttpStatus.NOT_FOUND)
.body(McpError.builder(ErrorCodes.INVALID_REQUEST)
.message("SessionId not found")
.data("Empty sessionId: " + sessionId)
.build());
}

try {
Expand All @@ -321,11 +329,11 @@ private ServerResponse handleMessage(ServerRequest request) {
}
catch (IllegalArgumentException | IOException e) {
logger.error("Failed to deserialize message: {}", e.getMessage());
return ServerResponse.badRequest().body(new McpError("Invalid message format"));
return ServerResponse.badRequest().body(new McpTransportException("Invalid message format", e));
}
catch (Exception e) {
logger.error("Error handling message: {}", e.getMessage());
return ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new McpError(e.getMessage()));
return ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new McpTransportException(e));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -486,7 +486,8 @@ void testAddRoot() {
void testAddRootWithNullValue() {
withClient(createMcpTransport(), mcpAsyncClient -> {
StepVerifier.create(mcpAsyncClient.addRoot(null))
.consumeErrorWith(e -> assertThat(e).isInstanceOf(McpError.class).hasMessage("Root must not be null"))
.consumeErrorWith(e -> assertThat(e).isInstanceOf(IllegalArgumentException.class)
.hasMessage("Root must not be null"))
.verify();
});
}
Expand All @@ -505,7 +506,7 @@ void testRemoveRoot() {
void testRemoveNonExistentRoot() {
withClient(createMcpTransport(), mcpAsyncClient -> {
StepVerifier.create(mcpAsyncClient.removeRoot("nonexistent-uri"))
.consumeErrorWith(e -> assertThat(e).isInstanceOf(McpError.class)
.consumeErrorWith(e -> assertThat(e).isInstanceOf(IllegalStateException.class)
.hasMessage("Root with uri 'nonexistent-uri' not found"))
.verify();
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ void testAddDuplicateTool() {
.create(mcpAsyncServer.addTool(new McpServerFeatures.AsyncToolSpecification(duplicateTool,
(exchange, args) -> Mono.just(new CallToolResult(List.of(), false)))))
.verifyErrorSatisfies(error -> {
assertThat(error).isInstanceOf(McpError.class)
assertThat(error).isInstanceOf(IllegalArgumentException.class)
.hasMessage("Tool with name '" + TEST_TOOL_NAME + "' already exists");
});

Expand All @@ -168,7 +168,7 @@ void testAddDuplicateToolCall() {
.tool(duplicateTool)
.callHandler((exchange, request) -> Mono.just(new CallToolResult(List.of(), false)))
.build())).verifyErrorSatisfies(error -> {
assertThat(error).isInstanceOf(McpError.class)
assertThat(error).isInstanceOf(IllegalArgumentException.class)
.hasMessage("Tool with name '" + TEST_TOOL_NAME + "' already exists");
});

Expand Down Expand Up @@ -254,7 +254,8 @@ void testRemoveNonexistentTool() {
.build();

StepVerifier.create(mcpAsyncServer.removeTool("nonexistent-tool")).verifyErrorSatisfies(error -> {
assertThat(error).isInstanceOf(McpError.class).hasMessage("Tool with name 'nonexistent-tool' not found");
assertThat(error).isInstanceOf(IllegalArgumentException.class)
.hasMessage("Tool with name 'nonexistent-tool' not found");
});

assertThatCode(() -> mcpAsyncServer.closeGracefully().block(Duration.ofSeconds(10))).doesNotThrowAnyException();
Expand Down Expand Up @@ -326,7 +327,7 @@ void testAddResourceWithNullSpecification() {

StepVerifier.create(mcpAsyncServer.addResource((McpServerFeatures.AsyncResourceSpecification) null))
.verifyErrorSatisfies(error -> {
assertThat(error).isInstanceOf(McpError.class).hasMessage("Resource must not be null");
assertThat(error).isInstanceOf(IllegalArgumentException.class).hasMessage("Resource must not be null");
});

assertThatCode(() -> mcpAsyncServer.closeGracefully().block(Duration.ofSeconds(10))).doesNotThrowAnyException();
Expand All @@ -345,7 +346,7 @@ void testAddResourceWithoutCapability() {
resource, (exchange, req) -> Mono.just(new ReadResourceResult(List.of())));

StepVerifier.create(serverWithoutResources.addResource(specification)).verifyErrorSatisfies(error -> {
assertThat(error).isInstanceOf(McpError.class)
assertThat(error).isInstanceOf(IllegalStateException.class)
.hasMessage("Server must be configured with resource capabilities");
});
}
Expand All @@ -358,7 +359,7 @@ void testRemoveResourceWithoutCapability() {
.build();

StepVerifier.create(serverWithoutResources.removeResource(TEST_RESOURCE_URI)).verifyErrorSatisfies(error -> {
assertThat(error).isInstanceOf(McpError.class)
assertThat(error).isInstanceOf(IllegalStateException.class)
.hasMessage("Server must be configured with resource capabilities");
});
}
Expand All @@ -385,7 +386,8 @@ void testAddPromptWithNullSpecification() {

StepVerifier.create(mcpAsyncServer.addPrompt((McpServerFeatures.AsyncPromptSpecification) null))
.verifyErrorSatisfies(error -> {
assertThat(error).isInstanceOf(McpError.class).hasMessage("Prompt specification must not be null");
assertThat(error).isInstanceOf(IllegalArgumentException.class)
.hasMessage("Prompt specification must not be null");
});
}

Expand All @@ -402,7 +404,7 @@ void testAddPromptWithoutCapability() {
.of(new PromptMessage(McpSchema.Role.ASSISTANT, new McpSchema.TextContent("Test content"))))));

StepVerifier.create(serverWithoutPrompts.addPrompt(specification)).verifyErrorSatisfies(error -> {
assertThat(error).isInstanceOf(McpError.class)
assertThat(error).isInstanceOf(IllegalStateException.class)
.hasMessage("Server must be configured with prompt capabilities");
});
}
Expand All @@ -415,7 +417,7 @@ void testRemovePromptWithoutCapability() {
.build();

StepVerifier.create(serverWithoutPrompts.removePrompt(TEST_PROMPT_NAME)).verifyErrorSatisfies(error -> {
assertThat(error).isInstanceOf(McpError.class)
assertThat(error).isInstanceOf(IllegalStateException.class)
.hasMessage("Server must be configured with prompt capabilities");
});
}
Expand Down Expand Up @@ -448,7 +450,7 @@ void testRemoveNonexistentPrompt() {
.build();

StepVerifier.create(mcpAsyncServer2.removePrompt("nonexistent-prompt")).verifyErrorSatisfies(error -> {
assertThat(error).isInstanceOf(McpError.class)
assertThat(error).isInstanceOf(IllegalArgumentException.class)
.hasMessage("Prompt with name 'nonexistent-prompt' not found");
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ void testAddDuplicateTool() {

assertThatThrownBy(() -> mcpSyncServer.addTool(new McpServerFeatures.SyncToolSpecification(duplicateTool,
(exchange, args) -> new CallToolResult(List.of(), false))))
.isInstanceOf(McpError.class)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Tool with name '" + TEST_TOOL_NAME + "' already exists");

assertThatCode(() -> mcpSyncServer.closeGracefully()).doesNotThrowAnyException();
Expand All @@ -172,7 +172,7 @@ void testAddDuplicateToolCall() {
assertThatThrownBy(() -> mcpSyncServer.addTool(McpServerFeatures.SyncToolSpecification.builder()
.tool(duplicateTool)
.callHandler((exchange, request) -> new CallToolResult(List.of(), false))
.build())).isInstanceOf(McpError.class)
.build())).isInstanceOf(IllegalArgumentException.class)
.hasMessage("Tool with name '" + TEST_TOOL_NAME + "' already exists");

assertThatCode(() -> mcpSyncServer.closeGracefully()).doesNotThrowAnyException();
Expand Down Expand Up @@ -256,7 +256,8 @@ void testRemoveNonexistentTool() {
.capabilities(ServerCapabilities.builder().tools(true).build())
.build();

assertThatThrownBy(() -> mcpSyncServer.removeTool("nonexistent-tool")).isInstanceOf(McpError.class)
assertThatThrownBy(() -> mcpSyncServer.removeTool("nonexistent-tool"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Tool with name 'nonexistent-tool' not found");

assertThatCode(() -> mcpSyncServer.closeGracefully()).doesNotThrowAnyException();
Expand Down Expand Up @@ -320,7 +321,7 @@ void testAddResourceWithNullSpecification() {
.build();

assertThatThrownBy(() -> mcpSyncServer.addResource((McpServerFeatures.SyncResourceSpecification) null))
.isInstanceOf(McpError.class)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Resource must not be null");

assertThatCode(() -> mcpSyncServer.closeGracefully()).doesNotThrowAnyException();
Expand All @@ -337,7 +338,8 @@ void testAddResourceWithoutCapability() {
McpServerFeatures.SyncResourceSpecification specification = new McpServerFeatures.SyncResourceSpecification(
resource, (exchange, req) -> new ReadResourceResult(List.of()));

assertThatThrownBy(() -> serverWithoutResources.addResource(specification)).isInstanceOf(McpError.class)
assertThatThrownBy(() -> serverWithoutResources.addResource(specification))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Server must be configured with resource capabilities");
}

Expand All @@ -347,7 +349,8 @@ void testRemoveResourceWithoutCapability() {
.serverInfo("test-server", "1.0.0")
.build();

assertThatThrownBy(() -> serverWithoutResources.removeResource(TEST_RESOURCE_URI)).isInstanceOf(McpError.class)
assertThatThrownBy(() -> serverWithoutResources.removeResource(TEST_RESOURCE_URI))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Server must be configured with resource capabilities");
}

Expand All @@ -372,7 +375,7 @@ void testAddPromptWithNullSpecification() {
.build();

assertThatThrownBy(() -> mcpSyncServer.addPrompt((McpServerFeatures.SyncPromptSpecification) null))
.isInstanceOf(McpError.class)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Prompt specification must not be null");
}

Expand All @@ -387,7 +390,8 @@ void testAddPromptWithoutCapability() {
(exchange, req) -> new GetPromptResult("Test prompt description", List
.of(new PromptMessage(McpSchema.Role.ASSISTANT, new McpSchema.TextContent("Test content")))));

assertThatThrownBy(() -> serverWithoutPrompts.addPrompt(specification)).isInstanceOf(McpError.class)
assertThatThrownBy(() -> serverWithoutPrompts.addPrompt(specification))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Server must be configured with prompt capabilities");
}

Expand All @@ -397,7 +401,8 @@ void testRemovePromptWithoutCapability() {
.serverInfo("test-server", "1.0.0")
.build();

assertThatThrownBy(() -> serverWithoutPrompts.removePrompt(TEST_PROMPT_NAME)).isInstanceOf(McpError.class)
assertThatThrownBy(() -> serverWithoutPrompts.removePrompt(TEST_PROMPT_NAME))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Server must be configured with prompt capabilities");
}

Expand Down Expand Up @@ -426,7 +431,8 @@ void testRemoveNonexistentPrompt() {
.capabilities(ServerCapabilities.builder().prompts(true).build())
.build();

assertThatThrownBy(() -> mcpSyncServer.removePrompt("nonexistent-prompt")).isInstanceOf(McpError.class)
assertThatThrownBy(() -> mcpSyncServer.removePrompt("nonexistent-prompt"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Prompt with name 'nonexistent-prompt' not found");

assertThatCode(() -> mcpSyncServer.closeGracefully()).doesNotThrowAnyException();
Expand Down
Loading