-
Notifications
You must be signed in to change notification settings - Fork 891
fix: avoid dropped errors when transport is closed or uninitialized #995
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
Open
chemicL
wants to merge
2
commits into
main
Choose a base branch
from
session-connect-and-close-issues
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+109
−58
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -30,17 +30,7 @@ | |
| import io.modelcontextprotocol.json.McpJsonDefaults; | ||
| import io.modelcontextprotocol.json.McpJsonMapper; | ||
| import io.modelcontextprotocol.json.TypeRef; | ||
| import io.modelcontextprotocol.spec.ClosedMcpTransportSession; | ||
| import io.modelcontextprotocol.spec.DefaultMcpTransportSession; | ||
| import io.modelcontextprotocol.spec.DefaultMcpTransportStream; | ||
| import io.modelcontextprotocol.spec.HttpHeaders; | ||
| import io.modelcontextprotocol.spec.McpClientTransport; | ||
| 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; | ||
| import io.modelcontextprotocol.spec.ProtocolVersions; | ||
| import io.modelcontextprotocol.spec.*; | ||
| import io.modelcontextprotocol.util.Assert; | ||
| import io.modelcontextprotocol.util.Utils; | ||
| import org.reactivestreams.Publisher; | ||
|
|
@@ -189,14 +179,6 @@ private McpTransportSession<Disposable> createTransportSession() { | |
| return new DefaultMcpTransportSession(onClose); | ||
| } | ||
|
|
||
| private McpTransportSession<Disposable> createClosedSession(McpTransportSession<Disposable> existingSession) { | ||
| var existingSessionId = Optional.ofNullable(existingSession) | ||
| .filter(session -> !(session instanceof ClosedMcpTransportSession<Disposable>)) | ||
| .flatMap(McpTransportSession::sessionId) | ||
| .orElse(null); | ||
| return new ClosedMcpTransportSession<>(existingSessionId); | ||
| } | ||
|
|
||
| private Publisher<Void> createDelete(String sessionId) { | ||
|
|
||
| var uri = Utils.resolveUri(this.baseUri, this.endpoint); | ||
|
|
@@ -240,7 +222,8 @@ private void handleException(Throwable t) { | |
| public Mono<Void> closeGracefully() { | ||
| return Mono.defer(() -> { | ||
| logger.debug("Graceful close triggered"); | ||
| McpTransportSession<Disposable> currentSession = this.activeSession.getAndUpdate(this::createClosedSession); | ||
| McpTransportSession<Disposable> currentSession = this.activeSession | ||
| .getAndSet(ClosedMcpTransportSession.INSTANCE); | ||
| if (currentSession != null) { | ||
| return Mono.from(currentSession.closeGracefully()); | ||
| } | ||
|
|
@@ -250,6 +233,19 @@ public Mono<Void> closeGracefully() { | |
|
|
||
| private Mono<Disposable> reconnect(McpTransportStream<Disposable> stream) { | ||
| return Mono.deferContextual(ctx -> { | ||
| var rh = this.handler.get(); | ||
| if (rh == null) { | ||
| logger.warn("Transport has no request handler registered. Remember to call connect!"); | ||
| } | ||
|
|
||
| final Function<Mono<McpSchema.JSONRPCMessage>, Mono<McpSchema.JSONRPCMessage>> requestHandler = rh != null | ||
| ? rh : msg -> Mono.error(new IllegalStateException("No request handler")); | ||
|
|
||
| final McpTransportSession<Disposable> transportSession = this.activeSession.get(); | ||
|
|
||
| if (ClosedMcpTransportSession.INSTANCE.equals(transportSession)) { | ||
| throw new McpTransportSessionClosedException(); | ||
| } | ||
|
|
||
| if (stream != null) { | ||
| logger.debug("Reconnecting stream {} with lastId {}", stream.streamId(), stream.lastId()); | ||
|
|
@@ -259,7 +255,7 @@ private Mono<Disposable> reconnect(McpTransportStream<Disposable> stream) { | |
| } | ||
|
|
||
| final AtomicReference<Disposable> disposableRef = new AtomicReference<>(); | ||
| final McpTransportSession<Disposable> transportSession = this.activeSession.get(); | ||
|
|
||
| var uri = Utils.resolveUri(this.baseUri, this.endpoint); | ||
|
|
||
| Disposable connection = Mono.deferContextual(connectionCtx -> { | ||
|
|
@@ -389,18 +385,18 @@ else if (statusCode == BAD_REQUEST) { | |
| "Received unrecognized SSE event type: " + sseResponseEvent.sseEvent().event())); | ||
| }) | ||
| .retryWhen(authorizationErrorRetrySpec()) | ||
| .flatMap(jsonrpcMessage -> this.handler.get().apply(Mono.just(jsonrpcMessage))) | ||
| .flatMap(jsonrpcMessage -> requestHandler.apply(Mono.just(jsonrpcMessage))) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. can this leak? |
||
| .onErrorMap(CompletionException.class, t -> t.getCause()) | ||
| .onErrorComplete(t -> { | ||
| this.handleException(t); | ||
| return true; | ||
| }) | ||
| .doFinally(s -> { | ||
| Disposable ref = disposableRef.getAndSet(null); | ||
| if (ref != null) { | ||
| transportSession.removeConnection(ref); | ||
| } | ||
| })) | ||
| .onErrorComplete(t -> { | ||
| this.handleException(t); | ||
| return true; | ||
| }) | ||
| .contextWrite(ctx) | ||
| .subscribe(); | ||
|
|
||
|
|
@@ -467,10 +463,23 @@ public String toString(McpSchema.JSONRPCMessage message) { | |
|
|
||
| public Mono<Void> sendMessage(McpSchema.JSONRPCMessage sentMessage) { | ||
| return Mono.create(deliveredSink -> { | ||
| var rh = this.handler.get(); | ||
| if (rh == null) { | ||
| logger.warn("Transport has no request handler registered. Remember to call connect!"); | ||
| } | ||
|
|
||
| final Function<Mono<McpSchema.JSONRPCMessage>, Mono<McpSchema.JSONRPCMessage>> requestHandler = rh != null | ||
| ? rh : msg -> Mono.error(new IllegalStateException("No request handler")); | ||
|
|
||
| var transportSession = this.activeSession.get(); | ||
|
|
||
| if (ClosedMcpTransportSession.INSTANCE.equals(transportSession)) { | ||
| throw new McpTransportSessionClosedException(); | ||
| } | ||
|
|
||
| logger.debug("Sending message {}", sentMessage); | ||
|
|
||
| final AtomicReference<Disposable> disposableRef = new AtomicReference<>(); | ||
| final McpTransportSession<Disposable> transportSession = this.activeSession.get(); | ||
|
|
||
| var uri = Utils.resolveUri(this.baseUri, this.endpoint); | ||
| String jsonBody = this.toString(sentMessage); | ||
|
|
@@ -643,22 +652,26 @@ else if (statusCode == BAD_REQUEST) { | |
| new RuntimeException("Failed to send message: " + responseEvent)); | ||
| }) | ||
| .retryWhen(authorizationErrorRetrySpec()) | ||
| .flatMap(jsonRpcMessage -> this.handler.get().apply(Mono.just(jsonRpcMessage))) | ||
| .flatMap(jsonRpcMessage -> requestHandler.apply(Mono.just(jsonRpcMessage))) | ||
| .onErrorMap(CompletionException.class, t -> t.getCause()) | ||
| .onErrorComplete(t -> { | ||
| // handle the error first | ||
| this.handleException(t); | ||
| // inform the caller of sendMessage | ||
| deliveredSink.error(t); | ||
| return true; | ||
| }) | ||
| .doFinally(s -> { | ||
| logger.debug("SendMessage finally: {}", s); | ||
| Disposable ref = disposableRef.getAndSet(null); | ||
| if (ref != null) { | ||
| transportSession.removeConnection(ref); | ||
| } | ||
| })).contextWrite(deliveredSink.contextView()).subscribe(); | ||
| })).onErrorComplete(t -> { | ||
| // handle the error first | ||
| try { | ||
| this.handleException(t); | ||
| } | ||
| catch (Exception e) { | ||
| logger.error("Error handling exception {}", t.getMessage(), e); | ||
| } | ||
| // inform the caller of sendMessage | ||
| deliveredSink.error(t); | ||
| return true; | ||
| }).contextWrite(deliveredSink.contextView()).subscribe(); | ||
|
|
||
| disposableRef.set(connection); | ||
| transportSession.addConnection(connection); | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -8,11 +8,14 @@ | |
| import io.modelcontextprotocol.client.transport.customizer.McpSyncHttpClientRequestCustomizer; | ||
| import io.modelcontextprotocol.common.McpTransportContext; | ||
| import io.modelcontextprotocol.spec.McpSchema; | ||
| import io.modelcontextprotocol.spec.McpTransportSessionClosedException; | ||
| import io.modelcontextprotocol.spec.ProtocolVersions; | ||
| import java.net.URI; | ||
| import java.net.URISyntaxException; | ||
| import java.util.Map; | ||
| import java.util.function.Consumer; | ||
| import java.util.function.Function; | ||
|
|
||
| import org.junit.jupiter.api.AfterAll; | ||
| import org.junit.jupiter.api.BeforeAll; | ||
| import org.junit.jupiter.api.Test; | ||
|
|
@@ -139,13 +142,14 @@ void testCloseUninitialized() { | |
| var testMessage = new McpSchema.JSONRPCRequest(McpSchema.METHOD_INITIALIZE, "test-id", initializeRequest); | ||
|
|
||
| StepVerifier.create(transport.sendMessage(testMessage)) | ||
| .expectErrorMessage("MCP session has been closed") | ||
| .expectErrorMessage("Transport has already been closed.") | ||
| .verify(); | ||
| } | ||
|
|
||
| @Test | ||
| void testCloseInitialized() { | ||
| var transport = HttpClientStreamableHttpTransport.builder(host).build(); | ||
| // transport.connect(Function.identity()).block(); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. How come we don't need to call "connect" anymore? |
||
|
|
||
| var initializeRequest = McpSchema.InitializeRequest | ||
| .builder(ProtocolVersions.MCP_2025_11_25, McpSchema.ClientCapabilities.builder().roots(true).build(), | ||
|
|
@@ -157,7 +161,8 @@ void testCloseInitialized() { | |
| StepVerifier.create(transport.closeGracefully()).verifyComplete(); | ||
|
|
||
| StepVerifier.create(transport.sendMessage(testMessage)) | ||
| .expectErrorMatches(err -> err.getMessage().matches("MCP session with ID [a-zA-Z0-9-]* has been closed")) | ||
| .expectErrorMatches(err -> err instanceof McpTransportSessionClosedException | ||
| && err.getMessage().contains("Transport has already been closed")) | ||
| .verify(); | ||
| } | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -81,6 +81,7 @@ void setUp() { | |
|
|
||
| @AfterEach | ||
| void tearDown() { | ||
| requestCustomizer.reset(); | ||
| mcpClient.close(); | ||
| } | ||
|
|
||
|
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nit - we typically don't do star imports.