Skip to content

Commit ebb9764

Browse files
OrGivatitzolov
authored andcommitted
feat: implement ping request handler in MCP async client (#203)
- Add ping request handler that responds with empty Map instead of null - Ensure compliance with MCP protocol requirement for ping responses - Add test for ping message request handling Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
1 parent 1cbace3 commit ebb9764

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

mcp/src/main/java/io/modelcontextprotocol/client/McpAsyncClient.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,9 @@ public class McpAsyncClient {
187187
// Request Handlers
188188
Map<String, RequestHandler<?>> requestHandlers = new HashMap<>();
189189

190+
// Ping MUST respond with an empty data, but not NULL response.
191+
requestHandlers.put(McpSchema.METHOD_PING, params -> Mono.just(Map.of()));
192+
190193
// Roots List Request Handler
191194
if (this.clientCapabilities.roots() != null) {
192195
requestHandlers.put(McpSchema.METHOD_ROOTS_LIST, rootsListRequestHandler());

mcp/src/test/java/io/modelcontextprotocol/client/McpAsyncClientResponseHandlerTests.java

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -525,4 +525,30 @@ void testElicitationCreateRequestHandlingWithNullHandler() {
525525
.hasMessage("Elicitation handler must not be null when client capabilities include elicitation");
526526
}
527527

528-
}
528+
@Test
529+
void testPingMessageRequestHandling() {
530+
MockMcpClientTransport transport = initializationEnabledTransport();
531+
532+
McpAsyncClient asyncMcpClient = McpClient.async(transport).build();
533+
534+
assertThat(asyncMcpClient.initialize().block()).isNotNull();
535+
536+
// Simulate incoming ping request from server
537+
McpSchema.JSONRPCRequest pingRequest = new McpSchema.JSONRPCRequest(McpSchema.JSONRPC_VERSION,
538+
McpSchema.METHOD_PING, "ping-id", null);
539+
transport.simulateIncomingMessage(pingRequest);
540+
541+
// Verify response
542+
McpSchema.JSONRPCMessage sentMessage = transport.getLastSentMessage();
543+
assertThat(sentMessage).isInstanceOf(McpSchema.JSONRPCResponse.class);
544+
545+
McpSchema.JSONRPCResponse response = (McpSchema.JSONRPCResponse) sentMessage;
546+
assertThat(response.id()).isEqualTo("ping-id");
547+
assertThat(response.error()).isNull();
548+
assertThat(response.result()).isInstanceOf(Map.class);
549+
assertThat(((Map<?, ?>) response.result())).isEmpty();
550+
551+
asyncMcpClient.closeGracefully();
552+
}
553+
554+
}

0 commit comments

Comments
 (0)