Commit graph java-sdk/mcp
Author SHA1 Message Date
Christian Tzolov
9c9e2ebdf7
fix: disable logging capabilities for stateless servers (#517)
Remove LoggingCapabilities from McpStatelessServerFeatures.Async constructor
as stateless servers do not support setLogging operations. This aligns the
async implementation with the sync implementation which already has logging
disabled.

Follows up on #463

Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
2025-08-26 12:48:42 +02:00
Christian Tzolov
336f2024e7
feat: implement demand-based request handling in ResponseSubscribers (#516)
- Add hasRequestedDemand volatile boolean flag to AggregateSubscriber and BodilessResponseLineSubscriber
- Modify hookOnSubscribe to request Long.MAX_VALUE only on first demand request
- Guard event emission in hookOnComplete with hasRequestedDemand check
- Prevents unnecessary data processing when no downstream demand exists
- Improves backpressure handling and resource efficiency

Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
2025-08-26 10:30:31 +02:00
shaoyin.zj
6ec443c89a
fix: When call the MCP SSE endpoint, the Content-Type header not passed by default (#489) 2025-08-26 07:51:07 +02:00
Zizo
cc67d8fa76
fix: http streamable client connect timeout (#511)
* add http streamable client connect timeout
* add http sse client connect timeout

Co-authored-by: gongwn1 <gongwn1@lenovo.com>
2025-08-25 16:14:28 +02:00
He-Pin(kerr)
94c03505c1
fix: Fix SseLineSubscriber lacking request. (#507)
Signed-off-by: He-Pin <hepin1989@gmail.com>
2025-08-25 15:46:17 +02:00
Christian Tzolov
888e555026
feat: implement identifier-based equals/hashCode for PromptReference (#514)
Ensure PromptReference equality is based solely on identifier and type fields, ignoring other fields like title

Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
2025-08-25 12:46:59 +02:00
Jordan Zimmerman
713ee1add0 fix: ServerCapabilities should not enable logging by default (#463)
- Change LoggingCapabilities from default-initialized to nullable in ServerCapabilities
- Add check if server logging is enabled in McpAsyncClient before setting logging level
- Ensure McpAsyncServer always enables logging capabilities when built
- Ensure McpStatelessAsyncServer has disabled logging capability by default
- Update tests to verify logging capabilities can be null

Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
Co-authored-by: Christian Tzolov <christian.tzolov@broadcom.com>
2025-08-11 23:03:25 +01:00
Christian Tzolov
6c38f37637 fix: improve streamable HTTP session reinitialization (#459)
Implements the MCP spec guidelines for streamable HTTP (re)initialization:
- Server MAY terminate session and MUST respond with HTTP 404 for terminated session IDs
- Client MUST start new session when receiving HTTP 404 for requests with session ID

Changes:
- Replace generic McpError with McpTransportException for transport-layer errors
- Only throw McpTransportSessionNotFoundException when session ID is present in request
  (per spec: 404 with session ID means session terminated, without means general error)
- Enhance error messages with more context (status codes, response events)
- Use RuntimeException for non-transport specific SSE endpoint failures
- Ensure consistent error handling across HTTP client transports

- Improve error handling with standard Java exceptions.
  Replace generic McpError with appropriate standard exceptions:
  - Use IllegalArgumentException for invalid input parameters
  - Use IllegalStateException for state-related issues
  - Use RuntimeException wrapper for initialization failures
  - Use McpError.builder() with proper error codes for protocol errors

Fixes #459

Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
2025-08-10 14:31:49 +01:00
Christian Tzolov
eb427add79 refactor: improve integration tests stability
- Replace inline StepVerifier assertions with AtomicReference pattern for better testability
- Add assertWith() usage for cleaner assertion blocks in async tests
- Simplify reactive chains using doOnNext() and thenReturn() patterns
- Remove unnecessary Thread.sleep() from elicitation handler
- Improve variable naming (rootsRef → toolsRef) for clarity
- Update timeout error message assertions to be more specific
- Clean up code formatting and remove redundant comments

Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
2025-08-09 18:41:13 +01:00
Christian Tzolov
cbfdb14e40
refactor: extract common integration test logic into abstract base classes (#473)
refactor: extract common integration test logic into abstract base classes

- Move duplicated test methods from WebFlux and WebMvc integration test classes to abstract base classes
- WebFluxSseIntegrationTests, WebFluxStreamableIntegrationTests now extend AbstractMcpClientServerIntegrationTests
- WebFluxStatelessIntegrationTests, WebMvcStatelessIntegrationTests now extend AbstractStatelessIntegrationTests  
- Each concrete test class now only implements transport-specific setup methods (prepareClients, prepareAsyncServerBuilder, prepareSyncServerBuilder)
- Eliminates ~1300+ lines of duplicated test code across multiple files
- Improves maintainability by centralizing test logic in reusable base classes
- Updates WebMvcSseServerTransportProvider to use builder pattern
- Adds new HttpServletSseIntegrationTests extending AbstractMcpClientServerIntegrationTests
  - Removes HttpServletSseServerTransportProviderIntegrationTests
- Standardizes timeout configurations and client setup across all integration tests

Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
2025-08-08 21:31:29 +02:00
Christian Tzolov
1edd1b64db feat: Add builder pattern for McpError and mutate method for capabilities
- Add builder pattern to McpError for structured error creation with validation
- Deprecate McpError(Object) constructor in favor of builder approach
- Add mutate() method to server capabilities for creating modified copies

Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
2025-08-08 09:36:40 +01:00
Jordan Zimmerman
a14ef425d6 If a handler throws McpError, use its values for the RPC error
Handlers should be able to throw RPC errors and `McpError` is the
right exception for that.

Improve `DefaultMcpStatelessServerHandler` error handler to check if the
exception is `McpError` and, if so, use it to build the RPC error
result instead of re-writing as `INTERNAL_ERROR`.
2025-08-08 10:20:53 +02:00
Christian Tzolov
4532b614e4 feat: handle SSE comment messages
- Add support for ignoring SSE comment lines that start with ':'
- Add debug logging for comment line processing

Resolves #443

Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
2025-08-07 11:36:16 +02:00
Daniel Garnier-Moiroux
032716546c Fix httpRequestCustomizer usage in HttpClientStreamableHttpTransport
- Closes #458

Signed-off-by: Daniel Garnier-Moiroux <git@garnier.wf>
2025-08-07 10:35:56 +02:00
Christian Tzolov
110a8d1940 refactor: downgrade unhandled notification logging from error to warn
- Change logger.error() to logger.warn() for unhandled notification methods
- Log full notification object instead of just method name for better context
- Affects McpClientSession, McpServerSession, and McpStreamableServerSession

Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
2025-08-06 08:34:30 +01:00
Yanming Zhou
7f37ddc4d7 Use Last-Event-ID instead of last-event-id
see https://html.spec.whatwg.org/multipage/server-sent-events.html#the-last-event-id-header

Signed-off-by: Yanming Zhou <zhouyanming@gmail.com>
2025-08-06 09:13:30 +02:00
codezkk
5aba8a0e8f fix: handle empty JSON responses in ResponseSubscribers
- Remove length check in hookOnComplete() to always emit AggregateResponseEvent
- Ensures proper completion handling regardless of response content length
- Add test for empty application/json responses with 200 OK status
2025-08-06 08:08:38 +01:00
Christian Tzolov
5e035ea255 fix: add backward compatibility for MCP servers returning older protocol versions
- Add ProtocolVersions interface with version constants
- Change protocolVersion() to protocolVersions() returning List<String>
- Streamable HTTP clients now support both 2024-11-05 and 2025-03-26
- Fixes compatibility with MCP servers that return 2024-11-05 instead of 2025-03-26

Resolves #436
Related to #438

Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
2025-08-04 15:27:43 +02:00
Yanming Zhou
577952d1ee Fix typo 2025-08-01 19:46:08 +02:00
Christian Tzolov
3e4d5dedaf Update copyright headers to 2025 and clean up code
- Add copyright headers to files missing them
- Add blank lines after copyright headers for consistency
- Remove unused imports in test files
- Remove unnecessary keep-alive warning logs in WebFlux and WebMvc transport providers

Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
2025-08-01 16:06:13 +01:00
Christian Tzolov
bf2c8c955c Next development version
Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
2025-07-31 03:34:02 +02:00
Christian Tzolov
28edd3630a revert
Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
2025-07-31 02:29:41 +02:00
Christian Tzolov
8dcb21773f Next development version
Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
2025-07-31 02:26:59 +02:00
Christian Tzolov
b4887ad8e1 Release version 0.11.0
Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
2025-07-31 02:25:34 +02:00
Christian Tzolov
1664401d0c Next development version
Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
2025-07-31 02:10:22 +02:00
Christian Tzolov
bead5321e3 Next development version
Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
2025-07-31 02:08:14 +02:00
Christian Tzolov
6384d794b1 Release version 0.11.0
Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
2025-07-31 02:07:49 +02:00
Christian Tzolov
8f03a40540 feat: add WebMVC and HttpServlet stateless server transports
- Add WebMvcStatelessServerTransport for mcp-spring-webmvc module
- Add HttpServletStatelessServerTransport for mcp module
- Implement builder patterns for AsyncToolSpecification and SyncToolSpecification
- Create AbstractStatelessIntegrationTests base class for shared test functionality
- Add integration tests for both transport implementations

Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
2025-07-31 00:48:34 +02:00
Christian Tzolov
9d58621918
feat: implement MCP protocol version per transport support (#404)
- Add protocolVersion() method to transport and transport provider interfaces and implementations
- Replace hardcoded HTTP header strings with HttpHeaders constants
- Update protocol versions to be transport-specific rather than global
- Deprecate McpSchema.LATEST_PROTOCOL_VERSION in favor of transport-specific versions
- Standardize header names: MCP-Protocol-Version, mcp-session-id, last-event-id
- Update clients and servers to use transport.protocolVersion() for initialization
- Refactor tests to use transport-specific protocol versions
- Include MCP-Protocol-Version header in all GET/POST/DELETE requests
- Update WebClientStreamableHttpTransport, WebFluxSseClientTransport,
  HttpClientSseClientTransport, and HttpClientStreamableHttpTransport

Related to #398 , #363 , #250

Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
2025-07-30 23:54:28 +02:00
Ilayaperumal Gopinathan
67de84b300 Expose the client initialization result
- Add getters for both MCP Sync/Async clients

Signed-off-by: Ilayaperumal Gopinathan <ilayaperumal.gopinathan@broadcom.com>
2025-07-30 21:22:03 +02:00
Christian Tzolov
ee2c891cca feat: implement MCP-compliant keep-alive functionality for server transports
- Add KeepAliveScheduler utility class for configurable periodic session pings
- Integrate keep-alive support in WebFlux, WebMVC, and HttpServlet SSE transport providers
- Add keepAliveInterval configuration option to all transport provider builders
- Deprecate existing constructors in favor of builder pattern with enhanced configuration
- Update graceful shutdown to properly clean up keep-alive schedulers
- Add unit tests for KeepAliveScheduler functionality

Implements MCP specification recommendations for connection health detection:
- Configurable ping frequency to suit different network environments
- Optional keep-alive (disabled by default) to avoid excessive network overhead
- Proper resource cleanup to prevent connection leaks

https://modelcontextprotocol.io/specification/2025-06-18/basic/utilities/ping#implementation-considerations

Resolves: #414, #158
Replaces #353

Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
2025-07-30 20:40:31 +02:00
Daniel Garnier-Moiroux
ae2fc8683b Introduce HttpRequest.Builder customizer for HttpClient-based transport
- Minor improvement: speed up HttpClientSseClientTransportTests by
  reusing the MCP Server container across tests.
- Minor improvement: rename "messageSink" to "deliveredSink" in
  HttpClientStreamableHttpTransport#sendMessage
2025-07-30 20:20:23 +02:00
Zachary German
bde1b6beec
feat: HttpServlet Streamable HTTP server implementation (#290)
Implementation of the Streamable HTTP transport provider for the Servlet API.

---
Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
Co-authored-by: Christian Tzolov <christian.tzolov@broadcom.com>
Co-authored-by: Zachary German <zdgerman@amazon.com>
2025-07-30 17:58:28 +02:00
Christian Tzolov
73515346ca
feat: Add Spring WebMVC streamable server transport provider (#425)
- Add WebMvcStreamableServerTransportProvider with SSE support for streamable sessions
- Support GET, POST, DELETE endpoints for MCP protocol operations
- Implement thread-safe SSE operations using ReentrantLock in WebMvcSseServerTransportProvider
- Add test infrastructure with AbstractMcpClientServerIntegrationTests
  - Refactor WebMvcStreamableIntegrationTests to use parameterized tests
  - Support testing with both HttpClient and WebFlux transports
- Add streamable transport tests for both async and sync server modes
- Refactor existing WebMVC SSE integration tests to use shared test base
- Add error handling improvements in McpStreamableServerSession
- Update dependencies: add json-unit-assertj for enhanced JSON testing
- Reorganize POM dependencies and add mcp-spring-webflux test dependency
- Wrap handler invocations with Mono.defer for lazy evaluation
   - Wrap consumer, tool, resource, prompt, and completion handler calls with Mono.defer()
   - Ensures proper lazy evaluation and error handling in reactive streams

Related to #72

Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
Signed-off-by: Dariusz Jędrzejczyk <dariusz.jedrzejczyk@broadcom.com>
Co-authored-by: Dariusz Jędrzejczyk <dariusz.jedrzejczyk@broadcom.com>
2025-07-30 14:38:16 +02:00
Dariusz Jędrzejczyk
a8f5a3fb4f
feat: add Streamable HTTP Server abstractions and implement WebFlux transport provider (#420)
- Add WebFluxStreamableServerTransportProvider for streamable HTTP sessions
- Add WebFluxStatelessServerTransport for stateless HTTP MCP servers
  - Add McpStatelessServerFeatures, McpStatelessServerHandler, McpStatelessRequestHandler, McpStatelessNotificationHandler
- Refactor server architecture to support multiple transport categories:
   streamable, single-session, stateless
- Introduce McpTransportContext for transport-level metadata extraction
- Add session management capabilities for streamable HTTP connections
- Update MCP protocol version to 2025-03-26
- Add test coverage for new transport implementations
- Implement integration tests for both stateless and streamable transports

Signed-off-by: Dariusz Jędrzejczyk <dariusz.jedrzejczyk@broadcom.com>
Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
Co-authored-by: Christian Tzolov <christian.tzolov@broadcom.com>
2025-07-30 13:41:18 +02:00
Christian Tzolov
c3a0b1855a fix: improve SSE event handling to gracefully ignore unrecognized events (#423)
- Replace McpError exceptions with debug/warning logs for unrecognized SSE event types
- Continue processing instead of failing when encountering unknown SSE events
- Update transport implementations:
  - WebClientStreamableHttpTransport: return empty tuple instead of throwing
  - WebFluxSseClientTransport: complete stream instead of erroring
  - HttpClientSseClientTransport: call sink.success() instead of sink.error()
  - HttpClientStreamableHttpTransport: return empty Flux for unknown events

This improves client resilience when servers send non-standard or future SSE event types.

Resolves #272 , #223 , #93, #421

Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
2025-07-25 12:13:37 +02:00
Christian Tzolov
4937fc1ef5 fix: improve compatibility with non-compliant MCP servers (#413)
Addresses issues with servers like Shopify that violate MCP/HTTP specs:
- Prioritize application/json in Accept headers to fix content-type issues
- Handle non-compliant notification non-empty responses
- Add status code validation and null safety improvements

Resolves #406

Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
2025-07-22 11:18:32 +02:00
Christian Tzolov
1e93776354 feat: enforce MCP request ID validation requirements
Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
2025-07-18 22:26:42 +02:00
Christian Tzolov
53f7b77edf refactor: Replace Map<String, Object> with CallToolRequest in StructuredOutputCallToolHandler
Follow up to #357 to update tool call handler signature from Map<String, Object>
to McpSchema.CallToolRequest for consistency with changes in #375.

- Change BiFunction parameter from Map<String, Object> to McpSchema.CallToolRequest for better type safety
- Update method signature to accept CallToolRequest instead of raw arguments map
- Replace toolSpecification.call() with toolSpecification.callHandler()
- Migrate to builder pattern for AsyncToolSpecification construction

Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
2025-07-18 07:32:18 +02:00
JiHwan Oh
b04c30b60e feat: Add progress notification support for MCP operations (#407)
Implement progress tracking for long-running operations with:
- New ProgressNotification schema and client/server support
- Progress consumer handlers in sync/async client builders
- Server exchange methods for sending progress updates
- Comprehensive integration tests
- Backwards compatibility maintained
- Add additional tests

Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
2025-07-17 13:26:04 +02:00
Anurag Pant
87cdaf883a feat: Add _meta support to MCPSchema (#368)
- Add _meta field to all MCP schema records for extensible metadata support
- Introduce Result and Notification sealed interfaces for better type organization
- Update Request interface to include SubscribeRequest and UnsubscribeRequest
- Add backwards-compatible constructors for existing record types
- Enhance test coverage for metadata field functionality

Breaking change: Modifyibng the Request seald inteface is a breaking change.
2025-07-17 09:18:08 +02:00
Christian Tzolov
8d71b76b21 refactor: reformat McpSchema.java (#392)
- Remove unused imports (CallToolResult, TextContent)
- Standardize code formatting and indentation throughout
- Adjust formatter comments positioning
- Improve readability of record definitions and builder classes
- Add comprehensive JavaDoc documentation to McpSchema

Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
2025-07-15 22:11:34 +02:00
Sun Yuhan
333a60b37e cleanup: Cleaned up some unused imports. (#358)
Signed-off-by: Sun Yuhan <sunyuhan1998@users.noreply.github.com>
2025-07-14 11:14:17 +02:00
Christian Tzolov
8a2f97f1b1 feat: add structured output support for MCP tools (#357)
- Add JsonSchemaValidator interface and DefaultJsonSchemaValidator implementation
 - put the JsonSchemaValidator classes into a dedicated spec package
 - add schema caching to DefaultJsonSchemaValidator for better performance
- Extend Tool schema to support outputSchema field for defining expected output structure
- Add structuredContent field to CallToolResult for validated structured responses
- Implement automatic validation of tool outputs against their defined schemas
- Add comprehensive test coverage for structured output validation scenarios
- Add json-schema-validator and json-unit-assertj dependencies for validation and testing
- Update McpServer builders to accept custom JsonSchemaValidator instances
- Ensure backward compatibility with existing tools without output schemas

This implements the MCP specification requirement that tools with output schemas
must provide structured results conforming to those schemas, with automatic
validation and error handling for non-conforming outputs.
https://modelcontextprotocol.io/specification/2025-06-18/server/tools#structured-content

Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
2025-07-13 15:29:56 +02:00
Christian Tzolov
b678de6514 fix: improve error handling in HttpClientSseClientTransport and add test
- Include response body in error messages for better debugging
- Change sendHttpPost return type from HttpResponse<Void> to HttpResponse<String>
- Use BodyHandlers.ofString() instead of discarding response body
- Add testErrorOnBogusMessage test to verify error handling for invalid JSON-RPC messages
- Test validates that malformed messages return 400 status with descriptive error message

Replace #361

Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>

Co-authored-by: jkma <jkma@trip.com>
2025-07-13 11:22:57 +02:00
Sun Yuhan
d282d40a38 refactor: replace string concatenation with {} placeholders in log statements
Signed-off-by: Sun Yuhan <sunyuhan1998@users.noreply.github.com>
2025-07-11 19:42:03 +02:00
bzsurbhi
dc477fc522 feat: add context support to CompleteRequest for dependent completions
- Add CompleteContext record to support contextual completion scenarios
- Update CompleteRequest to include context and meta fields with backward-compatible constructors
- Modify McpAsyncServer to extract and pass context/meta from request parameters
- Add tests for context-aware completions including dependent scenarios
- Maintain backward compatibility for existing completion handlers

Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
2025-07-11 15:29:23 +02:00
Christian Tzolov
c8c08dd1a6 Add legacy constructors for backwards compatibility in McpSchema record types
As a followup of #372 introduce new constructors to several record types
  in McpSchema (Resource, ResourceTemplate, Prompt, PromptArgument, Tool,
  PromptReference, and ResourceLink) to improve backwards compatibility
  with previous code versions.

Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
2025-07-11 13:47:47 +02:00
Christian Tzolov
901175e14f refactor: deprecate tool spec's arguments-only handler in favor of CallToolRequest (#375)
Tool handlers now receive CallToolRequest instead of raw arguments to
enable access to additional metadata parameters like progressToken

- Deprecate  handlers that take only Map<String, Object> arguments
- Introduce new  handlers that receive the full CallToolRequest object
- Maintain backward compatibility with deprecated call handlers
- Enhance API to provide access to complete tool request context beyond just arguments
- Add builder pattern for AsyncToolSpecification and SyncToolSpecification
- Add duplicate tool name validation during server building and runtime registration
- Update all test files to use new callTool handlers and builder pattern
- Add test coverage for new builder functionality and CallToolRequest handling

Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
2025-07-11 11:43:43 +02:00
Dariusz Jędrzejczyk
95df67ec05 Fix non-OK HTTP POST responses handling (#374)
Currently, JDK HttpClient SSE implementation incorrectly handles a
non-2xx HTTP response code for POST. Instead of immediately failing the
caller, it ignores the issue and the user awaits until the timeout kicks
in.

Set HttpClient to use HTTP/1.1 version explicitly for tests

A related problem happened with the WebClient Streamable HTTP
implementation, where the error was swallowed for non-400 responses.

Signed-off-by: Dariusz Jędrzejczyk <dariusz.jedrzejczyk@broadcom.com>
2025-07-11 08:21:01 +02:00