feat: add support for reactive hook in MCP client initialization by noxymon · Pull Request #866 · modelcontextprotocol/java-sdk

Summary

This PR introduces a connectHook to the McpClient builders and improves connection error propagation in McpClientSession. It ensures that failures during the transport connection phase (e.g., process startup failures in Stdio) are correctly reported
to callers instead of being dropped by Project Reactor.

Motivation and Context

This change addresses Closes #712 (#712). Previously, errors occurring during the asynchronous connection phase were often "dropped" by Reactor because the internal subscription lacked an error
handler. This led to onErrorDropped logs and caused client.initialize() to hang until a timeout occurred, rather than failing immediately with a descriptive error. The new connectHook also provides the requested extensibility for users to intercept
and transform the connection lifecycle.

How Has This Been Tested?

Tested via a new functional test suite McpClientInitializationTests.java:

  1. Error Propagation Test: Verified that providing a non-existent command to StdioClientTransport results in an immediate RuntimeException during initialize(), with the root "Failed to start process" cause preserved.
  2. Reactive Hook Test: Verified that a custom connectHook (e.g., .connectHook(mono -> mono.doOnError(...))) correctly intercepts connection-level errors.
  3. Build Validation: Full build and formatting check using ./mvnw clean install and spring-javaformat:apply.

Breaking Changes

No breaking changes. The connectHook is optional, and the updated internal constructors maintain backward compatibility via @deprecated overloads.

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Documentation update

Checklist

  • I have read the [MCP Documentation (https://modelcontextprotocol.io)
  • My code follows the repository's style guidelines
  • New and existing tests pass locally
  • I have added appropriate error handling
  • I have added or updated documentation as needed

Additional context

The fix in McpClientSession works by iterating over all pendingResponses when a connection error is detected and failing them immediately. This is a more robust approach than relying on timeouts, as it provides the actual cause of the connection
failure (e.g., IOException) to the user.