feat: add ping functionality to MCP server exchanges (#347)

- Add ping() method to McpAsyncServerExchange that sends ping requests to clients
- Add ping() method to McpSyncServerExchange as synchronous wrapper
- Add OBJECT_TYPE_REF constant for ping response type handling
- Create McpSyncServerExchangeTests.java with full test coverage
- Add ping integration tests across WebFlux, WebMVC, and HttpServlet transports

Follow up of #203

Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
This commit is contained in:
Christian Tzolov 2025-06-28 09:22:22 +02:00
commit d7bcb237b8
2 changed files with 1040 additions and 6 deletions

View file

@ -42,6 +42,9 @@ public class McpAsyncServerExchange {
private static final TypeReference<McpSchema.ElicitResult> ELICITATION_RESULT_TYPE_REF = new TypeReference<>() {
};
public static final TypeReference<Object> OBJECT_TYPE_REF = new TypeReference<>() {
};
/**
* Create a new asynchronous exchange with the client.
* @param session The server session representing a 1-1 interaction.
@ -132,9 +135,9 @@ public class McpAsyncServerExchange {
// @formatter:off
return this.listRoots(McpSchema.FIRST_PAGE)
.expand(result -> (result.nextCursor() != null) ?
.expand(result -> (result.nextCursor() != null) ?
this.listRoots(result.nextCursor()) : Mono.empty())
.reduce(new McpSchema.ListRootsResult(new ArrayList<>(), null),
.reduce(new McpSchema.ListRootsResult(new ArrayList<>(), null),
(allRootsResult, result) -> {
allRootsResult.roots().addAll(result.roots());
return allRootsResult;
@ -174,6 +177,14 @@ public class McpAsyncServerExchange {
});
}
/**
* Sends a ping request to the client.
* @return A Mono that completes with clients's ping response
*/
public Mono<Object> ping() {
return this.session.sendRequest(McpSchema.METHOD_PING, null, OBJECT_TYPE_REF);
}
/**
* Set the minimum logging level for the client. Messages below this level will be
* filtered out.

View file

@ -5,7 +5,6 @@
package io.modelcontextprotocol.server;
import io.modelcontextprotocol.spec.McpSchema;
import io.modelcontextprotocol.spec.McpSchema.LoggingLevel;
import io.modelcontextprotocol.spec.McpSchema.LoggingMessageNotification;
/**
@ -108,4 +107,12 @@ public class McpSyncServerExchange {
this.exchange.loggingNotification(loggingMessageNotification).block();
}
/**
* Sends a ping request to the client.
* @return A Mono that completes with clients's ping response
*/
public void ping() {
this.exchange.ping().block();
}
}