Refactoring and add semantic cache

This commit is contained in:
shahondin1624
2026-02-15 17:09:55 +01:00
parent a717b21d26
commit a8b82e93c1
9 changed files with 62 additions and 66 deletions

View File

@@ -33,5 +33,5 @@ public interface McpTool {
return null; return null;
} }
McpSchema.CallToolResult call(McpSchema.CallToolRequest request, Map<String, Object> arguments); McpSchema.CallToolResult call(final McpSchema.CallToolRequest request, final Map<String, Object> arguments);
} }

View File

@@ -4,8 +4,6 @@ import io.modelcontextprotocol.spec.McpSchema;
import mcp.tools.helper.AnnotationsBuilder; import mcp.tools.helper.AnnotationsBuilder;
import mcp.tools.helper.CallToolResultBuilder; import mcp.tools.helper.CallToolResultBuilder;
import mcp.tools.helper.ToolQueryValidator; import mcp.tools.helper.ToolQueryValidator;
import mcp.util.Err;
import mcp.util.Ok;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@@ -18,7 +16,7 @@ public abstract class McpValidatedTool implements McpTool {
public abstract McpSchema.CallToolResult callValidated(McpSchema.CallToolRequest request, Map<String, Object> arguments) throws Exception; public abstract McpSchema.CallToolResult callValidated(McpSchema.CallToolRequest request, Map<String, Object> arguments) throws Exception;
@Override @Override
public final McpSchema.CallToolResult call(McpSchema.CallToolRequest request, Map<String, Object> arguments) { public final McpSchema.CallToolResult call(final McpSchema.CallToolRequest request, final Map<String, Object> arguments) {
final var result = validator.validate(inputSchema(), arguments); final var result = validator.validate(inputSchema(), arguments);
if (result.isError()) { if (result.isError()) {
logger.warn("Validation failed for tool {}: {}", name(), result.err().unwrap().getMessage()); logger.warn("Validation failed for tool {}: {}", name(), result.err().unwrap().getMessage());
@@ -62,22 +60,22 @@ public abstract class McpValidatedTool implements McpTool {
return false; return false;
} }
protected McpSchema.CallToolResult success(String text) { protected McpSchema.CallToolResult success(final String text) {
return new CallToolResultBuilder().addText(text).build(); return new CallToolResultBuilder().addText(text).build();
} }
protected McpSchema.CallToolResult success(String text, Map<String, Object> structured) { protected McpSchema.CallToolResult success(final String text, final Map<String, Object> structured) {
return new CallToolResultBuilder() return new CallToolResultBuilder()
.addText(text) .addText(text)
.structuredContent(structured) .structuredContent(structured)
.build(); .build();
} }
protected McpSchema.CallToolResult successResult(Object resultValue) { protected McpSchema.CallToolResult successResult(final Object resultValue) {
return success(String.valueOf(resultValue), Map.of("result", resultValue)); return success(String.valueOf(resultValue), Map.of("result", resultValue));
} }
protected McpSchema.CallToolResult error(String text) { protected McpSchema.CallToolResult error(final String text) {
return new CallToolResultBuilder().isError(true).addText(text).build(); return new CallToolResultBuilder().isError(true).addText(text).build();
} }
} }

View File

@@ -10,32 +10,32 @@ public class AnnotationsBuilder {
private Boolean openWorldHint; private Boolean openWorldHint;
private Boolean returnDirect; private Boolean returnDirect;
public AnnotationsBuilder title(String title) { public AnnotationsBuilder title(final String title) {
this.title = title; this.title = title;
return this; return this;
} }
public AnnotationsBuilder readOnlyHint(Boolean readOnlyHint) { public AnnotationsBuilder readOnlyHint(final Boolean readOnlyHint) {
this.readOnlyHint = readOnlyHint; this.readOnlyHint = readOnlyHint;
return this; return this;
} }
public AnnotationsBuilder destructiveHint(Boolean destructiveHint) { public AnnotationsBuilder destructiveHint(final Boolean destructiveHint) {
this.destructiveHint = destructiveHint; this.destructiveHint = destructiveHint;
return this; return this;
} }
public AnnotationsBuilder idempotentHint(Boolean idempotentHint) { public AnnotationsBuilder idempotentHint(final Boolean idempotentHint) {
this.idempotentHint = idempotentHint; this.idempotentHint = idempotentHint;
return this; return this;
} }
public AnnotationsBuilder openWorldHint(Boolean openWorldHint) { public AnnotationsBuilder openWorldHint(final Boolean openWorldHint) {
this.openWorldHint = openWorldHint; this.openWorldHint = openWorldHint;
return this; return this;
} }
public AnnotationsBuilder returnDirect(Boolean returnDirect) { public AnnotationsBuilder returnDirect(final Boolean returnDirect) {
this.returnDirect = returnDirect; this.returnDirect = returnDirect;
return this; return this;
} }

View File

@@ -11,22 +11,22 @@ public class CallToolResultBuilder {
private Map<String, Object> meta; private Map<String, Object> meta;
private Map<String, Object> structuredContent; private Map<String, Object> structuredContent;
public CallToolResultBuilder isError(boolean isError) { public CallToolResultBuilder isError(final boolean isError) {
this.isError = isError; this.isError = isError;
return this; return this;
} }
public CallToolResultBuilder addText(String text) { public CallToolResultBuilder addText(final String text) {
this.content.add(new McpSchema.TextContent(text)); this.content.add(new McpSchema.TextContent(text));
return this; return this;
} }
public CallToolResultBuilder meta(Map<String, Object> meta) { public CallToolResultBuilder meta(final Map<String, Object> meta) {
this.meta = meta; this.meta = meta;
return this; return this;
} }
public CallToolResultBuilder structuredContent(Map<String, Object> structuredContent) { public CallToolResultBuilder structuredContent(final Map<String, Object> structuredContent) {
this.structuredContent = structuredContent; this.structuredContent = structuredContent;
return this; return this;
} }

View File

@@ -15,5 +15,5 @@ public interface QueryValidator {
* @param arguments The tool arguments to validate. * @param arguments The tool arguments to validate.
* @return A {@link Result} indicating success (Ok(null)) or failure (Err(exception)). * @return A {@link Result} indicating success (Ok(null)) or failure (Err(exception)).
*/ */
Result<Void, Exception> validate(McpSchema.JsonSchema schema, Map<String, Object> arguments); Result<Void, Exception> validate(final McpSchema.JsonSchema schema, final Map<String, Object> arguments);
} }

View File

@@ -14,13 +14,13 @@ public class SchemaBuilder {
private final Map<String, Object> definitions = new HashMap<>(); private final Map<String, Object> definitions = new HashMap<>();
private final Map<String, Object> defs = new HashMap<>(); private final Map<String, Object> defs = new HashMap<>();
public SchemaBuilder type(String type) { public SchemaBuilder type(final String type) {
this.type = type; this.type = type;
return this; return this;
} }
public SchemaBuilder addProperty(String name, String type, String description) { public SchemaBuilder addProperty(final String name, final String type, final String description) {
Map<String, Object> prop = new HashMap<>(); final Map<String, Object> prop = new HashMap<>();
prop.put("type", type); prop.put("type", type);
if (description != null) { if (description != null) {
prop.put("description", description); prop.put("description", description);
@@ -29,17 +29,17 @@ public class SchemaBuilder {
return this; return this;
} }
public SchemaBuilder required(String... names) { public SchemaBuilder required(final String... names) {
required.addAll(Arrays.asList(names)); required.addAll(Arrays.asList(names));
return this; return this;
} }
public SchemaBuilder additionalProperties(Boolean additionalProperties) { public SchemaBuilder additionalProperties(final Boolean additionalProperties) {
this.additionalProperties = additionalProperties; this.additionalProperties = additionalProperties;
return this; return this;
} }
public SchemaBuilder returns(String type, String description) { public SchemaBuilder returns(final String type, final String description) {
return this.type("object") return this.type("object")
.addProperty("result", type, description); .addProperty("result", type, description);
} }
@@ -56,7 +56,7 @@ public class SchemaBuilder {
} }
public Map<String, Object> buildMap() { public Map<String, Object> buildMap() {
Map<String, Object> map = new HashMap<>(); final Map<String, Object> map = new HashMap<>();
map.put("type", type); map.put("type", type);
if (!properties.isEmpty()) { if (!properties.isEmpty()) {
map.put("properties", properties); map.put("properties", properties);

View File

@@ -22,7 +22,7 @@ public class ToolQueryValidator {
* *
* @param validator The validator to add. * @param validator The validator to add.
*/ */
public void addValidator(QueryValidator validator) { public void addValidator(final QueryValidator validator) {
validators.add(validator); validators.add(validator);
} }
@@ -33,12 +33,12 @@ public class ToolQueryValidator {
* @param arguments The arguments passed to the tool. * @param arguments The arguments passed to the tool.
* @return A {@link Result} indicating success or failure. * @return A {@link Result} indicating success or failure.
*/ */
public Result<Void, Exception> validate(McpSchema.JsonSchema schema, Map<String, Object> arguments) { public Result<Void, Exception> validate(final McpSchema.JsonSchema schema, final Map<String, Object> arguments) {
if (schema == null) { if (schema == null) {
return Result.Ok(null); return Result.Ok(null);
} }
for (QueryValidator validator : validators) { for (final QueryValidator validator : validators) {
Result<Void, Exception> result = validator.validate(schema, arguments); final Result<Void, Exception> result = validator.validate(schema, arguments);
if (result.isError()) { if (result.isError()) {
return result; return result;
} }
@@ -51,32 +51,30 @@ public class ToolQueryValidator {
*/ */
private static class SchemaConformityValidator implements QueryValidator { private static class SchemaConformityValidator implements QueryValidator {
@Override @Override
public Result<Void, Exception> validate(McpSchema.JsonSchema schema, Map<String, Object> arguments) { public Result<Void, Exception> validate(final McpSchema.JsonSchema schema, final Map<String, Object> arguments) {
// Check required fields final List<String> requiredFields = schema.required();
List<String> requiredFields = schema.required();
if (requiredFields != null) { if (requiredFields != null) {
for (String field : requiredFields) { for (final String field : requiredFields) {
if (arguments == null || !arguments.containsKey(field) || arguments.get(field) == null) { if (arguments == null || !arguments.containsKey(field) || arguments.get(field) == null) {
return Result.Err(new IllegalArgumentException("Missing required argument: " + field)); return Result.Err(new IllegalArgumentException("Missing required argument: " + field));
} }
} }
} }
// Check types if properties are defined final Map<String, Object> properties = schema.properties();
Map<String, Object> properties = schema.properties();
if (properties != null && arguments != null) { if (properties != null && arguments != null) {
for (Map.Entry<String, Object> entry : arguments.entrySet()) { for (final Map.Entry<String, Object> entry : arguments.entrySet()) {
String argName = entry.getKey(); final String argName = entry.getKey();
Object argValue = entry.getValue(); final Object argValue = entry.getValue();
if (properties.containsKey(argName)) { if (properties.containsKey(argName)) {
Object propSchemaObj = properties.get(argName); final Object propSchemaObj = properties.get(argName);
if (propSchemaObj instanceof Map) { if (propSchemaObj instanceof Map) {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Map<String, Object> propSchema = (Map<String, Object>) propSchemaObj; final Map<String, Object> propSchema = (Map<String, Object>) propSchemaObj;
Object expectedType = propSchema.get("type"); final Object expectedType = propSchema.get("type");
if (expectedType instanceof String) { if (expectedType instanceof String) {
Result<Void, Exception> typeResult = validateType((String) expectedType, argValue, argName); final Result<Void, Exception> typeResult = validateType((String) expectedType, argValue, argName);
if (typeResult.isError()) { if (typeResult.isError()) {
return typeResult; return typeResult;
} }
@@ -89,12 +87,12 @@ public class ToolQueryValidator {
return Result.Ok(null); return Result.Ok(null);
} }
private Result<Void, Exception> validateType(String expectedType, Object value, String fieldName) { private Result<Void, Exception> validateType(final String expectedType, final Object value, final String fieldName) {
if (value == null) { if (value == null) {
return Result.Ok(null); return Result.Ok(null);
} }
boolean valid = switch (expectedType) { final boolean valid = switch (expectedType) {
case "string" -> value instanceof String; case "string" -> value instanceof String;
case "number" -> value instanceof Number; case "number" -> value instanceof Number;
case "integer" -> isInteger(value); case "integer" -> isInteger(value);
@@ -112,7 +110,7 @@ public class ToolQueryValidator {
return Result.Ok(null); return Result.Ok(null);
} }
private boolean isInteger(Object value) { private boolean isInteger(final Object value) {
if (value instanceof Integer || value instanceof Long || value instanceof Short || value instanceof Byte) { if (value instanceof Integer || value instanceof Long || value instanceof Short || value instanceof Byte) {
return true; return true;
} }

View File

@@ -20,16 +20,16 @@ public sealed interface Option<T> permits Some, None {
}; };
} }
default T unwrapOr(T defaultValue) { default T unwrapOr(final T defaultValue) {
return isSome() ? unwrap() : defaultValue; return isSome() ? unwrap() : defaultValue;
} }
default T unwrapOrElse(Supplier<? extends T> supplier) { default T unwrapOrElse(final Supplier<? extends T> supplier) {
return isSome() ? unwrap() : supplier.get(); return isSome() ? unwrap() : supplier.get();
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
default <R> Option<R> map(Function<? super T, ? extends R> mapper) { default <R> Option<R> map(final Function<? super T, ? extends R> mapper) {
return switch (this) { return switch (this) {
case Some<T> some -> new Some<>(mapper.apply(some.value())); case Some<T> some -> new Some<>(mapper.apply(some.value()));
case None<T> none -> (None<R>) none; case None<T> none -> (None<R>) none;
@@ -37,7 +37,7 @@ public sealed interface Option<T> permits Some, None {
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
default <R> Option<R> flatMap(Function<? super T, ? extends Option<R>> mapper) { default <R> Option<R> flatMap(final Function<? super T, ? extends Option<R>> mapper) {
return switch (this) { return switch (this) {
case Some<T> some -> mapper.apply(some.value()); case Some<T> some -> mapper.apply(some.value());
case None<T> none -> (None<R>) none; case None<T> none -> (None<R>) none;
@@ -48,15 +48,15 @@ public sealed interface Option<T> permits Some, None {
return isSome() ? Optional.of(unwrap()) : Optional.empty(); return isSome() ? Optional.of(unwrap()) : Optional.empty();
} }
default Option<T> filter(java.util.function.Predicate<? super T> predicate) { default Option<T> filter(final java.util.function.Predicate<? super T> predicate) {
return isSome() && predicate.test(unwrap()) ? this : none(); return isSome() && predicate.test(unwrap()) ? this : none();
} }
default Option<T> or(Option<T> alternative) { default Option<T> or(final Option<T> alternative) {
return isSome() ? this : alternative; return isSome() ? this : alternative;
} }
default Option<T> orElse(Supplier<? extends Option<T>> supplier) { default Option<T> orElse(final Supplier<? extends Option<T>> supplier) {
return isSome() ? this : supplier.get(); return isSome() ? this : supplier.get();
} }
@@ -64,11 +64,11 @@ public sealed interface Option<T> permits Some, None {
return isSome() ? Result.Ok(unwrap()) : Result.Err(error); return isSome() ? Result.Ok(unwrap()) : Result.Err(error);
} }
default <E extends Throwable> Result<T, E> okOrElse(Supplier<? extends E> errorSupplier) { default <E extends Throwable> Result<T, E> okOrElse(final Supplier<? extends E> errorSupplier) {
return isSome() ? Result.Ok(unwrap()) : Result.Err(errorSupplier.get()); return isSome() ? Result.Ok(unwrap()) : Result.Err(errorSupplier.get());
} }
static <T> Option<T> some(T value) { static <T> Option<T> some(final T value) {
return new Some<>(value); return new Some<>(value);
} }
@@ -76,7 +76,7 @@ public sealed interface Option<T> permits Some, None {
return new None<>(); return new None<>();
} }
static <T> Option<T> ofNullable(T value) { static <T> Option<T> ofNullable(final T value) {
return value == null ? none() : some(value); return value == null ? none() : some(value);
} }
} }

View File

@@ -19,10 +19,10 @@ public sealed interface Result<E, T extends Throwable> permits Err, Ok {
}; };
} }
default E unwrapOrElse(E defaultValue) { default E unwrapOrElse(final E defaultValue) {
try { try {
return isError() ? defaultValue : unwrap(); return isError() ? defaultValue : unwrap();
} catch (Throwable e) { } catch (final Throwable e) {
return defaultValue; return defaultValue;
} }
} }
@@ -30,7 +30,7 @@ public sealed interface Result<E, T extends Throwable> permits Err, Ok {
default Optional<E> toOptional() { default Optional<E> toOptional() {
try { try {
return isError() ? Optional.empty() : Optional.of(unwrap()); return isError() ? Optional.empty() : Optional.of(unwrap());
} catch (Throwable e) { } catch (final Throwable e) {
return Optional.empty(); return Optional.empty();
} }
} }
@@ -38,19 +38,19 @@ public sealed interface Result<E, T extends Throwable> permits Err, Ok {
default Option<E> toOption() { default Option<E> toOption() {
return switch (this) { return switch (this) {
case Ok<E, T> ok -> Option.some(ok.value()); case Ok<E, T> ok -> Option.some(ok.value());
case Err<E, T> err -> Option.none(); case Err<E, T> ignored -> Option.none();
}; };
} }
default Option<T> err() { default Option<T> err() {
return switch (this) { return switch (this) {
case Ok<E, T> ok -> Option.none(); case Ok<E, T> ignored -> Option.none();
case Err<E, T> err -> Option.some(err.throwable()); case Err<E, T> err -> Option.some(err.throwable());
}; };
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
default <R> Result<R, T> map(java.util.function.Function<? super E, ? extends R> mapper) { default <R> Result<R, T> map(final java.util.function.Function<? super E, ? extends R> mapper) {
return switch (this) { return switch (this) {
case Ok<E, T> ok -> new Ok<>(mapper.apply(ok.value())); case Ok<E, T> ok -> new Ok<>(mapper.apply(ok.value()));
case Err<E, T> err -> (Err<R, T>) err; case Err<E, T> err -> (Err<R, T>) err;
@@ -58,7 +58,7 @@ public sealed interface Result<E, T extends Throwable> permits Err, Ok {
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
default <R> Result<R, T> flatMap(java.util.function.Function<? super E, ? extends Result<R, T>> mapper) { default <R> Result<R, T> flatMap(final java.util.function.Function<? super E, ? extends Result<R, T>> mapper) {
return switch (this) { return switch (this) {
case Ok<E, T> ok -> mapper.apply(ok.value()); case Ok<E, T> ok -> mapper.apply(ok.value());
case Err<E, T> err -> (Err<R, T>) err; case Err<E, T> err -> (Err<R, T>) err;
@@ -66,18 +66,18 @@ public sealed interface Result<E, T extends Throwable> permits Err, Ok {
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
default <F extends Throwable> Result<E, F> mapError(java.util.function.Function<? super T, ? extends F> mapper) { default <F extends Throwable> Result<E, F> mapError(final java.util.function.Function<? super T, ? extends F> mapper) {
return switch (this) { return switch (this) {
case Ok<E, T> ok -> (Ok<E, F>) ok; case Ok<E, T> ok -> (Ok<E, F>) ok;
case Err<E, T> err -> new Err<>(mapper.apply(err.throwable())); case Err<E, T> err -> new Err<>(mapper.apply(err.throwable()));
}; };
} }
static <E, T extends Throwable> Result<E, T> Ok(E value) { static <E, T extends Throwable> Result<E, T> Ok(final E value) {
return new Ok<>(value); return new Ok<>(value);
} }
static <E, T extends Throwable> Result<E, T> Err(T throwable) { static <E, T extends Throwable> Result<E, T> Err(final T throwable) {
return new Err<>(throwable); return new Err<>(throwable);
} }
} }