feat: enforce sampling handler presence and add CreateMessageResult builder

Improves error handling by enforcing sampling handler presence when sampling capabilities are enabled. Adds a builder pattern for CreateMessageResult to improve API ergonomics.
This commit is contained in:
Christian Tzolov 2025-01-02 18:19:33 +01:00
commit 51b75dca19
2 changed files with 64 additions and 28 deletions

View file

@ -160,7 +160,10 @@ public class McpAsyncClient {
}
// Sampling Handler
if (samplingHandler != null && this.clientCapabilities.sampling() != null) {
if (this.clientCapabilities.sampling() != null) {
if (samplingHandler == null) {
throw new McpError("Sampling handler must not be null when client capabilities include sampling");
}
this.samplingHandler = samplingHandler;
requestHanlers.put(McpSchema.METHOD_SAMPLING_CREATE_MESSAGE, samplingCreateMessageHandler());
}

View file

@ -761,6 +761,46 @@ public class McpSchema {
@JsonProperty("stop_sequence") STOP_SEQUENCE,
@JsonProperty("max_tokens") MAX_TOKENS
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private Role role = Role.ASSISTANT;
private Content content;
private String model;
private StopReason stopReason = StopReason.END_TURN;
public Builder role(Role role) {
this.role = role;
return this;
}
public Builder content(Content content) {
this.content = content;
return this;
}
public Builder model(String model) {
this.model = model;
return this;
}
public Builder stopReason(StopReason stopReason) {
this.stopReason = stopReason;
return this;
}
public Builder message(String message) {
this.content = new TextContent(message);
return this;
}
public CreateMessageResult build() {
return new CreateMessageResult(role, content, model, stopReason);
}
}
}// @formatter:on
// ---------------------------